[statement] Parsing: strict CSV, amount and date fields, decoding; no bank until real samples arrive
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
//! Mandatory test 2: every real sample in `fixtures/<bank>/` parses to exactly its `.expected.json`, and
|
||||
//! every truncation of it is an error or a prefix of whole lines.
|
||||
//!
|
||||
//! A sample is any file in `fixtures/<bank>/` other than `*.expected.json` and `README*`. Day 1 has no
|
||||
//! samples, so this test walks an empty tree; it starts to bite the moment a sample is added (and fails until
|
||||
//! that bank has a parser and the expected rows).
|
||||
|
||||
use fiscus_statement::{parse, Statement};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn samples() -> Vec<PathBuf> {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
|
||||
let mut out = Vec::new();
|
||||
let Ok(banks) = std::fs::read_dir(&root) else { return out };
|
||||
for bank in banks.flatten().filter(|e| e.path().is_dir()) {
|
||||
for f in std::fs::read_dir(bank.path()).unwrap().flatten() {
|
||||
let name = f.file_name().to_string_lossy().to_string();
|
||||
if f.path().is_file() && !name.ends_with(".expected.json") && !name.starts_with("README") {
|
||||
out.push(f.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
fn expected_for(sample: &Path) -> PathBuf {
|
||||
let name = sample.file_name().unwrap().to_string_lossy();
|
||||
sample.with_file_name(format!("{name}.expected.json"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_fixture_parses_to_its_expected_rows() {
|
||||
let all = samples();
|
||||
eprintln!("statement fixtures: {}", all.len());
|
||||
for sample in all {
|
||||
let bytes = std::fs::read(&sample).unwrap();
|
||||
let want: Statement = serde_json::from_slice(
|
||||
&std::fs::read(expected_for(&sample)).unwrap_or_else(|_| panic!("{} has no .expected.json", sample.display())),
|
||||
)
|
||||
.unwrap();
|
||||
let got = parse(&bytes).unwrap_or_else(|e| panic!("{}: {e}", sample.display()));
|
||||
assert_eq!(got, want, "{}", sample.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_truncated_fixture_is_an_error_or_whole_lines() {
|
||||
for sample in samples() {
|
||||
let bytes = std::fs::read(&sample).unwrap();
|
||||
let full = parse(&bytes).unwrap();
|
||||
let step = (bytes.len() / 2000).max(1);
|
||||
for cut in (0..bytes.len()).step_by(step) {
|
||||
if let Ok(st) = parse(&bytes[..cut]) {
|
||||
assert!(st.lines.len() <= full.lines.len(), "{} cut at {cut}", sample.display());
|
||||
for (got, want) in st.lines.iter().zip(&full.lines) {
|
||||
assert_eq!(got, want, "{} cut at {cut}: a partial line", sample.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Mandatory test 2: hostile statement input. Random bytes and every truncation give a typed error or only
|
||||
//! whole rows, never a panic and never a partial row.
|
||||
|
||||
use fiscus_ledger::Haler;
|
||||
use fiscus_statement::csv::{read, CsvError, Dialect};
|
||||
use fiscus_statement::field::{amount, date_dmy, FieldError};
|
||||
use fiscus_statement::{decode, parse, Encoding, ParseError, MAX_FILE};
|
||||
use proptest::prelude::*;
|
||||
|
||||
const STRICT: Dialect = Dialect { delimiter: ';', final_newline: true };
|
||||
|
||||
/// A generic RFC 4180 file (not any bank's format): quotes, an escaped quote, a line break inside a field,
|
||||
/// CRLF, diacritics.
|
||||
const SAMPLE: &str = "date;amount;merchant;note\r\n\
|
||||
03.10.2026;-129,00;Albert;\r\n\
|
||||
04.10.2026;\"-1 234,50\";\"Kavárna \"\"U Nováků\"\"\";\"two\nlines\"\r\n\
|
||||
05.10.2026;35 000,00;Mzda;říjen\r\n";
|
||||
|
||||
#[test]
|
||||
fn reads_the_generic_sample() {
|
||||
let rows = read(SAMPLE, STRICT).unwrap();
|
||||
assert_eq!(rows.len(), 4);
|
||||
assert_eq!(rows[2].fields, vec!["04.10.2026", "-1 234,50", "Kavárna \"U Nováků\"", "two\nlines"]);
|
||||
assert_eq!(rows[3].line, 5, "the row after a two-line field starts on line 5");
|
||||
assert_eq!(amount(&rows[2].fields[1], ','), Ok(Haler(-123_450)));
|
||||
assert_eq!(amount(&rows[3].fields[1], ','), Ok(Haler(3_500_000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_truncation_is_an_error_or_whole_rows() {
|
||||
let full = read(SAMPLE, STRICT).unwrap();
|
||||
for cut in 0..SAMPLE.len() {
|
||||
if !SAMPLE.is_char_boundary(cut) {
|
||||
continue;
|
||||
}
|
||||
match read(&SAMPLE[..cut], STRICT) {
|
||||
Err(_) => {}
|
||||
Ok(rows) => {
|
||||
assert!(rows.len() <= full.len());
|
||||
for (got, want) in rows.iter().zip(&full) {
|
||||
assert_eq!(got, want, "a partial row at cut {cut}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn irregular_csv_is_refused_with_its_line() {
|
||||
let cases: &[(&str, usize, CsvError)] = &[
|
||||
("a;b\nc;d;e\n", 2, CsvError::Ragged { expected: 2, found: 3 }),
|
||||
("a;b\nc\n", 2, CsvError::Ragged { expected: 2, found: 1 }),
|
||||
("a;b\n\nc;d\n", 2, CsvError::Ragged { expected: 2, found: 1 }),
|
||||
("a;b\nc\"x;d\n", 2, CsvError::BareQuote),
|
||||
("a;b\n\"c;d\n", 2, CsvError::UnterminatedQuote),
|
||||
("a;b\n\"c\"x;d\n", 2, CsvError::TextAfterQuote),
|
||||
("a;b\nc;d", 2, CsvError::MissingFinalNewline),
|
||||
("a;b\rc;d\n", 1, CsvError::LoneCarriageReturn),
|
||||
];
|
||||
for (text, line, kind) in cases {
|
||||
assert_eq!(read(text, STRICT), Err((*line, kind.clone())), "{text:?}");
|
||||
}
|
||||
let long = format!("a\n{}\n", "x".repeat(70_000));
|
||||
assert_eq!(read(&long, STRICT), Err((2, CsvError::RowTooLong)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn amounts() {
|
||||
let ok: &[(&str, char, i64)] = &[
|
||||
("-1 234,50", ',', -123_450),
|
||||
("1234,50", ',', 123_450),
|
||||
("\u{2212}12,00", ',', -1_200),
|
||||
("1.234,50", ',', 123_450),
|
||||
("+5,5", ',', 550),
|
||||
("1\u{a0}000\u{a0}000,00", ',', 100_000_000),
|
||||
("-1,234.50", '.', -123_450),
|
||||
("0,01", ',', 1),
|
||||
("12", ',', 1_200),
|
||||
];
|
||||
for (text, dec, want) in ok {
|
||||
assert_eq!(amount(text, *dec), Ok(Haler(*want)), "{text:?}");
|
||||
}
|
||||
let bad = ["", "-", "1,2,3", "12,345", "1 23,00", "12 3456,00", "--5", "5-", "1e3", "12,", ",50", "NaN", "0x10", "١٢٣", "12.50"];
|
||||
for text in bad {
|
||||
assert!(amount(text, ',').is_err(), "{text:?} must be refused");
|
||||
}
|
||||
assert!(matches!(amount("12,345", ','), Err(FieldError::TooPrecise(_))));
|
||||
assert_eq!(amount("99999999999999999999,00", ','), Err(FieldError::Overflow));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dates() {
|
||||
assert_eq!(date_dmy("03.11.2026").unwrap().to_string(), "2026-11-03");
|
||||
assert_eq!(date_dmy("3.1.2026").unwrap().to_string(), "2026-01-03");
|
||||
for bad in ["31.02.2026", "03.11.26", "2026.11.03", "03/11/2026", "03.11.2026x", "", "0.0.0000"] {
|
||||
assert!(date_dmy(bad).is_err(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoding_is_strict() {
|
||||
assert_eq!(decode(b"\xEF\xBB\xBFa;b\n", Encoding::Utf8).unwrap(), "a;b\n");
|
||||
assert!(matches!(decode(b"a;\xC3\x28\n", Encoding::Utf8), Err(ParseError::Encoding { offset: 2 })));
|
||||
assert!(matches!(decode(b"a\x00b", Encoding::Utf8), Err(ParseError::Encoding { offset: 1 })));
|
||||
// "Příliš" in Windows-1250.
|
||||
assert_eq!(decode(b"P\xF8\xEDli\x9A", Encoding::Windows1250).unwrap(), "Příliš");
|
||||
assert!(matches!(decode(b"x\x81", Encoding::Windows1250), Err(ParseError::Encoding { .. })));
|
||||
assert_eq!(decode(b"", Encoding::Utf8), Err(ParseError::Empty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_bank_is_supported_without_samples() {
|
||||
assert!(fiscus_statement::BANKS.is_empty());
|
||||
assert_eq!(parse(SAMPLE.as_bytes()), Err(ParseError::UnsupportedFormat));
|
||||
assert_eq!(parse(b""), Err(ParseError::Empty));
|
||||
let huge = vec![b'a'; MAX_FILE + 1];
|
||||
assert_eq!(parse(&huge), Err(ParseError::TooLarge { size: MAX_FILE + 1 }));
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(2000))]
|
||||
|
||||
#[test]
|
||||
fn random_bytes_never_panic(bytes in prop::collection::vec(any::<u8>(), 0..400)) {
|
||||
let _ = parse(&bytes);
|
||||
for enc in [Encoding::Utf8, Encoding::Windows1250] {
|
||||
if let Ok(text) = decode(&bytes, enc) {
|
||||
for dialect in [STRICT, Dialect { delimiter: ',', final_newline: false }] {
|
||||
if let Ok(rows) = read(&text, dialect) {
|
||||
if let Some(first) = rows.first() {
|
||||
prop_assert!(rows.iter().all(|r| r.fields.len() == first.fields.len()));
|
||||
}
|
||||
for r in &rows {
|
||||
for f in &r.fields {
|
||||
let _ = amount(f, ',');
|
||||
let _ = date_dmy(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_like_noise_never_panics(text in "[a;\"\r\n,0-9 ]{0,200}") {
|
||||
let _ = read(&text, STRICT);
|
||||
let _ = read(&text, Dialect { delimiter: ',', final_newline: false });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn amounts_round_trip(h in -100_000_000_000i64..100_000_000_000) {
|
||||
prop_assert_eq!(amount(&Haler(h).to_czk(), ','), Ok(Haler(h)));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user