treesearch/output/
json.rs1use serde::Serialize;
7
8use crate::document::SearchResult;
9
10use super::OutputFormat;
11
12const SCHEMA_VERSION: &str = "1.0";
14
15#[derive(Serialize)]
17struct JsonEnvelope<'a> {
18 version: &'static str,
19 results: &'a [SearchResult],
20}
21
22pub struct JsonOutput;
24
25impl JsonOutput {
26 pub fn new() -> Self {
27 Self
28 }
29}
30
31impl Default for JsonOutput {
32 fn default() -> Self {
33 Self::new()
34 }
35}
36
37impl OutputFormat for JsonOutput {
38 fn render(&self, results: &[SearchResult], _verbose: u8) -> String {
39 let envelope = JsonEnvelope {
40 version: SCHEMA_VERSION,
41 results,
42 };
43 serde_json::to_string_pretty(&envelope).unwrap_or_else(|error| {
44 serde_json::json!({ "error": format!("serialization failed: {error}") }).to_string()
45 })
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 fn sample_result() -> SearchResult {
54 SearchResult {
55 node_id: "1".into(),
56 doc_id: "doc1".into(),
57 doc_name: "test.md".into(),
58 title: "Test Title".into(),
59 summary: "A test summary".into(),
60 text: "Some body text".into(),
61 source_type: "markdown".into(),
62 source_path: "docs/test.md".into(),
63 line_start: Some(1),
64 line_end: Some(10),
65 score: 0.95,
66 depth: 0,
67 breadcrumb: vec!["Root".into(), "Test Title".into()],
68 }
69 }
70
71 #[test]
72 fn test_json_output_has_version() {
73 let json_out = JsonOutput::new();
74 let output = json_out.render(&[sample_result()], 0);
75 assert!(output.contains("\"version\": \"1.0\""));
76 }
77
78 #[test]
79 fn test_json_output_has_results() {
80 let json_out = JsonOutput::new();
81 let output = json_out.render(&[sample_result()], 0);
82 assert!(output.contains("\"results\""));
83 assert!(output.contains("\"Test Title\""));
84 assert!(output.contains("0.95"));
85 }
86
87 #[test]
88 fn test_json_output_empty() {
89 let json_out = JsonOutput::new();
90 let output = json_out.render(&[], 0);
91 assert!(output.contains("\"version\": \"1.0\""));
92 assert!(output.contains("\"results\": []"));
93 }
94
95 #[test]
96 fn test_json_output_valid_json() {
97 let json_out = JsonOutput::new();
98 let output = json_out.render(&[sample_result()], 0);
99 let parsed: serde_json::Value = serde_json::from_str(&output).unwrap();
100 assert_eq!(parsed["version"], "1.0");
101 assert!(parsed["results"].is_array());
102 assert_eq!(parsed["results"].as_array().unwrap().len(), 1);
103 }
104
105 #[test]
106 fn test_json_output_pretty_printed() {
107 let json_out = JsonOutput::new();
108 let output = json_out.render(&[sample_result()], 0);
109 assert!(output.contains('\n'));
111 assert!(output.contains(" "));
112 }
113
114 #[test]
115 fn test_json_output_multiple_results() {
116 let json_out = JsonOutput::new();
117 let results = vec![sample_result(), sample_result()];
118 let output = json_out.render(&results, 0);
119 let parsed: serde_json::Value = serde_json::from_str(&output).unwrap();
120 assert_eq!(parsed["results"].as_array().unwrap().len(), 2);
121 }
122}