import importlib.util import os import tempfile import unittest MODULE_PATH = os.path.join(os.path.dirname(__file__), "pre-receive-guard.py") SPEC = importlib.util.spec_from_file_location("pre_receive_guard", MODULE_PATH) GUARD = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(GUARD) class PreReceiveGuardTests(unittest.TestCase): def test_private_identifiers_are_loaded_from_root_only_file(self): with tempfile.NamedTemporaryFile("w", delete=False) as handle: handle.write("private-owner-id\nowner@example.invalid\n") filename = handle.name try: patterns = GUARD.load_forbidden_identifiers(filename) findings = GUARD.scan_content("x private-owner-id y", "demo.txt", patterns=patterns) self.assertEqual(len(findings), 1) self.assertEqual(findings[0]["pattern_name"], "私密禁用标识") self.assertNotIn("private-owner-id", repr(findings[0])) finally: os.unlink(filename) def test_security_clean_commit_marker_cannot_bypass_scanning(self): with open(MODULE_PATH, encoding="utf-8") as handle: source = handle.read() self.assertNotIn("TRUST_SEC_CLEAN", source) self.assertNotIn('"[SEC-CLEAN]" in', source) def test_repository_source_does_not_embed_owner_identifier(self): with open(MODULE_PATH, encoding="utf-8") as handle: source = handle.read() self.assertNotRegex(source, r"\b\d{7,12}@qq\\\.com\b") if __name__ == "__main__": unittest.main()