From a2951991ddebbab0b1f7b098196a00a7b72c125b Mon Sep 17 00:00:00 2001 From: poria-lang Date: Mon, 10 Aug 2026 18:39:45 +0300 Subject: [PATCH] fix(report): write the executive report atomically --- strix/report/writer.py | 14 ++++++++------ tests/test_report_writer.py | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/strix/report/writer.py b/strix/report/writer.py index ec592f142..1fa2ad498 100644 --- a/strix/report/writer.py +++ b/strix/report/writer.py @@ -114,12 +114,14 @@ def write_run_record(run_dir: Path, run_record: dict[str, Any]) -> None: def write_executive_report(run_dir: Path, final_scan_result: str) -> None: - path = run_dir / "penetration_test_report.md" - with path.open("w", encoding="utf-8") as f: - f.write("# Security Penetration Test Report\n\n") - f.write(f"**Generated:** {datetime.now(UTC).strftime('%Y-%m-%d %H:%M:%S UTC')}\n\n") - f.write(f"{final_scan_result}\n") - logger.info("Saved final penetration test report to: %s", path) + report_path = run_dir / "penetration_test_report.md" + payload = ( + "# Security Penetration Test Report\n\n" + f"**Generated:** {datetime.now(UTC).strftime('%Y-%m-%d %H:%M:%S UTC')}\n\n" + f"{final_scan_result}\n" + ) + _atomic_write_text(report_path, payload) + logger.info("Saved final penetration test report to: %s", report_path) def write_vulnerabilities( diff --git a/tests/test_report_writer.py b/tests/test_report_writer.py index 05222796f..7d424d883 100644 --- a/tests/test_report_writer.py +++ b/tests/test_report_writer.py @@ -4,6 +4,7 @@ from __future__ import annotations import csv import json +import tempfile from typing import TYPE_CHECKING, Any import pytest @@ -179,3 +180,20 @@ def test_write_executive_report_writes_markdown(tmp_path: Path) -> None: content = (tmp_path / "penetration_test_report.md").read_text(encoding="utf-8") assert "# Security Penetration Test Report" in content assert "Scan complete. No critical issues." in content + + +def test_write_executive_report_failure_preserves_previous_report( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + target = tmp_path / "penetration_test_report.md" + target.write_text("previous report", encoding="utf-8") + + def _disk_full(*_args: Any, **_kwargs: Any) -> None: + raise OSError("disk full") + + monkeypatch.setattr(tempfile, "NamedTemporaryFile", _disk_full) + + with pytest.raises(OSError, match="disk full"): + write_executive_report(tmp_path, "new content") + + assert target.read_text(encoding="utf-8") == "previous report"