1 | import logging
|
---|
2 | from pathlib import Path # type:ignore
|
---|
3 | import threading
|
---|
4 | from time import sleep
|
---|
5 | import unittest
|
---|
6 | from unittest.mock import Mock
|
---|
7 |
|
---|
8 | from tudelft_utilities_logging.Reporter import Reporter
|
---|
9 | from uri import URI
|
---|
10 |
|
---|
11 | from geniusweb.profileconnection.FileProfileConnector import FileProfileConnector
|
---|
12 | from geniusweb.profileconnection.Session import Session
|
---|
13 | from geniusweb.profileconnection.WebSocketContainer import WebSocketContainer, \
|
---|
14 | DefaultWebSocketContainer
|
---|
15 | from geniusweb.profileconnection.WebsocketProfileConnector import WebsocketProfileConnector
|
---|
16 |
|
---|
17 |
|
---|
18 | class DummyReporter(Reporter):
|
---|
19 | def log(self, level:int, msg:str, thrown:Exception=None):
|
---|
20 | print(msg)
|
---|
21 |
|
---|
22 |
|
---|
23 |
|
---|
24 | class WebSocketProfileConnectorTest(unittest.TestCase):
|
---|
25 |
|
---|
26 | profiletext = Path("test/resources/japantrip1.json").read_text("utf-8")
|
---|
27 | reporter=DummyReporter()
|
---|
28 |
|
---|
29 | def t1estConnect(self):
|
---|
30 | session=Mock(Session)
|
---|
31 | # this session does nothing, we manipulate it ourselves.
|
---|
32 |
|
---|
33 | #mock websocket
|
---|
34 | wsContainer = Mock(WebSocketContainer)
|
---|
35 | wsContainer.connectToServer.return_value=session
|
---|
36 |
|
---|
37 | profint= WebsocketProfileConnector("ws://blabla", self.reporter, wsContainer )
|
---|
38 |
|
---|
39 | def pumpevents():
|
---|
40 | profint.onOpen(session)
|
---|
41 | sleep(1)
|
---|
42 | profint.onMessage(self.profiletext)
|
---|
43 | print ("Message was sent")
|
---|
44 |
|
---|
45 | threading.Thread(target=pumpevents).start()
|
---|
46 | profint.close()
|
---|
47 |
|
---|
48 |
|
---|
49 | self.assertEqual("japantrip1", profint.getProfile().getName())
|
---|
50 | print("Received profile succesfully!")
|
---|
51 |
|
---|
52 | def t1estConnectTimeout(self):
|
---|
53 | session=Mock(Session)
|
---|
54 | #mock websocket
|
---|
55 | wsContainer = Mock(WebSocketContainer)
|
---|
56 | wsContainer.connectToServer.return_value=session
|
---|
57 |
|
---|
58 | profint= WebsocketProfileConnector("ws://blabla", self.reporter, wsContainer )
|
---|
59 |
|
---|
60 | # since we don't pump events, this should timeout.
|
---|
61 | self.assertRaises(IOError, lambda:profint.getProfile())
|
---|
62 | profint.close()
|
---|
63 |
|
---|
64 |
|
---|
65 | def testWithRealProfilesServer(self):
|
---|
66 | '''
|
---|
67 | TO RUN THIS, ENSURE YOU HAVE A RUNNING PROFILESSERVER ON LOCALHOST
|
---|
68 | '''
|
---|
69 | profint= WebsocketProfileConnector(URI("ws://localhost:8080/profilesserver/websocket/get/party/party1"), self.reporter, DefaultWebSocketContainer() )
|
---|
70 | sleep(1)
|
---|
71 | profile=profint.getProfile()
|
---|
72 | self.assertTrue(profile)
|
---|
73 | profint.close()
|
---|
74 |
|
---|
75 | |
---|