Passed
Pull Request — main (#42)
by Switcheolytics
55s
created

tests.test_ws_unsubscribe   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 34
dl 0
loc 54
rs 10
c 0
b 0
f 0
1
import asyncio
2
from typing import List
3
4
from tests import APITestCase, MAINNET_WS_URI, WALLET_SWTH_ETH1_AMM, WEBSOCKET_TIMEOUT_GET_REQUEST
5
from tradehub.websocket_client import DemexWebsocket
6
7
8
class TestWSUnsubscribe(APITestCase):
9
10
    def test_unsubscribe_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
        # connect to websocket
21
        client = DemexWebsocket(uri=MAINNET_WS_URI)
22
        # little work around to save the response
23
        self.response: List[dict] = []
24
25
        async def on_connect():
26
            # use AMM to be sure deterministic of which tokens the wallet holds
27
            await client.subscribe_balances('balance', WALLET_SWTH_ETH1_AMM)
28
29
        async def on_message(message: dict):
30
            # save response into self
31
            if "id" in message.keys():
32
                self.response.append(message)
33
            if len(self.response) == 1:
34
                await client.unsubscribe("unsubscribe", self.response[0]["result"])
35
36
        try:
37
            loop = asyncio.get_event_loop()
38
            loop.run_until_complete(asyncio.wait_for(client.connect(on_connect_callback=on_connect,
39
                                                                    on_receive_message_callback=on_message),
40
                                                     WEBSOCKET_TIMEOUT_GET_REQUEST))
41
        except asyncio.TimeoutError:
42
            loop = asyncio.get_event_loop()
43
            loop.run_until_complete(client.disconnect())
44
45
        if not self.response:
46
            raise RuntimeError("Did not receive a response.")
47
48
        self.assertTrue(len(self.response) >= 2, msg=f"Expected at least 2 messages: channel subscription and and first update message")
49
50
        channel_subscription: dict = self.response[0]
51
        self.assertDictStructure(expect_subscription, channel_subscription)
52
        channel_unsubscription: dict = self.response[1]
53
        self.assertDictStructure(expect_subscription, channel_unsubscription)
54