"""Secret configuration must preserve unrelated settings and existing client credentials.""" import json from dotenv import dotenv_values from scripts.setup_external_risk import configure_client, read_operator_mappings, write_operator_mapping def test_configure_keeps_settings_and_does_not_rotate_existing_secret(tmp_path): env_file = tmp_path / ".env" env_file.write_text("RISK_DATABASE_URL=keep-this-value\n# 保留注释\n", encoding="utf-8") assert configure_client(env_file, "dieya-plm") values = dotenv_values(env_file) clients = json.loads(values["RISK_INTEGRATION_CLIENTS"]) assert len(clients["dieya-plm"]) >= 32 assert values["RISK_DATABASE_URL"] == "keep-this-value" previous = env_file.read_bytes() assert not configure_client(env_file, "dieya-plm") assert env_file.read_bytes() == previous def test_external_mapping_preserves_secret_and_other_mappings(tmp_path): env_file = tmp_path / ".env" assert configure_client(env_file, "dieya-plm") secret = dotenv_values(env_file)["RISK_INTEGRATION_CLIENTS"] write_operator_mapping(env_file, "other-system", "user-1", "employee-1") write_operator_mapping(env_file, "dieya-plm", "superadmin", "plm_superadmin") assert read_operator_mappings(env_file) == { "other-system": {"user-1": "employee-1"}, "dieya-plm": {"superadmin": "plm_superadmin"}, } assert dotenv_values(env_file)["RISK_INTEGRATION_CLIENTS"] == secret def test_configure_preserves_other_secret_with_quotes_and_backslashes(tmp_path): env_file = tmp_path / ".env" existing = "a'b\"c\\d" + "-" * 40 encoded = json.dumps(json.dumps({"other-system": existing})) env_file.write_text(f"RISK_INTEGRATION_CLIENTS={encoded}\n", encoding="utf-8") assert configure_client(env_file, "dieya-plm") clients = json.loads(dotenv_values(env_file)["RISK_INTEGRATION_CLIENTS"]) assert clients["other-system"] == existing assert len(clients["dieya-plm"]) >= 32