Files
ai-exchange/tests/unit/test_secret_static_checks.py
T
2026-05-18 22:30:34 +08:00

59 lines
2.1 KiB
Python

import contextlib
import io
import json
import tempfile
import unittest
from pathlib import Path
from scripts import run_secret_static_checks
class SecretStaticChecksTests(unittest.TestCase):
def test_detects_expect_password_without_printing_value(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
script = root / "deploy.exp"
script.write_text('set password "123456"\n', encoding="utf-8")
result = run_secret_static_checks.run_secret_static_checks(root=root, files=(script,))
self.assertFalse(result["passed"])
self.assertEqual(result["findings"][0]["pattern"], "expect_password_literal")
self.assertNotIn("123456", json.dumps(result, ensure_ascii=False))
def test_allows_placeholder_env_examples(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
example = root / ".env.example"
example.write_text("OKX_API_SECRET=<set-in-shell>\n", encoding="utf-8")
result = run_secret_static_checks.run_secret_static_checks(root=root, files=(example,))
self.assertTrue(result["passed"])
def test_detects_tracked_runtime_env(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
env_file = root / ".env"
env_file.write_text("DATABASE_URL=postgresql://user:pass@localhost/db\n", encoding="utf-8")
result = run_secret_static_checks.run_secret_static_checks(root=root, files=(env_file,))
self.assertFalse(result["passed"])
self.assertEqual(result["findings"][0]["pattern"], "tracked_runtime_env")
def test_json_output_is_machine_readable_and_redacted(self) -> None:
output = io.StringIO()
with contextlib.redirect_stdout(output):
exit_code = run_secret_static_checks.main(env={"SECRET_CHECKS_OUTPUT_JSON": "1"})
summary = json.loads(output.getvalue())
self.assertEqual(exit_code, 0)
self.assertTrue(summary["passed"])
self.assertIn("checked_file_count", summary)
if __name__ == "__main__":
unittest.main()