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

tests.test_ws_subscribe_account_trades   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 143
Duplicated Lines 92.31 %

Importance

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