/
test_tx_websocket_agent.py
77 lines (56 loc) · 2.03 KB
/
test_tx_websocket_agent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from twisted.trial import unittest
try:
from autobahn.twisted.testing import create_memory_agent, MemoryReactorClockResolver, create_pumper
HAVE_TESTING = True
except ImportError:
HAVE_TESTING = False
from twisted.internet.defer import inlineCallbacks
from autobahn.twisted.websocket import WebSocketServerProtocol
class TestAgent(unittest.TestCase):
skip = not HAVE_TESTING
def setUp(self):
self.pumper = create_pumper()
self.reactor = MemoryReactorClockResolver()
return self.pumper.start()
def tearDown(self):
return self.pumper.stop()
@inlineCallbacks
def test_echo_server(self):
class EchoServer(WebSocketServerProtocol):
def onMessage(self, msg, is_binary):
self.sendMessage(msg)
agent = create_memory_agent(self.reactor, self.pumper, EchoServer)
proto = yield agent.open("ws://localhost:1234/ws", dict())
messages = []
def got(msg, is_binary):
messages.append(msg)
proto.on("message", got)
proto.sendMessage(b"hello")
if True:
# clean close
proto.sendClose()
else:
# unclean close
proto.transport.loseConnection()
yield proto.is_closed
self.assertEqual([b"hello"], messages)
@inlineCallbacks
def test_secure_echo_server(self):
class EchoServer(WebSocketServerProtocol):
def onMessage(self, msg, is_binary):
self.sendMessage(msg)
agent = create_memory_agent(self.reactor, self.pumper, EchoServer)
proto = yield agent.open("wss://localhost:1234/ws", dict())
messages = []
def got(msg, is_binary):
messages.append(msg)
proto.on("message", got)
proto.sendMessage(b"hello")
if True:
# clean close
proto.sendClose()
else:
# unclean close
proto.transport.loseConnection()
yield proto.is_closed
self.assertEqual([b"hello"], messages)