Completed
Push — main ( 5e6d02...339f4c )
by
unknown
15s queued 12s
created

tests.test_ws_subscribe_books   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 65
Duplicated Lines 87.69 %

Importance

Changes 0
Metric Value
eloc 40
dl 57
loc 65
rs 10
c 0
b 0
f 0
wmc 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
import asyncio
2
from typing import List
3
4
from tests import APITestCase, MAINNET_WS_URI, WEBSOCKET_TIMEOUT_SUBSCRIPTION
5
from tradehub.websocket_client import DemexWebsocket
6
7
8
class TestWSSubscribeBooks(APITestCase):
9
10
    def test_subscribe_books_structure(self):
11
        """
12
        Check if response match expected dict structure.
13
        :return:
14
        """
15
        expect_subscription: dict = {
16
            'id': str,
17
            'result': [str]
18
        }
19
20
        expect: dict = {
21
            'channel': str,
22
            'sequence_number': int,
23
            'result': [
24
                {
25
                    'market': str,
26
                    'price': str,
27
                    'quantity': str,
28
                    'side': str,
29
                    'type': str
30
                }
31
            ]
32
        }
33
34
        # connect to websocket
35
        client = DemexWebsocket(uri=MAINNET_WS_URI)
36
        # little work around to save the response
37
        self.response: List[dict] = []
38
39
        async def on_connect():
40
            await client.subscribe_books('book', "eth1_usdc1")
41
42
        async def on_message(message: dict):
43
            # save response into self
44
            self.response.append(message)
45
46
        try:
47
            loop = asyncio.get_event_loop()
48
            loop.run_until_complete(asyncio.wait_for(client.connect(on_connect_callback=on_connect,
49
                                                                    on_receive_message_callback=on_message),
50
                                                     WEBSOCKET_TIMEOUT_SUBSCRIPTION))
51
        except asyncio.TimeoutError:
52
            loop = asyncio.get_event_loop()
53
            loop.run_until_complete(client.disconnect())
54
55
        if not self.response:
56
            raise RuntimeError("Did not receive a response.")
57
58
        self.assertTrue(len(self.response) >= 2, msg=f"Expected at least 2 messages: channel subscription and an update message")
59
60
        channel_subscription: dict = self.response[0]
61
        self.assertDictStructure(expect_subscription, channel_subscription)
62
63
        for message in self.response[1:]:
64
            self.assertDictStructure(expect, message)
65