test_captcha_breaker.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import os
  2. import io
  3. import base64
  4. import tempfile
  5. import unittest
  6. from unittest.mock import MagicMock
  7. from toolkit.captcha_breaker import (
  8. CaptchaBreaker,
  9. CaptchaBreakerError,
  10. normalize_image_to_data_url,
  11. )
  12. class TestNormalizeImageToDataUrl(unittest.TestCase):
  13. def test_bytes_input(self):
  14. raw_bytes = b"fake-image-bytes"
  15. expected_b64 = base64.b64encode(raw_bytes).decode("utf-8")
  16. result = normalize_image_to_data_url(raw_bytes)
  17. self.assertEqual(result, f"data:image/png;base64,{expected_b64}")
  18. def test_bytesio_input(self):
  19. bio = io.BytesIO(b"fake-bytesio-data")
  20. expected_b64 = base64.b64encode(b"fake-bytesio-data").decode("utf-8")
  21. result = normalize_image_to_data_url(bio)
  22. self.assertEqual(result, f"data:image/png;base64,{expected_b64}")
  23. def test_already_data_url(self):
  24. data_url = "data:image/jpeg;base64,123456"
  25. result = normalize_image_to_data_url(data_url)
  26. self.assertEqual(result, data_url)
  27. def test_raw_base64_string(self):
  28. raw_b64 = "ABCD1234EFGH"
  29. result = normalize_image_to_data_url(raw_b64)
  30. self.assertEqual(result, f"data:image/png;base64,{raw_b64}")
  31. def test_file_path_input(self):
  32. with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
  33. tmp.write(b"jpeg-content")
  34. tmp_path = tmp.name
  35. try:
  36. result = normalize_image_to_data_url(tmp_path)
  37. expected_b64 = base64.b64encode(b"jpeg-content").decode("utf-8")
  38. self.assertEqual(result, f"data:image/jpeg;base64,{expected_b64}")
  39. finally:
  40. if os.path.exists(tmp_path):
  41. os.remove(tmp_path)
  42. def test_invalid_type_raises(self):
  43. with self.assertRaises(ValueError):
  44. normalize_image_to_data_url(12345) # type: ignore
  45. class TestCaptchaBreaker(unittest.TestCase):
  46. def test_config_precedence_explicit_args(self):
  47. breaker = CaptchaBreaker(
  48. api_key="explicit_key",
  49. base_url="https://api.openai.com/v1",
  50. model="gpt-4o",
  51. timeout=15.0
  52. )
  53. self.assertEqual(breaker.api_key, "explicit_key")
  54. self.assertEqual(breaker.base_url, "https://api.openai.com/v1")
  55. self.assertEqual(breaker.model, "gpt-4o")
  56. self.assertEqual(breaker.timeout, 15.0)
  57. def test_missing_api_key_raises_on_client_access(self):
  58. from unittest.mock import patch
  59. with patch("toolkit.captcha_breaker.CAPTCHA_LLM_CONFIG", None):
  60. with patch.dict(os.environ, {}, clear=True):
  61. breaker = CaptchaBreaker()
  62. with self.assertRaises(CaptchaBreakerError) as ctx:
  63. _ = breaker.client
  64. self.assertIn("API Key is not configured", str(ctx.exception))
  65. with self.assertRaises(CaptchaBreakerError) as ctx2:
  66. breaker.break_captcha(b"dummy")
  67. self.assertIn("API Key is not configured", str(ctx2.exception))
  68. def test_fallback_to_env_when_config_is_none(self):
  69. from unittest.mock import patch
  70. with patch("toolkit.captcha_breaker.CAPTCHA_LLM_CONFIG", None):
  71. with patch.dict(os.environ, {
  72. "CAPTCHA_LLM_API_KEY": "env-key-123",
  73. "CAPTCHA_LLM_MODEL": "gpt-4o-mini",
  74. "CAPTCHA_LLM_BASE_URL": "https://custom.api/v1",
  75. "CAPTCHA_LLM_TIMEOUT": "20.0"
  76. }):
  77. mock_client = MagicMock()
  78. breaker = CaptchaBreaker(client=mock_client)
  79. self.assertEqual(breaker.api_key, "env-key-123")
  80. self.assertEqual(breaker.model, "gpt-4o-mini")
  81. self.assertEqual(breaker.base_url, "https://custom.api/v1")
  82. self.assertEqual(breaker.timeout, 20.0)
  83. def test_clean_result(self):
  84. breaker = CaptchaBreaker(api_key="test-key")
  85. self.assertEqual(breaker._clean_result(" 123456 "), "123456")
  86. self.assertEqual(breaker._clean_result('"ABCD"'), "ABCD")
  87. self.assertEqual(breaker._clean_result("'XYZW'"), "XYZW")
  88. markdown_wrapped = "```\n987654\n```"
  89. self.assertEqual(breaker._clean_result(markdown_wrapped), "987654")
  90. codeblock_wrapped = "```text\nK8W2\n```"
  91. self.assertEqual(breaker._clean_result(codeblock_wrapped), "K8W2")
  92. def test_break_captcha_with_mock_client(self):
  93. mock_client = MagicMock()
  94. mock_choice = MagicMock()
  95. mock_choice.message.content = " 884210 "
  96. mock_client.chat.completions.create.return_value.choices = [mock_choice]
  97. breaker = CaptchaBreaker(
  98. api_key="test-key",
  99. base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
  100. model="qwen-vl-max",
  101. client=mock_client
  102. )
  103. res = breaker.break_captcha(b"sample-image", prompt="识别验证码")
  104. self.assertEqual(res, "884210")
  105. mock_client.chat.completions.create.assert_called_once()
  106. call_kwargs = mock_client.chat.completions.create.call_args[1]
  107. self.assertEqual(call_kwargs["model"], "qwen-vl-max")
  108. self.assertEqual(call_kwargs["temperature"], 0.0)
  109. messages = call_kwargs["messages"]
  110. self.assertEqual(messages[0]["role"], "user")
  111. self.assertEqual(messages[0]["content"][0]["text"], "识别验证码")
  112. self.assertTrue(messages[0]["content"][1]["image_url"]["url"].startswith("data:image/png;base64,"))
  113. def test_api_exception_wrapped_in_captchabreakererror(self):
  114. mock_client = MagicMock()
  115. mock_client.chat.completions.create.side_effect = RuntimeError("Connection timed out")
  116. breaker = CaptchaBreaker(
  117. api_key="test-key",
  118. client=mock_client
  119. )
  120. with self.assertRaises(CaptchaBreakerError) as ctx:
  121. breaker.break_captcha(b"sample-image")
  122. self.assertIn("Connection timed out", str(ctx.exception))
  123. def test_callable_instance(self):
  124. mock_client = MagicMock()
  125. mock_choice = MagicMock()
  126. mock_choice.message.content = "ABC9"
  127. mock_client.chat.completions.create.return_value.choices = [mock_choice]
  128. breaker = CaptchaBreaker(api_key="test-key", client=mock_client)
  129. res = breaker(b"sample-image")
  130. self.assertEqual(res, "ABC9")
  131. if __name__ == "__main__":
  132. unittest.main()