clnrm_core/reporting/
json.rs

1//! JSON report format
2//!
3//! Generates structured JSON reports for test results with pass/fail details.
4
5use crate::error::{CleanroomError, Result};
6use crate::validation::ValidationReport;
7use serde::Serialize;
8use std::path::Path;
9
10/// JSON report structure
11#[derive(Debug, Serialize)]
12pub struct JsonReport {
13    /// Overall test success status
14    pub passed: bool,
15    /// Total number of passing validations
16    pub total_passes: usize,
17    /// Total number of failing validations
18    pub total_failures: usize,
19    /// List of validation names that passed
20    pub passes: Vec<String>,
21    /// List of failures with details
22    pub failures: Vec<FailureDetail>,
23}
24
25/// Detailed failure information
26#[derive(Debug, Serialize)]
27pub struct FailureDetail {
28    /// Name of the failing validation
29    pub name: String,
30    /// Error message describing the failure
31    pub error: String,
32}
33
34/// JSON report generator
35pub struct JsonReporter;
36
37impl JsonReporter {
38    /// Write JSON report to file
39    ///
40    /// # Arguments
41    /// * `path` - File path for JSON output
42    /// * `report` - Validation report to convert
43    ///
44    /// # Returns
45    /// * `Result<()>` - Success or error
46    ///
47    /// # Errors
48    /// Returns error if:
49    /// - JSON serialization fails
50    /// - File write fails
51    pub fn write(path: &Path, report: &ValidationReport) -> Result<()> {
52        let json_report = Self::convert_report(report);
53        let json_str = Self::serialize(&json_report)?;
54        Self::write_file(path, &json_str)
55    }
56
57    /// Convert ValidationReport to JsonReport
58    fn convert_report(report: &ValidationReport) -> JsonReport {
59        JsonReport {
60            passed: report.is_success(),
61            total_passes: report.passes().len(),
62            total_failures: report.failures().len(),
63            passes: report.passes().to_vec(),
64            failures: report
65                .failures()
66                .iter()
67                .map(|(name, error)| FailureDetail {
68                    name: name.clone(),
69                    error: error.clone(),
70                })
71                .collect(),
72        }
73    }
74
75    /// Serialize JsonReport to pretty-printed JSON string
76    fn serialize(json_report: &JsonReport) -> Result<String> {
77        serde_json::to_string_pretty(json_report).map_err(|e| {
78            CleanroomError::serialization_error(format!("JSON serialization failed: {}", e))
79        })
80    }
81
82    /// Write JSON string to file
83    fn write_file(path: &Path, content: &str) -> Result<()> {
84        std::fs::write(path, content).map_err(|e| {
85            CleanroomError::report_error(format!("Failed to write JSON report: {}", e))
86        })
87    }
88}