test_app.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # -*- coding: utf-8 -*-
  2. #
  3. """
  4. test_app.py
  5. websocket - WebSocket client library for Python
  6. Copyright 2021 engn33r
  7. Licensed under the Apache License, Version 2.0 (the "License");
  8. you may not use this file except in compliance with the License.
  9. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. """
  17. import os
  18. import os.path
  19. import websocket as ws
  20. import ssl
  21. import unittest
  22. # Skip test to access the internet unless TEST_WITH_INTERNET == 1
  23. TEST_WITH_INTERNET = os.environ.get('TEST_WITH_INTERNET', '0') == '1'
  24. # Skip tests relying on local websockets server unless LOCAL_WS_SERVER_PORT != -1
  25. LOCAL_WS_SERVER_PORT = os.environ.get('LOCAL_WS_SERVER_PORT', '-1')
  26. TEST_WITH_LOCAL_SERVER = LOCAL_WS_SERVER_PORT != '-1'
  27. TRACEABLE = True
  28. class WebSocketAppTest(unittest.TestCase):
  29. class NotSetYet:
  30. """ A marker class for signalling that a value hasn't been set yet.
  31. """
  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. def tearDown(self):
  38. WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet()
  39. WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet()
  40. WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet()
  41. @unittest.skipUnless(TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled")
  42. def testKeepRunning(self):
  43. """ A WebSocketApp should keep running as long as its self.keep_running
  44. is not False (in the boolean context).
  45. """
  46. def on_open(self, *args, **kwargs):
  47. """ Set the keep_running flag for later inspection and immediately
  48. close the connection.
  49. """
  50. self.send("hello!")
  51. WebSocketAppTest.keep_running_open = self.keep_running
  52. self.keep_running = False
  53. def on_message(wsapp, message):
  54. print(message)
  55. self.close()
  56. def on_close(self, *args, **kwargs):
  57. """ Set the keep_running flag for the test to use.
  58. """
  59. WebSocketAppTest.keep_running_close = self.keep_running
  60. app = ws.WebSocketApp('ws://127.0.0.1:' + LOCAL_WS_SERVER_PORT, on_open=on_open, on_close=on_close, on_message=on_message)
  61. app.run_forever()
  62. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  63. def testSockMaskKey(self):
  64. """ A WebSocketApp should forward the received mask_key function down
  65. to the actual socket.
  66. """
  67. def my_mask_key_func():
  68. return "\x00\x00\x00\x00"
  69. app = ws.WebSocketApp('wss://stream.meetup.com/2/rsvps', get_mask_key=my_mask_key_func)
  70. # if numpy is installed, this assertion fail
  71. # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
  72. self.assertEqual(id(app.get_mask_key), id(my_mask_key_func))
  73. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  74. def testInvalidPingIntervalPingTimeout(self):
  75. """ Test exception handling if ping_interval < ping_timeout
  76. """
  77. def on_ping(app, msg):
  78. print("Got a ping!")
  79. app.close()
  80. def on_pong(app, msg):
  81. print("Got a pong! No need to respond")
  82. app.close()
  83. app = ws.WebSocketApp('wss://api-pub.bitfinex.com/ws/1', on_ping=on_ping, on_pong=on_pong)
  84. self.assertRaises(ws.WebSocketException, app.run_forever, ping_interval=1, ping_timeout=2, sslopt={"cert_reqs": ssl.CERT_NONE})
  85. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  86. def testPingInterval(self):
  87. """ Test WebSocketApp proper ping functionality
  88. """
  89. def on_ping(app, msg):
  90. print("Got a ping!")
  91. app.close()
  92. def on_pong(app, msg):
  93. print("Got a pong! No need to respond")
  94. app.close()
  95. app = ws.WebSocketApp('wss://api-pub.bitfinex.com/ws/1', on_ping=on_ping, on_pong=on_pong)
  96. app.run_forever(ping_interval=2, ping_timeout=1, sslopt={"cert_reqs": ssl.CERT_NONE})
  97. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  98. def testOpcodeClose(self):
  99. """ Test WebSocketApp close opcode
  100. """
  101. app = ws.WebSocketApp('wss://tsock.us1.twilio.com/v3/wsconnect')
  102. app.run_forever(ping_interval=2, ping_timeout=1, ping_payload="Ping payload")
  103. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  104. def testOpcodeBinary(self):
  105. """ Test WebSocketApp binary opcode
  106. """
  107. app = ws.WebSocketApp('streaming.vn.teslamotors.com/streaming/')
  108. app.run_forever(ping_interval=2, ping_timeout=1, ping_payload="Ping payload")
  109. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  110. def testBadPingInterval(self):
  111. """ A WebSocketApp handling of negative ping_interval
  112. """
  113. app = ws.WebSocketApp('wss://api-pub.bitfinex.com/ws/1')
  114. self.assertRaises(ws.WebSocketException, app.run_forever, ping_interval=-5, sslopt={"cert_reqs": ssl.CERT_NONE})
  115. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  116. def testBadPingTimeout(self):
  117. """ A WebSocketApp handling of negative ping_timeout
  118. """
  119. app = ws.WebSocketApp('wss://api-pub.bitfinex.com/ws/1')
  120. self.assertRaises(ws.WebSocketException, app.run_forever, ping_timeout=-3, sslopt={"cert_reqs": ssl.CERT_NONE})
  121. @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
  122. def testCloseStatusCode(self):
  123. """ Test extraction of close frame status code and close reason in WebSocketApp
  124. """
  125. def on_close(wsapp, close_status_code, close_msg):
  126. print("on_close reached")
  127. app = ws.WebSocketApp('wss://tsock.us1.twilio.com/v3/wsconnect', on_close=on_close)
  128. closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b'\x03\xe8no-init-from-client')
  129. self.assertEqual([1000, 'no-init-from-client'], app._get_close_args(closeframe))
  130. closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b'')
  131. self.assertEqual([None, None], app._get_close_args(closeframe))
  132. app2 = ws.WebSocketApp('wss://tsock.us1.twilio.com/v3/wsconnect')
  133. closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b'')
  134. self.assertEqual([None, None], app2._get_close_args(closeframe))
  135. self.assertRaises(ws.WebSocketConnectionClosedException, app.send, data="test if connection is closed")
  136. if __name__ == "__main__":
  137. unittest.main()