Skip to content

A fast, helpful, and open-source document parser

wip: unit tests

Clelia (Astra) Bertelli3361631f54c5
diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rs
index 8ecd773..fb35a15 100644
--- a/crates/liteparse/src/config.rs
+++ b/crates/liteparse/src/config.rs
@@ -101,4 +101,44 @@ mod tests {
assert!(parse_target_pages("5-3").is_err());
assert!(parse_target_pages("abc").is_err());
}
+
+ #[test]
+ fn test_parse_target_pages_with_whitespace() {
+ assert_eq!(parse_target_pages(" 1 , 2 - 4 ").unwrap(), vec![1, 2, 3, 4]);
+ }
+
+ #[test]
+ fn test_parse_target_pages_single_range() {
+ assert_eq!(parse_target_pages("2-2").unwrap(), vec![2]);
+ }
+
+ #[test]
+ fn test_default_config() {
+ let c = LiteParseConfig::default();
+ assert_eq!(c.ocr_language, "eng");
+ assert!(c.ocr_enabled);
+ assert_eq!(c.max_pages, 1000);
+ assert_eq!(c.dpi, 150.0);
+ assert_eq!(c.output_format, OutputFormat::Json);
+ assert!(!c.preserve_very_small_text);
+ assert!(!c.quiet);
+ assert!(c.password.is_none());
+ }
+
+ #[test]
+ fn test_output_format_lowercase_serde() {
+ let s = serde_json::to_string(&OutputFormat::Json).unwrap();
+ assert_eq!(s, "\"json\"");
+ let back: OutputFormat = serde_json::from_str("\"text\"").unwrap();
+ assert_eq!(back, OutputFormat::Text);
+ }
+
+ #[test]
+ fn test_config_roundtrip() {
+ let c = LiteParseConfig::default();
+ let s = serde_json::to_string(&c).unwrap();
+ let back: LiteParseConfig = serde_json::from_str(&s).unwrap();
+ assert_eq!(back.ocr_language, c.ocr_language);
+ assert_eq!(back.output_format, c.output_format);
+ }
}
diff --git a/crates/liteparse/src/conversion.rs b/crates/liteparse/src/conversion.rs
index 70d784a..c988081 100644
--- a/crates/liteparse/src/conversion.rs
+++ b/crates/liteparse/src/conversion.rs
@@ -462,3 +462,117 @@ pub async fn convert_data_to_pdf(
tokio::fs::write(&tmp_path, data).await?;
convert_to_pdf(tmp_path.to_str().unwrap(), password).await
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_is_pdf() {
+ assert!(is_pdf("foo.pdf"));
+ assert!(is_pdf("foo.PDF"));
+ assert!(is_pdf("/abs/dir/Bar.Pdf"));
+ assert!(!is_pdf("foo.docx"));
+ assert!(!is_pdf("foo"));
+ assert!(!is_pdf(""));
+ }
+
+ #[test]
+ fn test_is_supported_extension() {
+ assert!(is_supported_extension("a.pdf"));
+ assert!(is_supported_extension("A.DOCX"));
+ assert!(is_supported_extension("a.pptx"));
+ assert!(is_supported_extension("a.xlsx"));
+ assert!(is_supported_extension("a.png"));
+ assert!(is_supported_extension("a.svg"));
+ assert!(!is_supported_extension("a.exe"));
+ assert!(!is_supported_extension("noext"));
+ }
+
+ #[test]
+ fn test_conversion_tool_display() {
+ assert_eq!(ConverstionTool::ImageMagick.to_string(), "ImageMagick");
+ assert_eq!(ConverstionTool::LibreOffice.to_string(), "LibreOffice");
+ }
+
+ #[test]
+ fn test_get_resolved_path_from_output_first_and_last() {
+ let out = " /usr/bin/foo\n\n/opt/bin/foo\n";
+ assert_eq!(
+ get_resolved_path_from_output(out, false).as_deref(),
+ Some("/usr/bin/foo")
+ );
+ assert_eq!(
+ get_resolved_path_from_output(out, true).as_deref(),
+ Some("/opt/bin/foo")
+ );
+ }
+
+ #[test]
+ fn test_get_resolved_path_from_output_empty() {
+ assert!(get_resolved_path_from_output("", false).is_none());
+ assert!(get_resolved_path_from_output(" \n \n", true).is_none());
+ }
+
+ #[test]
+ fn test_is_windows_system_convert() {
+ // SAFETY: tests run single-threaded for env modification scope
+ unsafe { std::env::set_var("SystemRoot", "C:\\Windows") };
+ assert!(is_windows_system_convert("C:\\Windows\\System32\\convert.exe"));
+ assert!(is_windows_system_convert(
+ "C:/Windows/System32/convert.exe"
+ ));
+ assert!(!is_windows_system_convert(
+ "C:\\Program Files\\ImageMagick\\convert.exe"
+ ));
+ }
+
+ #[test]
+ fn test_guess_extension_from_data_png() {
+ let png_header = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
+ assert_eq!(guess_extension_from_data(&png_header).as_deref(), Some("png"));
+ }
+
+ #[test]
+ fn test_guess_extension_from_data_unknown() {
+ assert!(guess_extension_from_data(&[0u8, 1, 2, 3]).is_none());
+ }
+
+ #[tokio::test]
+ async fn test_execute_command_failure() {
+ let r = execute_command("ls", vec!["/this/definitely/does/not/exist"], 5000).await;
+ assert!(r.is_err());
+ }
+
+ #[tokio::test]
+ async fn test_execute_command_timeout() {
+ let r = execute_command("sleep", vec!["5"], 50).await;
+ assert!(r.is_err());
+ assert!(r.unwrap_err().to_string().contains("timed out"));
+ }
+
+ #[tokio::test]
+ async fn test_execute_command_spawn_error() {
+ let r = execute_command("definitely_not_a_real_command_xyz123", vec![], 1000).await;
+ assert!(r.is_err());
+ }
+
+ #[tokio::test]
+ async fn test_is_path_executable_nonexistent() {
+ assert!(!is_path_executable("/no/such/path/zzz").await);
+ }
+
+ #[tokio::test]
+ async fn test_convert_to_pdf_passthrough_pdf() {
+ let res = convert_to_pdf("/some/file.pdf", None).await.unwrap();
+ assert_eq!(res.pdf_path, "/some/file.pdf");
+ assert_eq!(res.original_extension, "pdf");
+ }
+
+ #[tokio::test]
+ async fn test_convert_to_pdf_unsupported() {
+ let r = convert_to_pdf("/some/file.xyz", None).await;
+ assert!(r.is_err());
+ assert!(r.unwrap_err().to_string().contains("unsupported"));
+ }
+}
diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rs
index f662e8d..37bdca4 100644
--- a/crates/liteparse/src/extract.rs
+++ b/crates/liteparse/src/extract.rs
@@ -683,3 +683,151 @@ impl SegmentBuilder {
self.pending_space = false;
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::f32::consts::PI;
+
+ fn ti(text: &str, x: f32, y: f32, w: f32, h: f32) -> TextItem {
+ TextItem {
+ text: text.to_string(),
+ x,
+ y,
+ width: w,
+ height: h,
+ rotation: 0.0,
+ font_name: None,
+ font_size: None,
+ font_height: None,
+ font_ascent: None,
+ font_descent: None,
+ font_weight: None,
+ font_flags: None,
+ text_width: None,
+ font_is_buggy: false,
+ mcid: None,
+ fill_color: None,
+ stroke_color: None,
+ confidence: None,
+ }
+ }
+
+ #[test]
+ fn dedup_drops_earlier_exact_duplicate() {
+ let mut items = vec![ti("hello", 0.0, 0.0, 10.0, 5.0), ti("hello", 1.0, 0.0, 10.0, 5.0)];
+ dedup_overlapping_items(&mut items);
+ assert_eq!(items.len(), 1);
+ assert_eq!(items[0].x, 1.0);
+ }
+
+ #[test]
+ fn dedup_keeps_non_overlapping() {
+ let mut items = vec![ti("a", 0.0, 0.0, 5.0, 5.0), ti("b", 100.0, 100.0, 5.0, 5.0)];
+ dedup_overlapping_items(&mut items);
+ assert_eq!(items.len(), 2);
+ }
+
+ #[test]
+ fn dedup_drops_earlier_when_different_text_overlaps_heavily() {
+ let mut items = vec![ti("old", 0.0, 0.0, 10.0, 5.0), ti("new", 0.0, 0.0, 10.0, 5.0)];
+ dedup_overlapping_items(&mut items);
+ assert_eq!(items.len(), 1);
+ assert_eq!(items[0].text, "new");
+ }
+
+ #[test]
+ fn dedup_keeps_both_when_different_text_overlaps_lightly() {
+ let mut items = vec![ti("aaa", 0.0, 0.0, 10.0, 5.0), ti("bbb", 9.0, 0.0, 10.0, 5.0)];
+ dedup_overlapping_items(&mut items);
+ assert_eq!(items.len(), 2);
+ }
+
+ #[test]
+ fn dedup_noop_for_empty_or_single() {
+ let mut empty: Vec<TextItem> = vec![];
+ dedup_overlapping_items(&mut empty);
+ assert!(empty.is_empty());
+ let mut one = vec![ti("x", 0.0, 0.0, 1.0, 1.0)];
+ dedup_overlapping_items(&mut one);
+ assert_eq!(one.len(), 1);
+ }
+
+ #[test]
+ fn adjust_angle_no_rotation() {
+ assert!((adjust_angle_for_rotation(0.5, 0) - 0.5).abs() < 1e-6);
+ }
+
+ #[test]
+ fn adjust_angle_180() {
+ let r = adjust_angle_for_rotation(PI, 2);
+ assert!(r.abs() < 1e-5 || (r - 2.0 * PI).abs() < 1e-5);
+ }
+
+ #[test]
+ fn adjust_angle_wraps_into_0_2pi() {
+ let r = adjust_angle_for_rotation(0.0, 1);
+ assert!(r >= 0.0 && r < 2.0 * PI);
+ }
+
+ #[test]
+ fn decompose_scale_identity() {
+ let m = pdfium::Matrix { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 };
+ let (sx, sy) = decompose_scale(&m);
+ assert!((sx - 1.0).abs() < 1e-5);
+ assert!((sy - 1.0).abs() < 1e-5);
+ }
+
+ #[test]
+ fn decompose_scale_uniform() {
+ let m = pdfium::Matrix { a: 2.0, b: 0.0, c: 0.0, d: 2.0, e: 0.0, f: 0.0 };
+ let (sx, sy) = decompose_scale(&m);
+ assert!((sx - 2.0).abs() < 1e-4);
+ assert!((sy - 2.0).abs() < 1e-4);
+ }
+
+ #[test]
+ fn buggy_font_truetype_subset_prefix() {
+ assert!(is_buggy_font("TTFoo", FontType::TrueType));
+ assert!(is_buggy_font("ABCDEF+TTBar", FontType::TrueType));
+ assert!(!is_buggy_font("Arial", FontType::TrueType));
+ }
+
+ #[test]
+ fn buggy_font_type1_underscore() {
+ assert!(is_buggy_font("ABCDEF_Foo", FontType::Type1));
+ assert!(!is_buggy_font("ABCDEF_Foo", FontType::TrueType));
+ assert!(!is_buggy_font("Short", FontType::Type1));
+ }
+
+ #[test]
+ fn buggy_codepoint_ranges() {
+ assert!(is_buggy_codepoint(0x00));
+ assert!(is_buggy_codepoint(0x1F));
+ assert!(!is_buggy_codepoint(0x20));
+ assert!(is_buggy_codepoint(0xE001));
+ assert!(is_buggy_codepoint(0xF8FF));
+ assert!(!is_buggy_codepoint(0xE000));
+ assert!(!is_buggy_codepoint(0xF900));
+ }
+
+ #[test]
+ fn color_to_argb_hex_formats() {
+ let c = pdfium::Color { r: 0xAB, g: 0xCD, b: 0xEF, a: 0x12 };
+ assert_eq!(color_to_argb_hex(&c), "12abcdef");
+ let z = pdfium::Color { r: 0, g: 0, b: 0, a: 0 };
+ assert_eq!(color_to_argb_hex(&z), "00000000");
+ }
+
+ #[test]
+ fn extract_pages_missing_file_errors() {
+ let res = extract_pages("/nonexistent/path/does-not-exist.pdf", None);
+ assert!(res.is_err());
+ }
+
+ #[test]
+ fn extract_pages_filtered_missing_file_errors() {
+ let res = extract_pages_filtered("/nonexistent/path/does-not-exist.pdf", None, 10, None);
+ assert!(res.is_err());
+ }
+}
diff --git a/crates/liteparse/src/ocr/http_simple.rs b/crates/liteparse/src/ocr/http_simple.rs
index b894dfe..68f1ded 100644
--- a/crates/liteparse/src/ocr/http_simple.rs
+++ b/crates/liteparse/src/ocr/http_simple.rs
@@ -94,3 +94,42 @@ impl OcrEngine for HttpOcrEngine {
Ok(results)
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_new_sets_name_and_url() {
+ let e = HttpOcrEngine::new("http://example.com/ocr".into());
+ assert_eq!(e.name(), "http-ocr");
+ assert_eq!(e.server_url, "http://example.com/ocr");
+ }
+
+ #[test]
+ fn test_response_deserializes() {
+ let raw = r#"{"results":[{"text":"hi","bbox":[1.0,2.0,3.0,4.0],"confidence":0.85}]}"#;
+ let parsed: HttpOcrResponse = serde_json::from_str(raw).unwrap();
+ assert_eq!(parsed.results.len(), 1);
+ assert_eq!(parsed.results[0].text, "hi");
+ assert_eq!(parsed.results[0].bbox, [1.0, 2.0, 3.0, 4.0]);
+ assert!((parsed.results[0].confidence - 0.85).abs() < 1e-6);
+ }
+
+ #[test]
+ fn test_response_deserializes_empty() {
+ let raw = r#"{"results":[]}"#;
+ let parsed: HttpOcrResponse = serde_json::from_str(raw).unwrap();
+ assert!(parsed.results.is_empty());
+ }
+
+ #[test]
+ fn test_recognize_network_error() {
+ let e = HttpOcrEngine::new("http://127.0.0.1:1/ocr".into());
+ let opts = OcrOptions {
+ language: "eng".into(),
+ };
+ let r = e.recognize(&[0u8; 4], 1, 1, &opts);
+ assert!(r.is_err());
+ }
+}
diff --git a/crates/liteparse/src/ocr/mod.rs b/crates/liteparse/src/ocr/mod.rs
index 11c39a8..4deea01 100644
--- a/crates/liteparse/src/ocr/mod.rs
+++ b/crates/liteparse/src/ocr/mod.rs
@@ -25,3 +25,54 @@ pub trait OcrEngine {
options: &OcrOptions,
) -> Result<Vec<OcrResult>, Box<dyn std::error::Error>>;
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ struct DummyEngine;
+ impl OcrEngine for DummyEngine {
+ fn name(&self) -> &str {
+ "dummy"
+ }
+ fn recognize(
+ &self,
+ _image_data: &[u8],
+ _width: u32,
+ _height: u32,
+ options: &OcrOptions,
+ ) -> Result<Vec<OcrResult>, Box<dyn std::error::Error>> {
+ Ok(vec![OcrResult {
+ text: format!("lang={}", options.language),
+ bbox: [0.0, 0.0, 10.0, 10.0],
+ confidence: 0.9,
+ }])
+ }
+ }
+
+ #[test]
+ fn test_engine_trait_object() {
+ let engine: Box<dyn OcrEngine> = Box::new(DummyEngine);
+ assert_eq!(engine.name(), "dummy");
+ let opts = OcrOptions {
+ language: "eng".into(),
+ };
+ let r = engine.recognize(&[], 1, 1, &opts).unwrap();
+ assert_eq!(r.len(), 1);
+ assert_eq!(r[0].text, "lang=eng");
+ assert_eq!(r[0].bbox, [0.0, 0.0, 10.0, 10.0]);
+ assert!((r[0].confidence - 0.9).abs() < 1e-6);
+ }
+
+ #[test]
+ fn test_ocr_result_clone() {
+ let r = OcrResult {
+ text: "hi".into(),
+ bbox: [1.0, 2.0, 3.0, 4.0],
+ confidence: 0.5,
+ };
+ let c = r.clone();
+ assert_eq!(c.text, "hi");
+ assert_eq!(c.bbox, [1.0, 2.0, 3.0, 4.0]);
+ }
+}
diff --git a/crates/liteparse/src/ocr/tesseract.rs b/crates/liteparse/src/ocr/tesseract.rs
index ec75357..4d74c36 100644
--- a/crates/liteparse/src/ocr/tesseract.rs
+++ b/crates/liteparse/src/ocr/tesseract.rs
@@ -121,3 +121,42 @@ fn default_tessdata_dir() -> String {
}
"tessdata".to_string()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_normalize_language_known_codes() {
+ assert_eq!(TesseractOcrEngine::normalize_language("en"), "eng");
+ assert_eq!(TesseractOcrEngine::normalize_language("EN"), "eng");
+ assert_eq!(TesseractOcrEngine::normalize_language(" fr "), "fra");
+ assert_eq!(TesseractOcrEngine::normalize_language("zh"), "chi_sim");
+ assert_eq!(TesseractOcrEngine::normalize_language("zh-tw"), "chi_tra");
+ assert_eq!(TesseractOcrEngine::normalize_language("ja"), "jpn");
+ }
+
+ #[test]
+ fn test_normalize_language_passthrough_for_unknown() {
+ assert_eq!(TesseractOcrEngine::normalize_language("eng"), "eng");
+ assert_eq!(TesseractOcrEngine::normalize_language("xyz"), "xyz");
+ }
+
+ #[test]
+ fn test_engine_name() {
+ let e = TesseractOcrEngine::new(None);
+ assert_eq!(e.name(), "tesseract");
+ }
+
+ #[test]
+ fn test_new_stores_tessdata_path() {
+ let e = TesseractOcrEngine::new(Some("/custom/tessdata".to_string()));
+ assert_eq!(e.tessdata_path.as_deref(), Some("/custom/tessdata"));
+ }
+
+ #[test]
+ fn test_default_tessdata_dir_non_empty() {
+ let d = default_tessdata_dir();
+ assert!(!d.is_empty());
+ }
+}
diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rs
index 85c1a2f..90435fd 100644
--- a/crates/liteparse/src/ocr_merge.rs
+++ b/crates/liteparse/src/ocr_merge.rs
@@ -191,4 +191,60 @@ mod tests {
assert_eq!(clean_ocr_table_artifacts(""), "");
assert_eq!(clean_ocr_table_artifacts("|||"), "|||");
}
+
+ fn make_item(x: f32, y: f32, w: f32, h: f32) -> TextItem {
+ TextItem {
+ text: "x".into(),
+ x,
+ y,
+ width: w,
+ height: h,
+ rotation: 0.0,
+ font_name: None,
+ font_size: None,
+ font_height: None,
+ font_ascent: None,
+ font_descent: None,
+ font_weight: None,
+ font_flags: None,
+ text_width: None,
+ font_is_buggy: false,
+ mcid: None,
+ fill_color: None,
+ stroke_color: None,
+ confidence: None,
+ }
+ }
+
+ #[test]
+ fn test_overlaps_existing_text_inside() {
+ let items = vec![make_item(10.0, 10.0, 20.0, 5.0)];
+ assert!(overlaps_existing_text(&items, 12.0, 11.0, 5.0, 2.0, 2.0));
+ }
+
+ #[test]
+ fn test_overlaps_existing_text_disjoint() {
+ let items = vec![make_item(10.0, 10.0, 20.0, 5.0)];
+ assert!(!overlaps_existing_text(&items, 100.0, 100.0, 5.0, 5.0, 2.0));
+ }
+
+ #[test]
+ fn test_overlaps_existing_text_tolerance() {
+ let items = vec![make_item(10.0, 10.0, 20.0, 5.0)];
+ // Just outside but within tolerance
+ assert!(overlaps_existing_text(&items, 31.0, 10.0, 5.0, 5.0, 2.0));
+ // Beyond tolerance
+ assert!(!overlaps_existing_text(&items, 35.0, 10.0, 5.0, 5.0, 2.0));
+ }
+
+ #[test]
+ fn test_overlaps_empty() {
+ assert!(!overlaps_existing_text(&[], 0.0, 0.0, 1.0, 1.0, 0.0));
+ }
+
+ #[test]
+ fn test_clean_ocr_keeps_whitespace_trimmed() {
+ assert_eq!(clean_ocr_table_artifacts(" "), "");
+ assert_eq!(clean_ocr_table_artifacts(" 123 "), "123");
+ }
}
diff --git a/crates/liteparse/src/output/json.rs b/crates/liteparse/src/output/json.rs
index 29f6e44..ba1a4cc 100644
--- a/crates/liteparse/src/output/json.rs
+++ b/crates/liteparse/src/output/json.rs
@@ -64,3 +64,72 @@ pub fn format_json(pages: &[ParsedPage]) -> Result<String, serde_json::Error> {
let result = build_json(pages);
serde_json::to_string_pretty(&result)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::types::{ParsedPage, TextItem};
+
+ fn item(text: &str, conf: Option<f32>) -> TextItem {
+ TextItem {
+ text: text.into(),
+ x: 1.0,
+ y: 2.0,
+ width: 3.0,
+ height: 4.0,
+ rotation: 0.0,
+ font_name: Some("Helv".into()),
+ font_size: Some(10.0),
+ font_height: None,
+ font_ascent: None,
+ font_descent: None,
+ font_weight: None,
+ font_flags: None,
+ text_width: None,
+ font_is_buggy: false,
+ mcid: None,
+ fill_color: None,
+ stroke_color: None,
+ confidence: conf,
+ }
+ }
+
+ fn page(items: Vec<TextItem>) -> ParsedPage {
+ ParsedPage {
+ page_number: 1,
+ page_width: 612.0,
+ page_height: 792.0,
+ text: "txt".into(),
+ text_items: items,
+ }
+ }
+
+ #[test]
+ fn test_build_json_native_text_defaults_confidence_to_one() {
+ let j = build_json(&[page(vec![item("hi", None)])]);
+ assert_eq!(j.pages.len(), 1);
+ assert_eq!(j.pages[0].page, 1);
+ assert_eq!(j.pages[0].text_items[0].confidence, Some(1.0));
+ assert_eq!(j.pages[0].text_items[0].font_name.as_deref(), Some("Helv"));
+ }
+
+ #[test]
+ fn test_build_json_preserves_ocr_confidence() {
+ let j = build_json(&[page(vec![item("hi", Some(0.42))])]);
+ assert_eq!(j.pages[0].text_items[0].confidence, Some(0.42));
+ }
+
+ #[test]
+ fn test_format_json_pretty() {
+ let s = format_json(&[page(vec![item("hi", None)])]).unwrap();
+ assert!(s.contains("\n"));
+ assert!(s.contains("\"text\": \"hi\""));
+ assert!(s.contains("\"page\": 1"));
+ }
+
+ #[test]
+ fn test_build_json_empty() {
+ let j = build_json(&[]);
+ assert!(j.pages.is_empty());
+ }
+}
diff --git a/crates/liteparse/src/output/text.rs b/crates/liteparse/src/output/text.rs
index 5886af3..d451a7a 100644
--- a/crates/liteparse/src/output/text.rs
+++ b/crates/liteparse/src/output/text.rs
@@ -8,3 +8,38 @@ pub fn format_text(pages: &[ParsedPage]) -> String {
.collect::<Vec<_>>()
.join("\n\n")
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn page(n: usize, text: &str) -> ParsedPage {
+ ParsedPage {
+ page_number: n,
+ page_width: 0.0,
+ page_height: 0.0,
+ text: text.into(),
+ text_items: vec![],
+ }
+ }
+
+ #[test]
+ fn test_format_text_empty() {
+ assert_eq!(format_text(&[]), "");
+ }
+
+ #[test]
+ fn test_format_text_single_page() {
+ let out = format_text(&[page(1, "hello")]);
+ assert!(out.contains("--- Page 1 ---"));
+ assert!(out.contains("hello"));
+ }
+
+ #[test]
+ fn test_format_text_multiple_pages_joined() {
+ let out = format_text(&[page(1, "a"), page(2, "b")]);
+ assert!(out.contains("--- Page 1 ---"));
+ assert!(out.contains("--- Page 2 ---"));
+ assert!(out.find("a").unwrap() < out.find("b").unwrap());
+ }
+}
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index 6f67dae..0f3516a 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -127,3 +127,51 @@ impl LiteParse {
&self.config
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::types::ParsedPage;
+
+ #[test]
+ fn test_new_stores_config() {
+ let mut cfg = LiteParseConfig::default();
+ cfg.ocr_enabled = false;
+ cfg.max_pages = 7;
+ let lp = LiteParse::new(cfg);
+ assert!(!lp.config().ocr_enabled);
+ assert_eq!(lp.config().max_pages, 7);
+ }
+
+ fn fake_result() -> ParseResult {
+ ParseResult {
+ pages: vec![ParsedPage {
+ page_number: 1,
+ page_width: 100.0,
+ page_height: 200.0,
+ text: "hello".into(),
+ text_items: vec![],
+ }],
+ text: "hello".into(),
+ }
+ }
+
+ #[test]
+ fn test_format_json() {
+ let mut cfg = LiteParseConfig::default();
+ cfg.output_format = OutputFormat::Json;
+ let lp = LiteParse::new(cfg);
+ let s = lp.format(&fake_result()).unwrap();
+ assert!(s.contains("\"page\""));
+ assert!(s.contains("\"hello\""));
+ }
+
+ #[test]
+ fn test_format_text() {
+ let mut cfg = LiteParseConfig::default();
+ cfg.output_format = OutputFormat::Text;
+ let lp = LiteParse::new(cfg);
+ let s = lp.format(&fake_result()).unwrap();
+ assert!(s.contains("hello"));
+ }
+}
diff --git a/crates/liteparse/src/render.rs b/crates/liteparse/src/render.rs
index 5ff37af..642b1bf 100644
--- a/crates/liteparse/src/render.rs
+++ b/crates/liteparse/src/render.rs
@@ -98,3 +98,33 @@ pub fn image_bounds(
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_image_bounds_output_serializes() {
+ let b = ImageBoundsOutput {
+ x: 1.0,
+ y: 2.0,
+ width: 3.0,
+ height: 4.0,
+ };
+ let s = serde_json::to_string(&b).unwrap();
+ assert!(s.contains("\"x\":1"));
+ assert!(s.contains("\"width\":3"));
+ }
+
+ #[test]
+ fn test_screenshot_missing_file_errors() {
+ let r = screenshot("/nonexistent/path/does_not_exist.pdf", 1, 72.0, "/tmp/out.png");
+ assert!(r.is_err());
+ }
+
+ #[test]
+ fn test_image_bounds_missing_file_errors() {
+ let r = image_bounds("/nonexistent/path/does_not_exist.pdf", None);
+ assert!(r.is_err());
+ }
+}
diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rs
index 93f3dca..8407c83 100644
--- a/crates/liteparse/src/types.rs
+++ b/crates/liteparse/src/types.rs
@@ -113,3 +113,86 @@ pub struct ProjectedTextItem {
}
pub type AnchorMap = HashMap<i32, Vec<(usize, usize)>>;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sample_item() -> TextItem {
+ TextItem {
+ text: "hi".into(),
+ x: 1.0,
+ y: 2.0,
+ width: 10.0,
+ height: 4.0,
+ rotation: 0.0,
+ font_name: Some("Arial".into()),
+ font_size: Some(12.0),
+ font_height: None,
+ font_ascent: None,
+ font_descent: None,
+ font_weight: None,
+ font_flags: None,
+ text_width: None,
+ font_is_buggy: false,
+ mcid: None,
+ fill_color: None,
+ stroke_color: None,
+ confidence: None,
+ }
+ }
+
+ #[test]
+ fn output_format_serializes() {
+ assert_eq!(serde_json::to_string(&OutputFormat::Json).unwrap(), "\"Json\"");
+ assert_eq!(serde_json::to_string(&OutputFormat::Text).unwrap(), "\"Text\"");
+ }
+
+ #[test]
+ fn input_type_roundtrip() {
+ let v = InputType::FilePath("/tmp/x.pdf".into());
+ let s = serde_json::to_string(&v).unwrap();
+ let back: InputType = serde_json::from_str(&s).unwrap();
+ match back {
+ InputType::FilePath(p) => assert_eq!(p, "/tmp/x.pdf"),
+ _ => panic!("wrong variant"),
+ }
+ }
+
+ #[test]
+ fn text_item_skips_none_fields() {
+ let item = sample_item();
+ let s = serde_json::to_string(&item).unwrap();
+ assert!(!s.contains("font_height"));
+ assert!(!s.contains("confidence"));
+ assert!(!s.contains("font_is_buggy"));
+ assert!(s.contains("\"text\":\"hi\""));
+ }
+
+ #[test]
+ fn text_item_includes_buggy_flag_when_true() {
+ let mut item = sample_item();
+ item.font_is_buggy = true;
+ let s = serde_json::to_string(&item).unwrap();
+ assert!(s.contains("font_is_buggy"));
+ }
+
+ #[test]
+ fn page_serializes() {
+ let p = Page {
+ page_number: 1,
+ page_width: 100.0,
+ page_height: 200.0,
+ text_items: vec![sample_item()],
+ };
+ let s = serde_json::to_string(&p).unwrap();
+ assert!(s.contains("\"page_number\":1"));
+ }
+
+ #[test]
+ fn anchor_map_basic() {
+ let mut m: AnchorMap = HashMap::new();
+ m.entry(5).or_default().push((1, 2));
+ assert_eq!(m.get(&5).unwrap()[0], (1, 2));
+ }
+}