import unittest from unittest.mock import patch from scripts.check_environment_docs import ( Setting, check_documentation, python_environment_names, settings_inventory, ) class EnvironmentDocumentationTests(unittest.TestCase): def test_reference_covers_repository_variables_and_defaults(self): errors, count = check_documentation() self.assertGreater(count, 100) self.assertEqual(errors, [], "\n".join(errors)) def test_settings_parser_preserves_implicit_names_alias_order_and_defaults(self): source = ''' class Settings(BaseSettings): model_config = SettingsConfigDict(env_prefix="") app_name: str = "Example" service_url: str = Field(default=None, validation_alias=AliasChoices("SERVICE_URL", "OLD_URL")) enabled: bool = Field(default=False, validation_alias="ENABLED") interval: int = Field(default=60) build_number: str = Field(default=BUILD_NUMBER) ''' self.assertEqual(settings_inventory(source), [ Setting(("APP_NAME",), '"Example"'), Setting(("SERVICE_URL", "OLD_URL"), "null"), Setting(("ENABLED",), "false"), Setting(("INTERVAL",), "60"), Setting(("BUILD_NUMBER",), "@BUILD_NUMBER"), ]) def test_python_scanner_handles_reads_writes_and_bootstrap_mapping(self): source = ''' os.getenv("METRICS_ENABLED", "false") os.environ.get("WORKERS_ENABLED", "true") environment.get("MANAGED_SECRETS", "auto") prepared["GENERATED_KEY"] = "not-a-real-key" other.get("NOT_AN_ENVIRONMENT_VARIABLE") environment.get("lowercase-internal-key") ''' self.assertEqual(python_environment_names(source), { "METRICS_ENABLED", "WORKERS_ENABLED", "MANAGED_SECRETS", "GENERATED_KEY", }) def test_scanning_never_executes_source_or_imports_settings(self): source = '\ufeffraise RuntimeError("must not execute")\nos.getenv("SAFE_TO_SCAN")\n' self.assertEqual(python_environment_names(source), {"SAFE_TO_SCAN"}) def test_reference_guard_reports_missing_variables_and_stale_defaults(self): document = '| `RETRY_SECONDS` | `30` | Retry interval |' source = 'class Settings(BaseSettings):\n retry_seconds: int = 60\n' with patch("scripts.check_environment_docs.Path.read_text", side_effect=[document, source]), \ patch("scripts.check_environment_docs.runtime_environment_names", return_value={"NEW_FLAG"}): errors, count = check_documentation() self.assertEqual(count, 2) self.assertIn("Undocumented environment variable: NEW_FLAG", errors) self.assertTrue(any("Stale source default for RETRY_SECONDS" in error for error in errors)) if __name__ == "__main__": unittest.main()