test_app.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. # -*- coding: utf-8 -*-
  2. #
  3. import os
  4. import os.path
  5. import ssl
  6. import threading
  7. import unittest
  8. import websocket as ws
  9. """
  10. test_app.py
  11. websocket - WebSocket client library for Python
  12. Copyright 2024 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. def setUp(self):
  33. ws.enableTrace(TRACEABLE)
  34. WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet()
  35. WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet()
  36. WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet()
  37. WebSocketAppTest.on_error_data = WebSocketAppTest.NotSetYet()
  38. def tearDown(self):
  39. WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet()
  40. WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet()
  41. WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet()
  42. WebSocketAppTest.on_error_data = WebSocketAppTest.NotSetYet()
  43. def close(self):
  44. pass
  45. @unittest.skipUnless(
  46. TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled"
  47. )
  48. def test_keep_running(self):
  49. """A WebSocketApp should keep running as long as its self.keep_running
  50. is not False (in the boolean context).
  51. """
  52. def on_open(self, *args, **kwargs):
  53. """Set the keep_running flag for later inspection and immediately
  54. close the connection.
  55. """
  56. self.send("hello!")
  57. WebSocketAppTest.keep_running_open = self.keep_running
  58. self.keep_running = False
  59. def on_message(_, message):
  60. print(message)
  61. self.close()
  62. def on_close(self, *args, **kwargs):
  63. """Set the keep_running flag for the test to use."""
  64. WebSocketAppTest.keep_running_close = self.keep_running
  65. app = ws.WebSocketApp(
  66. f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}",
  67. on_open=on_open,
  68. on_close=on_close,
  69. on_message=on_message,
  70. )
  71. app.run_forever()
  72. # @unittest.skipUnless(TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled")
  73. @unittest.skipUnless(False, "Test disabled for now (requires rel)")
  74. def test_run_forever_dispatcher(self):
  75. """A WebSocketApp should keep running as long as its self.keep_running
  76. is not False (in the boolean context).
  77. """
  78. def on_open(self, *args, **kwargs):
  79. """Send a message, receive, and send one more"""
  80. self.send("hello!")
  81. self.recv()
  82. self.send("goodbye!")
  83. def on_message(_, message):
  84. print(message)
  85. self.close()
  86. app = ws.WebSocketApp(
  87. f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}",
  88. on_open=on_open,
  89. on_message=on_message,
  90. )
  91. app.run_forever(dispatcher="Dispatcher") # doesn't work
  92. # app.run_forever(dispatcher=rel) # would work
  93. # rel.dispatch()
  94. @unittest.skipUnless(
  95. TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled"
  96. )
  97. def test_run_forever_teardown_clean_exit(self):
  98. """The WebSocketApp.run_forever() method should return `False` when the application ends gracefully."""
  99. app = ws.WebSocketApp(f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}")
  100. threading.Timer(interval=0.2, function=app.close).start()
  101. teardown = app.run_forever()
  102. self.assertEqual(teardown, False)
  103. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  104. def test_sock_mask_key(self):
  105. """A WebSocketApp should forward the received mask_key function down
  106. to the actual socket.
  107. """
  108. def my_mask_key_func():
  109. return "\x00\x00\x00\x00"
  110. app = ws.WebSocketApp(
  111. "wss://api-pub.bitfinex.com/ws/1", get_mask_key=my_mask_key_func
  112. )
  113. # if numpy is installed, this assertion fail
  114. # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
  115. self.assertEqual(id(app.get_mask_key), id(my_mask_key_func))
  116. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  117. def test_invalid_ping_interval_ping_timeout(self):
  118. """Test exception handling if ping_interval < ping_timeout"""
  119. def on_ping(app, _):
  120. print("Got a ping!")
  121. app.close()
  122. def on_pong(app, _):
  123. print("Got a pong! No need to respond")
  124. app.close()
  125. app = ws.WebSocketApp(
  126. "wss://api-pub.bitfinex.com/ws/1", on_ping=on_ping, on_pong=on_pong
  127. )
  128. self.assertRaises(
  129. ws.WebSocketException,
  130. app.run_forever,
  131. ping_interval=1,
  132. ping_timeout=2,
  133. sslopt={"cert_reqs": ssl.CERT_NONE},
  134. )
  135. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  136. def test_ping_interval(self):
  137. """Test WebSocketApp proper ping functionality"""
  138. def on_ping(app, _):
  139. print("Got a ping!")
  140. app.close()
  141. def on_pong(app, _):
  142. print("Got a pong! No need to respond")
  143. app.close()
  144. app = ws.WebSocketApp(
  145. "wss://api-pub.bitfinex.com/ws/1", on_ping=on_ping, on_pong=on_pong
  146. )
  147. app.run_forever(
  148. ping_interval=2, ping_timeout=1, sslopt={"cert_reqs": ssl.CERT_NONE}
  149. )
  150. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  151. def test_opcode_close(self):
  152. """Test WebSocketApp close opcode"""
  153. app = ws.WebSocketApp("wss://tsock.us1.twilio.com/v3/wsconnect")
  154. app.run_forever(ping_interval=2, ping_timeout=1, ping_payload="Ping payload")
  155. # This is commented out because the URL no longer responds in the expected way
  156. # @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  157. # def testOpcodeBinary(self):
  158. # """ Test WebSocketApp binary opcode
  159. # """
  160. # app = ws.WebSocketApp('wss://streaming.vn.teslamotors.com/streaming/')
  161. # app.run_forever(ping_interval=2, ping_timeout=1, ping_payload="Ping payload")
  162. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  163. def test_bad_ping_interval(self):
  164. """A WebSocketApp handling of negative ping_interval"""
  165. app = ws.WebSocketApp("wss://api-pub.bitfinex.com/ws/1")
  166. self.assertRaises(
  167. ws.WebSocketException,
  168. app.run_forever,
  169. ping_interval=-5,
  170. sslopt={"cert_reqs": ssl.CERT_NONE},
  171. )
  172. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  173. def test_bad_ping_timeout(self):
  174. """A WebSocketApp handling of negative ping_timeout"""
  175. app = ws.WebSocketApp("wss://api-pub.bitfinex.com/ws/1")
  176. self.assertRaises(
  177. ws.WebSocketException,
  178. app.run_forever,
  179. ping_timeout=-3,
  180. sslopt={"cert_reqs": ssl.CERT_NONE},
  181. )
  182. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  183. def test_close_status_code(self):
  184. """Test extraction of close frame status code and close reason in WebSocketApp"""
  185. def on_close(wsapp, close_status_code, close_msg):
  186. print("on_close reached")
  187. app = ws.WebSocketApp(
  188. "wss://tsock.us1.twilio.com/v3/wsconnect", on_close=on_close
  189. )
  190. closeframe = ws.ABNF(
  191. opcode=ws.ABNF.OPCODE_CLOSE, data=b"\x03\xe8no-init-from-client"
  192. )
  193. self.assertEqual([1000, "no-init-from-client"], app._get_close_args(closeframe))
  194. closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b"")
  195. self.assertEqual([None, None], app._get_close_args(closeframe))
  196. app2 = ws.WebSocketApp("wss://tsock.us1.twilio.com/v3/wsconnect")
  197. closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b"")
  198. self.assertEqual([None, None], app2._get_close_args(closeframe))
  199. self.assertRaises(
  200. ws.WebSocketConnectionClosedException,
  201. app.send,
  202. data="test if connection is closed",
  203. )
  204. @unittest.skipUnless(
  205. TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled"
  206. )
  207. def test_callback_function_exception(self):
  208. """Test callback function exception handling"""
  209. exc = None
  210. passed_app = None
  211. def on_open(app):
  212. raise RuntimeError("Callback failed")
  213. def on_error(app, err):
  214. nonlocal passed_app
  215. passed_app = app
  216. nonlocal exc
  217. exc = err
  218. def on_pong(app, _):
  219. app.close()
  220. app = ws.WebSocketApp(
  221. f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}",
  222. on_open=on_open,
  223. on_error=on_error,
  224. on_pong=on_pong,
  225. )
  226. app.run_forever(ping_interval=2, ping_timeout=1)
  227. self.assertEqual(passed_app, app)
  228. self.assertIsInstance(exc, RuntimeError)
  229. self.assertEqual(str(exc), "Callback failed")
  230. @unittest.skipUnless(
  231. TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled"
  232. )
  233. def test_callback_method_exception(self):
  234. """Test callback method exception handling"""
  235. class Callbacks:
  236. def __init__(self):
  237. self.exc = None
  238. self.passed_app = None
  239. self.app = ws.WebSocketApp(
  240. f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}",
  241. on_open=self.on_open,
  242. on_error=self.on_error,
  243. on_pong=self.on_pong,
  244. )
  245. self.app.run_forever(ping_interval=2, ping_timeout=1)
  246. def on_open(self, _):
  247. raise RuntimeError("Callback failed")
  248. def on_error(self, app, err):
  249. self.passed_app = app
  250. self.exc = err
  251. def on_pong(self, app, _):
  252. app.close()
  253. callbacks = Callbacks()
  254. self.assertEqual(callbacks.passed_app, callbacks.app)
  255. self.assertIsInstance(callbacks.exc, RuntimeError)
  256. self.assertEqual(str(callbacks.exc), "Callback failed")
  257. @unittest.skipUnless(
  258. TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled"
  259. )
  260. def test_reconnect(self):
  261. """Test reconnect"""
  262. pong_count = 0
  263. exc = None
  264. def on_error(_, err):
  265. nonlocal exc
  266. exc = err
  267. def on_pong(app, _):
  268. nonlocal pong_count
  269. pong_count += 1
  270. if pong_count == 1:
  271. # First pong, shutdown socket, enforce read error
  272. app.sock.shutdown()
  273. if pong_count >= 2:
  274. # Got second pong after reconnect
  275. app.close()
  276. app = ws.WebSocketApp(
  277. f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", on_pong=on_pong, on_error=on_error
  278. )
  279. app.run_forever(ping_interval=2, ping_timeout=1, reconnect=3)
  280. self.assertEqual(pong_count, 2)
  281. self.assertIsInstance(exc, ws.WebSocketTimeoutException)
  282. self.assertEqual(str(exc), "ping/pong timed out")
  283. if __name__ == "__main__":
  284. unittest.main()