Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_app.py 12KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. # -*- coding: utf-8 -*-
  2. #
  3. import os
  4. import os.path
  5. import threading
  6. import websocket as ws
  7. import ssl
  8. import unittest
  9. """
  10. test_app.py
  11. websocket - WebSocket client library for Python
  12. Copyright 2023 engn33r
  13. Licensed under the Apache License, Version 2.0 (the "License");
  14. you may not use this file except in compliance with the License.
  15. You may obtain a copy of the License at
  16. http://www.apache.org/licenses/LICENSE-2.0
  17. Unless required by applicable law or agreed to in writing, software
  18. distributed under the License is distributed on an "AS IS" BASIS,
  19. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. See the License for the specific language governing permissions and
  21. limitations under the License.
  22. """
  23. # Skip test to access the internet unless TEST_WITH_INTERNET == 1
  24. TEST_WITH_INTERNET = os.environ.get('TEST_WITH_INTERNET', '0') == '1'
  25. # Skip tests relying on local websockets server unless LOCAL_WS_SERVER_PORT != -1
  26. LOCAL_WS_SERVER_PORT = os.environ.get('LOCAL_WS_SERVER_PORT', '-1')
  27. TEST_WITH_LOCAL_SERVER = LOCAL_WS_SERVER_PORT != '-1'
  28. TRACEABLE = True
  29. class WebSocketAppTest(unittest.TestCase):
  30. class NotSetYet:
  31. """ A marker class for signalling that a value hasn't been set yet.
  32. """
  33. def setUp(self):
  34. ws.enableTrace(TRACEABLE)
  35. WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet()
  36. WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet()
  37. WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet()
  38. WebSocketAppTest.on_error_data = WebSocketAppTest.NotSetYet()
  39. def tearDown(self):
  40. WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet()
  41. WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet()
  42. WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet()
  43. WebSocketAppTest.on_error_data = WebSocketAppTest.NotSetYet()
  44. @unittest.skipUnless(TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled")
  45. def testKeepRunning(self):
  46. """ A WebSocketApp should keep running as long as its self.keep_running
  47. is not False (in the boolean context).
  48. """
  49. def on_open(self, *args, **kwargs):
  50. """ Set the keep_running flag for later inspection and immediately
  51. close the connection.
  52. """
  53. self.send("hello!")
  54. WebSocketAppTest.keep_running_open = self.keep_running
  55. self.keep_running = False
  56. def on_message(wsapp, message):
  57. print(message)
  58. self.close()
  59. def on_close(self, *args, **kwargs):
  60. """ Set the keep_running flag for the test to use.
  61. """
  62. WebSocketAppTest.keep_running_close = self.keep_running
  63. app = ws.WebSocketApp('ws://127.0.0.1:' + LOCAL_WS_SERVER_PORT, on_open=on_open, on_close=on_close, on_message=on_message)
  64. app.run_forever()
  65. # @unittest.skipUnless(TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled")
  66. @unittest.skipUnless(False, "Test disabled for now (requires rel)")
  67. def testRunForeverDispatcher(self):
  68. """ A WebSocketApp should keep running as long as its self.keep_running
  69. is not False (in the boolean context).
  70. """
  71. def on_open(self, *args, **kwargs):
  72. """ Send a message, receive, and send one more
  73. """
  74. self.send("hello!")
  75. self.recv()
  76. self.send("goodbye!")
  77. def on_message(wsapp, message):
  78. print(message)
  79. self.close()
  80. app = ws.WebSocketApp('ws://127.0.0.1:' + LOCAL_WS_SERVER_PORT, on_open=on_open, on_message=on_message)
  81. app.run_forever(dispatcher="Dispatcher") # doesn't work
  82. # app.run_forever(dispatcher=rel) # would work
  83. # rel.dispatch()
  84. @unittest.skipUnless(TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled")
  85. def testRunForeverTeardownCleanExit(self):
  86. """ The WebSocketApp.run_forever() method should return `False` when the application ends gracefully.
  87. """
  88. app = ws.WebSocketApp('ws://127.0.0.1:' + LOCAL_WS_SERVER_PORT)
  89. threading.Timer(interval=0.2, function=app.close).start()
  90. teardown = app.run_forever()
  91. self.assertEqual(teardown, False)
  92. @unittest.skipUnless(TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled")
  93. def testRunForeverTeardownExceptionalExit(self):
  94. """ The WebSocketApp.run_forever() method should return `True` when the application ends with an exception.
  95. It should also invoke the `on_error` callback before exiting.
  96. """
  97. def break_it():
  98. # Deliberately break the WebSocketApp by closing the inner socket.
  99. app.sock.close()
  100. def on_error(_, err):
  101. WebSocketAppTest.on_error_data = str(err)
  102. app = ws.WebSocketApp('ws://127.0.0.1:' + LOCAL_WS_SERVER_PORT, on_error=on_error)
  103. threading.Timer(interval=0.2, function=break_it).start()
  104. teardown = app.run_forever(ping_timeout=0.1)
  105. self.assertEqual(teardown, True)
  106. self.assertTrue(len(WebSocketAppTest.on_error_data) > 0)
  107. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  108. def testSockMaskKey(self):
  109. """ A WebSocketApp should forward the received mask_key function down
  110. to the actual socket.
  111. """
  112. def my_mask_key_func():
  113. return "\x00\x00\x00\x00"
  114. app = ws.WebSocketApp('wss://api-pub.bitfinex.com/ws/1', get_mask_key=my_mask_key_func)
  115. # if numpy is installed, this assertion fail
  116. # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
  117. self.assertEqual(id(app.get_mask_key), id(my_mask_key_func))
  118. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  119. def testInvalidPingIntervalPingTimeout(self):
  120. """ Test exception handling if ping_interval < ping_timeout
  121. """
  122. def on_ping(app, msg):
  123. print("Got a ping!")
  124. app.close()
  125. def on_pong(app, msg):
  126. print("Got a pong! No need to respond")
  127. app.close()
  128. app = ws.WebSocketApp('wss://api-pub.bitfinex.com/ws/1', on_ping=on_ping, on_pong=on_pong)
  129. self.assertRaises(ws.WebSocketException, app.run_forever, ping_interval=1, ping_timeout=2, sslopt={"cert_reqs": ssl.CERT_NONE})
  130. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  131. def testPingInterval(self):
  132. """ Test WebSocketApp proper ping functionality
  133. """
  134. def on_ping(app, msg):
  135. print("Got a ping!")
  136. app.close()
  137. def on_pong(app, msg):
  138. print("Got a pong! No need to respond")
  139. app.close()
  140. app = ws.WebSocketApp('wss://api-pub.bitfinex.com/ws/1', on_ping=on_ping, on_pong=on_pong)
  141. app.run_forever(ping_interval=2, ping_timeout=1, sslopt={"cert_reqs": ssl.CERT_NONE})
  142. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  143. def testOpcodeClose(self):
  144. """ Test WebSocketApp close opcode
  145. """
  146. app = ws.WebSocketApp('wss://tsock.us1.twilio.com/v3/wsconnect')
  147. app.run_forever(ping_interval=2, ping_timeout=1, ping_payload="Ping payload")
  148. # This is commented out because the URL no longer responds in the expected way
  149. # @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  150. # def testOpcodeBinary(self):
  151. # """ Test WebSocketApp binary opcode
  152. # """
  153. # app = ws.WebSocketApp('wss://streaming.vn.teslamotors.com/streaming/')
  154. # app.run_forever(ping_interval=2, ping_timeout=1, ping_payload="Ping payload")
  155. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  156. def testBadPingInterval(self):
  157. """ A WebSocketApp handling of negative ping_interval
  158. """
  159. app = ws.WebSocketApp('wss://api-pub.bitfinex.com/ws/1')
  160. self.assertRaises(ws.WebSocketException, app.run_forever, ping_interval=-5, sslopt={"cert_reqs": ssl.CERT_NONE})
  161. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  162. def testBadPingTimeout(self):
  163. """ A WebSocketApp handling of negative ping_timeout
  164. """
  165. app = ws.WebSocketApp('wss://api-pub.bitfinex.com/ws/1')
  166. self.assertRaises(ws.WebSocketException, app.run_forever, ping_timeout=-3, sslopt={"cert_reqs": ssl.CERT_NONE})
  167. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  168. def testCloseStatusCode(self):
  169. """ Test extraction of close frame status code and close reason in WebSocketApp
  170. """
  171. def on_close(wsapp, close_status_code, close_msg):
  172. print("on_close reached")
  173. app = ws.WebSocketApp('wss://tsock.us1.twilio.com/v3/wsconnect', on_close=on_close)
  174. closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b'\x03\xe8no-init-from-client')
  175. self.assertEqual([1000, 'no-init-from-client'], app._get_close_args(closeframe))
  176. closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b'')
  177. self.assertEqual([None, None], app._get_close_args(closeframe))
  178. app2 = ws.WebSocketApp('wss://tsock.us1.twilio.com/v3/wsconnect')
  179. closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b'')
  180. self.assertEqual([None, None], app2._get_close_args(closeframe))
  181. self.assertRaises(ws.WebSocketConnectionClosedException, app.send, data="test if connection is closed")
  182. @unittest.skipUnless(TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled")
  183. def testCallbackFunctionException(self):
  184. """ Test callback function exception handling """
  185. exc = None
  186. passed_app = None
  187. def on_open(app):
  188. raise RuntimeError("Callback failed")
  189. def on_error(app, err):
  190. nonlocal passed_app
  191. passed_app = app
  192. nonlocal exc
  193. exc = err
  194. def on_pong(app, msg):
  195. app.close()
  196. app = ws.WebSocketApp('ws://127.0.0.1:' + LOCAL_WS_SERVER_PORT, on_open=on_open, on_error=on_error, on_pong=on_pong)
  197. app.run_forever(ping_interval=2, ping_timeout=1)
  198. self.assertEqual(passed_app, app)
  199. self.assertIsInstance(exc, RuntimeError)
  200. self.assertEqual(str(exc), "Callback failed")
  201. @unittest.skipUnless(TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled")
  202. def testCallbackMethodException(self):
  203. """ Test callback method exception handling """
  204. class Callbacks:
  205. def __init__(self):
  206. self.exc = None
  207. self.passed_app = None
  208. self.app = ws.WebSocketApp(
  209. 'ws://127.0.0.1:' + LOCAL_WS_SERVER_PORT,
  210. on_open=self.on_open,
  211. on_error=self.on_error,
  212. on_pong=self.on_pong
  213. )
  214. self.app.run_forever(ping_interval=2, ping_timeout=1)
  215. def on_open(self, app):
  216. raise RuntimeError("Callback failed")
  217. def on_error(self, app, err):
  218. self.passed_app = app
  219. self.exc = err
  220. def on_pong(self, app, msg):
  221. app.close()
  222. callbacks = Callbacks()
  223. self.assertEqual(callbacks.passed_app, callbacks.app)
  224. self.assertIsInstance(callbacks.exc, RuntimeError)
  225. self.assertEqual(str(callbacks.exc), "Callback failed")
  226. @unittest.skipUnless(TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled")
  227. def testReconnect(self):
  228. """ Test reconnect """
  229. pong_count = 0
  230. exc = None
  231. def on_error(app, err):
  232. nonlocal exc
  233. exc = err
  234. def on_pong(app, msg):
  235. nonlocal pong_count
  236. pong_count += 1
  237. if pong_count == 1:
  238. # First pong, shutdown socket, enforce read error
  239. app.sock.shutdown()
  240. if pong_count >= 2:
  241. # Got second pong after reconnect
  242. app.close()
  243. app = ws.WebSocketApp('ws://127.0.0.1:' + LOCAL_WS_SERVER_PORT, on_pong=on_pong, on_error=on_error)
  244. app.run_forever(ping_interval=2, ping_timeout=1, reconnect=3)
  245. self.assertEqual(pong_count, 2)
  246. self.assertIsInstance(exc, ws.WebSocketTimeoutException)
  247. self.assertEqual(str(exc), "ping/pong timed out")
  248. if __name__ == "__main__":
  249. unittest.main()