codekingpro/portable-devtools
115k
1# -*- coding: utf-8 -*-2import sys3import unittest4from unittest.mock import patch5 6"""7test_utils.py8websocket - WebSocket client library for Python9 10Copyright 2025 engn33r11 12Licensed under the Apache License, Version 2.0 (the "License");13you may not use this file except in compliance with the License.14You may obtain a copy of the License at15 16 http://www.apache.org/licenses/LICENSE-2.017 18Unless required by applicable law or agreed to in writing, software19distributed under the License is distributed on an "AS IS" BASIS,20WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.21See the License for the specific language governing permissions and22limitations under the License.23"""24 25class UtilsTest(unittest.TestCase):26 def test_nolock(self):27 """Test NoLock context manager"""28 from websocket._utils import NoLock29 30 lock = NoLock()31 32 # Test that it can be used as context manager33 with lock:34 pass # Should not raise any exception35 36 # Test enter/exit methods directly37 self.assertIsNone(lock.__enter__())38 self.assertIsNone(lock.__exit__(None, None, None))39 40 def test_utf8_validation_with_wsaccel(self):41 """Test UTF-8 validation when wsaccel is available"""42 # Import normally (wsaccel should be available in test environment)43 from websocket._utils import validate_utf844 45 # Test valid UTF-8 strings (convert to bytes for wsaccel)46 self.assertTrue(validate_utf8("Hello, World!".encode("utf-8")))47 self.assertTrue(validate_utf8("🌟 Unicode test".encode("utf-8")))48 self.assertTrue(validate_utf8(b"Hello, bytes"))49 self.assertTrue(validate_utf8("Héllo with accénts".encode("utf-8")))50 51 # Test invalid UTF-8 sequences52 self.assertFalse(validate_utf8(b"\xff\xfe")) # Invalid UTF-853 self.assertFalse(validate_utf8(b"\x80\x80")) # Invalid continuation54 55 def test_utf8_validation_fallback(self):56 """Test UTF-8 validation fallback when wsaccel is not available"""57 # Remove _utils from modules to force reimport58 if "websocket._utils" in sys.modules:59 del sys.modules["websocket._utils"]60 61 # Mock wsaccel import to raise ImportError62 import builtins63 64 original_import = builtins.__import__65 66 def mock_import(name, *args, **kwargs):67 if "wsaccel" in name:68 raise ImportError(f"No module named '{name}'")69 return original_import(name, *args, **kwargs)70 71 with patch("builtins.__import__", side_effect=mock_import):72 import websocket._utils as utils73 74 # Test valid UTF-8 strings with fallback implementation (convert strings to bytes)75 self.assertTrue(utils.validate_utf8("Hello, World!".encode("utf-8")))76 self.assertTrue(utils.validate_utf8(b"Hello, bytes"))77 self.assertTrue(utils.validate_utf8("ASCII text".encode("utf-8")))78 79 # Test Unicode strings (convert to bytes)80 self.assertTrue(utils.validate_utf8("🌟 Unicode test".encode("utf-8")))81 self.assertTrue(utils.validate_utf8("Héllo with accénts".encode("utf-8")))82 83 # Test empty string/bytes84 self.assertTrue(utils.validate_utf8("".encode("utf-8")))85 self.assertTrue(utils.validate_utf8(b""))86 87 # Test invalid UTF-8 sequences (should return False)88 self.assertFalse(utils.validate_utf8(b"\xff\xfe"))89 self.assertFalse(utils.validate_utf8(b"\x80\x80"))90 91 # Note: The fallback implementation may have different validation behavior92 # than wsaccel, so we focus on clearly invalid sequences93 94 def test_extract_err_message(self):95 """Test extract_err_message function"""96 from websocket._utils import extract_err_message97 98 # Test with exception that has args99 exc_with_args = Exception("Test error message")100 self.assertEqual(extract_err_message(exc_with_args), "Test error message")101 102 # Test with exception that has multiple args103 exc_multi_args = Exception("First arg", "Second arg")104 self.assertEqual(extract_err_message(exc_multi_args), "First arg")105 106 # Test with exception that has no args107 exc_no_args = Exception()108 self.assertIsNone(extract_err_message(exc_no_args))109 110 def test_extract_error_code(self):111 """Test extract_error_code function"""112 from websocket._utils import extract_error_code113 114 # Test with exception that has integer as first arg115 exc_with_code = Exception(404, "Not found")116 self.assertEqual(extract_error_code(exc_with_code), 404)117 118 # Test with exception that has string as first arg119 exc_with_string = Exception("Error message", "Second arg")120 self.assertIsNone(extract_error_code(exc_with_string))121 122 # Test with exception that has only one arg123 exc_single_arg = Exception("Single arg")124 self.assertIsNone(extract_error_code(exc_single_arg))125 126 # Test with exception that has no args127 exc_no_args = Exception()128 self.assertIsNone(extract_error_code(exc_no_args))129 130 def tearDown(self):131 """Clean up after tests"""132 # Ensure _utils is reimported fresh for next test133 if "websocket._utils" in sys.modules:134 del sys.modules["websocket._utils"]135 136 137if __name__ == "__main__":138 unittest.main()139 