import os import io import base64 import tempfile import unittest from unittest.mock import MagicMock from toolkit.captcha_breaker import ( CaptchaBreaker, CaptchaBreakerError, normalize_image_to_data_url, ) class TestNormalizeImageToDataUrl(unittest.TestCase): def test_bytes_input(self): raw_bytes = b"fake-image-bytes" expected_b64 = base64.b64encode(raw_bytes).decode("utf-8") result = normalize_image_to_data_url(raw_bytes) self.assertEqual(result, f"data:image/png;base64,{expected_b64}") def test_bytesio_input(self): bio = io.BytesIO(b"fake-bytesio-data") expected_b64 = base64.b64encode(b"fake-bytesio-data").decode("utf-8") result = normalize_image_to_data_url(bio) self.assertEqual(result, f"data:image/png;base64,{expected_b64}") def test_already_data_url(self): data_url = "data:image/jpeg;base64,123456" result = normalize_image_to_data_url(data_url) self.assertEqual(result, data_url) def test_raw_base64_string(self): raw_b64 = "ABCD1234EFGH" result = normalize_image_to_data_url(raw_b64) self.assertEqual(result, f"data:image/png;base64,{raw_b64}") def test_file_path_input(self): with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp: tmp.write(b"jpeg-content") tmp_path = tmp.name try: result = normalize_image_to_data_url(tmp_path) expected_b64 = base64.b64encode(b"jpeg-content").decode("utf-8") self.assertEqual(result, f"data:image/jpeg;base64,{expected_b64}") finally: if os.path.exists(tmp_path): os.remove(tmp_path) def test_invalid_type_raises(self): with self.assertRaises(ValueError): normalize_image_to_data_url(12345) # type: ignore class TestCaptchaBreaker(unittest.TestCase): def test_config_precedence_explicit_args(self): breaker = CaptchaBreaker( api_key="explicit_key", base_url="https://api.openai.com/v1", model="gpt-4o", timeout=15.0 ) self.assertEqual(breaker.api_key, "explicit_key") self.assertEqual(breaker.base_url, "https://api.openai.com/v1") self.assertEqual(breaker.model, "gpt-4o") self.assertEqual(breaker.timeout, 15.0) def test_missing_api_key_raises_on_client_access(self): from unittest.mock import patch with patch("toolkit.captcha_breaker.CAPTCHA_LLM_CONFIG", None): with patch.dict(os.environ, {}, clear=True): breaker = CaptchaBreaker() with self.assertRaises(CaptchaBreakerError) as ctx: _ = breaker.client self.assertIn("API Key is not configured", str(ctx.exception)) with self.assertRaises(CaptchaBreakerError) as ctx2: breaker.break_captcha(b"dummy") self.assertIn("API Key is not configured", str(ctx2.exception)) def test_fallback_to_env_when_config_is_none(self): from unittest.mock import patch with patch("toolkit.captcha_breaker.CAPTCHA_LLM_CONFIG", None): with patch.dict(os.environ, { "CAPTCHA_LLM_API_KEY": "env-key-123", "CAPTCHA_LLM_MODEL": "gpt-4o-mini", "CAPTCHA_LLM_BASE_URL": "https://custom.api/v1", "CAPTCHA_LLM_TIMEOUT": "20.0" }): mock_client = MagicMock() breaker = CaptchaBreaker(client=mock_client) self.assertEqual(breaker.api_key, "env-key-123") self.assertEqual(breaker.model, "gpt-4o-mini") self.assertEqual(breaker.base_url, "https://custom.api/v1") self.assertEqual(breaker.timeout, 20.0) def test_clean_result(self): breaker = CaptchaBreaker(api_key="test-key") self.assertEqual(breaker._clean_result(" 123456 "), "123456") self.assertEqual(breaker._clean_result('"ABCD"'), "ABCD") self.assertEqual(breaker._clean_result("'XYZW'"), "XYZW") markdown_wrapped = "```\n987654\n```" self.assertEqual(breaker._clean_result(markdown_wrapped), "987654") codeblock_wrapped = "```text\nK8W2\n```" self.assertEqual(breaker._clean_result(codeblock_wrapped), "K8W2") def test_break_captcha_with_mock_client(self): mock_client = MagicMock() mock_choice = MagicMock() mock_choice.message.content = " 884210 " mock_client.chat.completions.create.return_value.choices = [mock_choice] breaker = CaptchaBreaker( api_key="test-key", base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", model="qwen-vl-max", client=mock_client ) res = breaker.break_captcha(b"sample-image", prompt="识别验证码") self.assertEqual(res, "884210") mock_client.chat.completions.create.assert_called_once() call_kwargs = mock_client.chat.completions.create.call_args[1] self.assertEqual(call_kwargs["model"], "qwen-vl-max") self.assertEqual(call_kwargs["temperature"], 0.0) messages = call_kwargs["messages"] self.assertEqual(messages[0]["role"], "user") self.assertEqual(messages[0]["content"][0]["text"], "识别验证码") self.assertTrue(messages[0]["content"][1]["image_url"]["url"].startswith("data:image/png;base64,")) def test_api_exception_wrapped_in_captchabreakererror(self): mock_client = MagicMock() mock_client.chat.completions.create.side_effect = RuntimeError("Connection timed out") breaker = CaptchaBreaker( api_key="test-key", client=mock_client ) with self.assertRaises(CaptchaBreakerError) as ctx: breaker.break_captcha(b"sample-image") self.assertIn("Connection timed out", str(ctx.exception)) def test_callable_instance(self): mock_client = MagicMock() mock_choice = MagicMock() mock_choice.message.content = "ABC9" mock_client.chat.completions.create.return_value.choices = [mock_choice] breaker = CaptchaBreaker(api_key="test-key", client=mock_client) res = breaker(b"sample-image") self.assertEqual(res, "ABC9") if __name__ == "__main__": unittest.main()