Passed
Pull Request — main (#43)
by Switcheolytics
01:26
created

tests.test_ws_subscribe_orders   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 165
Duplicated Lines 93.33 %

Importance

Changes 0
Metric Value
eloc 114
dl 154
loc 165
rs 10
c 0
b 0
f 0
wmc 10

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, WALLET_SWTH_ETH1_AMM, WEBSOCKET_TIMEOUT_SUBSCRIPTION
5
from tradehub.websocket_client import DemexWebsocket
6
7
8
class TestWSSubscribeOrders(APITestCase):
9
10
    def test_subscribe_orders_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
            'result': [
23
                {
24
                    'order_id': str,
25
                    'block_height': int,
26
                    'triggered_block_height': int,
27
                    'address': str,
28
                    'market': str,
29
                    'side': str,
30
                    'price': str,
31
                    'quantity': str,
32
                    'available': str,
33
                    'filled': str,
34
                    'order_status': str,
35
                    'order_type': str,
36
                    'initiator': str,
37
                    'time_in_force': str,
38
                    'stop_price': str,
39
                    'trigger_type': str,
40
                    'allocated_margin_denom': str,
41
                    'allocated_margin_amount': str,
42
                    'is_liquidation': bool,
43
                    'is_post_only': bool,
44
                    'is_reduce_only': bool,
45
                    'type': str,
46
                    'block_created_at': str,
47
                    'username': str,
48
                    'id': str
49
                }
50
            ]
51
        }
52
53
        # connect to websocket
54
        client = DemexWebsocket(uri=MAINNET_WS_URI)
55
        # little work around to save the response
56
        self.response: List[dict] = []
57
58
        async def on_connect():
59
            # use AMM to be sure deterministic of which tokens the wallet holds
60
            await client.subscribe_orders('orders', WALLET_SWTH_ETH1_AMM)
61
62
        async def on_message(message: dict):
63
            # save response into self
64
            self.response.append(message)
65
66
        try:
67
            loop = asyncio.get_event_loop()
68
            loop.run_until_complete(asyncio.wait_for(client.connect(on_connect_callback=on_connect,
69
                                                                    on_receive_message_callback=on_message),
70
                                                     WEBSOCKET_TIMEOUT_SUBSCRIPTION))
71
        except asyncio.TimeoutError:
72
            loop = asyncio.get_event_loop()
73
            loop.run_until_complete(client.disconnect())
74
75
        if not self.response:
76
            raise RuntimeError("Did not receive a response.")
77
78
        if len(self.response) < 2:
79
            self.skipTest(f"Did not receive orders within time, test can not finish.")
80
81
        channel_subscription: dict = self.response[0]
82
        self.assertDictStructure(expect_subscription, channel_subscription)
83
84
        for message in self.response[1:]:
85
            # if this fails, check if the AMM wallet own other tokens as expected
86
            self.assertDictStructure(expect, message)
87
88
    def test_subscribe_market_orders_structure(self):
89
        """
90
        Check if response match expected dict structure.
91
        :return:
92
        """
93
        expect_subscription: dict = {
94
            'id': str,
95
            'result': [str]
96
        }
97
98
        expect: dict = {
99
            'channel': str,
100
            'result': [
101
                {
102
                    'order_id': str,
103
                    'block_height': int,
104
                    'triggered_block_height': int,
105
                    'address': str,
106
                    'market': str,
107
                    'side': str,
108
                    'price': str,
109
                    'quantity': str,
110
                    'available': str,
111
                    'filled': str,
112
                    'order_status': str,
113
                    'order_type': str,
114
                    'initiator': str,
115
                    'time_in_force': str,
116
                    'stop_price': str,
117
                    'trigger_type': str,
118
                    'allocated_margin_denom': str,
119
                    'allocated_margin_amount': str,
120
                    'is_liquidation': bool,
121
                    'is_post_only': bool,
122
                    'is_reduce_only': bool,
123
                    'type': str,
124
                    'block_created_at': str,
125
                    'username': str,
126
                    'id': str
127
                }
128
            ]
129
        }
130
131
        # connect to websocket
132
        client = DemexWebsocket(uri=MAINNET_WS_URI)
133
        # little work around to save the response
134
        self.response: List[dict] = []
135
136
        async def on_connect():
137
            # use AMM to be sure deterministic of which tokens the wallet holds
138
            await client.subscribe_orders('orders', WALLET_SWTH_ETH1_AMM, "swth_eth1")
139
140
        async def on_message(message: dict):
141
            # save response into self
142
            self.response.append(message)
143
144
        try:
145
            loop = asyncio.get_event_loop()
146
            loop.run_until_complete(asyncio.wait_for(client.connect(on_connect_callback=on_connect,
147
                                                                    on_receive_message_callback=on_message),
148
                                                     WEBSOCKET_TIMEOUT_SUBSCRIPTION))
149
        except asyncio.TimeoutError:
150
            loop = asyncio.get_event_loop()
151
            loop.run_until_complete(client.disconnect())
152
153
        if not self.response:
154
            raise RuntimeError("Did not receive a response.")
155
156
        if len(self.response) < 2:
157
            self.skipTest(f"Did not receive orders within time, test can not finish.")
158
159
        channel_subscription: dict = self.response[0]
160
        self.assertDictStructure(expect_subscription, channel_subscription)
161
162
        for message in self.response[1:]:
163
            # if this fails, check if the AMM wallet own other tokens as expected
164
            self.assertDictStructure(expect, message)
165