import importlib.util from pathlib import Path import sys import types import unittest from unittest.mock import patch MODULE_PATH = ( Path(__file__).resolve().parents[1] / "core" / "identification_feedback.py" ) SPEC = importlib.util.spec_from_file_location( "identification_feedback_under_test", MODULE_PATH ) FEEDBACK = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(FEEDBACK) class FakeResponse: def __init__(self, body): self.body = body def raise_for_status(self): return None def json(self): return self.body class IdentificationFeedbackTests(unittest.TestCase): def call_with_response(self, response_body, callback): calls = [] requests_module = types.ModuleType("requests") def post(url, json, timeout): calls.append((url, json, timeout)) return FakeResponse(response_body) requests_module.post = post api_module = types.ModuleType("api") api_module.data_record_url = "https://cloud/data_record" api_module.the_folder = "客户A" with patch.dict(sys.modules, { "requests": requests_module, "api": api_module, }): value = callback() return value, calls def test_registers_uploaded_csv(self): _, calls = self.call_with_response( {"success": True}, lambda: FEEDBACK.register_identification_result("result.csv", 7), ) self.assertEqual(calls[0][1], { "type": "registerIdentificationResult", "deviceId": "客户A", "runId": "result.csv", "fileName": "result.csv", }) def test_pending_feedback_returns_none(self): value, _ = self.call_with_response( {"success": True, "ready": False}, lambda: FEEDBACK.get_identification_feedback("result.csv"), ) self.assertIsNone(value) def test_feedback_returns_only_zero_or_one(self): for result in (0, 1): value, _ = self.call_with_response( {"success": True, "ready": True, "result": result}, lambda: FEEDBACK.get_identification_feedback("result.csv"), ) self.assertEqual(value, result) with self.assertRaisesRegex(ValueError, "0 或 1"): self.call_with_response( {"success": True, "ready": True, "result": 2}, lambda: FEEDBACK.get_identification_feedback("result.csv"), ) if __name__ == "__main__": unittest.main()