en16931-cli 0.7.2

The EN 16931 validator as a command. Validates UBL, CII and ZUGFeRD/Factur-X PDFs against the core model, XRechnung and Peppol BIS Billing 3.0; converts between the two syntaxes; compares two documents as invoices rather than as XML; reports as text, JSON or SVRL.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
//! The command, exercised as a command.
//!
//! # Why the exit codes get their own tests
//!
//! The library is covered by the libraries' suites; what this crate adds is a
//! *process contract*, and the part of it people build on is the exit code. A CI
//! job that cannot tell "this invoice is invalid" (`1`) from "that path does not
//! exist" (`2`) will eventually ship an invoice because a volume was not
//! mounted, and no amount of library testing catches that.

use std::io::Write as _;

use assert_cmd::Command;
use predicates::prelude::PredicateBooleanExt as _;
use predicates::str::contains;

/// Run the command, expect success, and return its standard output.
///
/// Hoisted out of the four tests that each declared their own closure: a
/// helper copied four times is four places to fix when the invocation changes.
fn stdout(args: &[&str]) -> String {
    let out = cli()
        .args(args)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    String::from_utf8(out).expect("the CLI writes UTF-8")
}

/// A minimal but *core-valid* UBL invoice, written from the model rather than
/// pasted — a fixture that drifts out of validity tests nothing.
fn valid_ubl() -> String {
    use en16931::invoice::*;
    use en16931::{Date, Identifier, Invoice, InvoiceAmount, InvoiceLine, Percentage, Quantity};

    let party = |name: &str, country: &str| Party {
        name: Some(name.to_owned()),
        vat_identifier: Some(format!("{country}123456789")),
        electronic_address: Some(Identifier::schemed(name, "0088")),
        address: PostalAddress {
            city: Some("Musterstadt".to_owned()),
            post_code: Some("12345".to_owned()),
            country: Some(Code::new(country)),
            ..Default::default()
        },
        ..Default::default()
    };
    let invoice = Invoice::builder(
        en16931::profiles::EN16931.specification_id,
        "CLI-1",
        Date::parse("2026-07-31").expect("date"),
        "380",
        "EUR",
    )
    .seller(party("Seller GmbH", "DE"))
    .buyer(party("Buyer BV", "NL"))
    .due_in_days(14)
    .line(InvoiceLine::new(
        "1",
        "Widget",
        Quantity::ONE,
        "C62",
        InvoiceAmount::parse("100.00").expect("amount"),
        "S",
        Some(Percentage::new(rust_decimal::Decimal::from(19))),
    ))
    .build_reconciled()
    .expect("reconciles");
    assert!(en16931::validate(&invoice).is_valid());
    en16931_formats::ubl::to_string(&invoice)
}

/// Write a fixture to a path **no other test can be writing at the same time**.
///
/// `cargo test` runs these in parallel threads of one process, and the first
/// version of this keyed the filename on `name` alone — so two tests both
/// wanting `valid.xml` truncated the file under each other and one of them read
/// an empty document. Intermittently, and only under load.
fn write_temp(name: &str, body: &str) -> std::path::PathBuf {
    use std::sync::atomic::{AtomicU32, Ordering};
    static NEXT: AtomicU32 = AtomicU32::new(0);

    let unique = NEXT.fetch_add(1, Ordering::Relaxed);
    let path = std::env::temp_dir().join(format!(
        "en16931-cli-{}-{unique}-{name}",
        std::process::id()
    ));
    let mut f = std::fs::File::create(&path).expect("create fixture");
    f.write_all(body.as_bytes()).expect("write fixture");
    f.sync_all().expect("flush fixture");
    path
}

fn cli() -> Command {
    Command::cargo_bin("en16931").expect("the binary is built")
}

#[test]
fn a_valid_invoice_exits_zero() {
    let path = write_temp("valid.xml", &valid_ubl());
    cli()
        .args(["validate", path.to_str().unwrap()])
        .assert()
        .success()
        .stdout(contains("valid"));
}

#[test]
fn an_invalid_invoice_exits_one_and_says_which_rules() {
    let path = write_temp(
        "empty.xml",
        r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#,
    );
    cli()
        .args(["validate", path.to_str().unwrap()])
        .assert()
        .code(1)
        .stdout(contains("BR-02")) // no invoice number
        .stdout(contains("BR-16")); // no invoice line
}

/// The distinction the whole exit-code contract exists for.
#[test]
fn an_unreadable_document_exits_two_not_one() {
    cli()
        .args(["validate", "/definitely/not/here.xml"])
        .assert()
        .code(2);

    let path = write_temp("nonsense.xml", "<html/>");
    cli()
        .args(["validate", path.to_str().unwrap()])
        .assert()
        .code(2)
        .stderr(contains("not an e-invoice"));
}

#[test]
fn the_rule_set_comes_from_bt_24_by_default() {
    let path = write_temp("valid.xml", &valid_ubl());
    // Declared core, so core is what runs.
    cli()
        .args(["validate", path.to_str().unwrap()])
        .assert()
        .success()
        .stdout(contains("EN 16931 validation"));
    // …and naming a profile overrides it, which is how you ask "would this
    // pass in Germany?" about a document that does not claim to.
    cli()
        .args([
            "validate",
            path.to_str().unwrap(),
            "--profile",
            "XRechnung 3.0",
        ])
        .assert()
        .code(1)
        .stdout(contains("BR-DE-15"));
}

#[test]
fn an_unknown_profile_is_refused_with_the_list() {
    cli()
        .args(["validate", "-", "--profile", "XRechnung 9.9"])
        .assert()
        .code(2)
        .stderr(contains("unknown profile"))
        // The list offers the *slugs*, because those are what a person types.
        .stderr(contains("xrechnung-extension"))
        .stderr(contains("peppol"));
}

/// A profile is selectable by the name that needs no quoting.
///
/// `--profile "XRechnung 3.0"` was the only spelling that worked, which is a
/// selector every shell needs quoted and every person gets wrong once.
#[test]
fn a_profile_is_selectable_by_slug_name_or_bt24() {
    let path = write_temp("slug.xml", &valid_ubl());
    let file = path.to_str().expect("utf-8 path");
    for spelling in [
        "xrechnung",
        "XRECHNUNG",
        "XRechnung 3.0",
        en16931::profiles::XRECHNUNG.specification_id,
    ] {
        cli()
            .args(["validate", file, "--profile", spelling, "--format", "json"])
            .assert()
            .stdout(contains("XRechnung 3.0"));
    }
}

#[test]
fn a_conversion_round_trips_through_the_model() {
    let path = write_temp("valid.xml", &valid_ubl());
    let cii = cli()
        .args(["convert", path.to_str().unwrap(), "--to", "cii"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let cii = String::from_utf8(cii).expect("UTF-8");
    assert!(cii.contains("CrossIndustryInvoice"));

    // Reading it back gives a document that still validates — the conversion
    // went through the semantic model, so this is a claim about meaning and not
    // about element names.
    let back = write_temp("roundtrip.xml", &cii);
    cli()
        .args(["validate", back.to_str().unwrap()])
        .assert()
        .success();
}

/// `--profile` on `convert` refuses to write a document that would be rejected.
#[test]
fn converting_for_a_profile_refuses_rather_than_writing_something_invalid() {
    let path = write_temp("valid.xml", &valid_ubl());
    cli()
        .args([
            "convert",
            path.to_str().unwrap(),
            "--to",
            "cii",
            "--profile",
            "XRechnung 3.0",
        ])
        .assert()
        .code(1)
        .stdout(predicates::str::is_empty()) // nothing half-written
        .stderr(contains("BR-DE-15"));
}

#[test]
fn stdin_is_a_document_source() {
    cli()
        .args(["inspect", "-"])
        .write_stdin(valid_ubl())
        .assert()
        .success()
        .stdout(contains("UBL 2.1"))
        .stdout(contains("CLI-1"));
}

#[test]
fn json_output_carries_the_versioned_schema() {
    let path = write_temp("valid.xml", &valid_ubl());
    let out = cli()
        .args(["validate", path.to_str().unwrap(), "--format", "json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let value: serde_json::Value = serde_json::from_slice(&out).expect("valid JSON");
    assert_eq!(value["schema"], en16931::report::SCHEMA);
    assert_eq!(value["valid"], true);
    // Always an array, even for one document — a consumer must not have to
    // branch on the shape of the top level.
    assert_eq!(value["documents"].as_array().map(Vec::len), Some(1));
}

#[test]
fn svrl_output_is_well_formed() {
    let path = write_temp(
        "empty.xml",
        r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#,
    );
    let out = cli()
        .args(["validate", path.to_str().unwrap(), "--format", "svrl"])
        .assert()
        .code(1)
        .get_output()
        .stdout
        .clone();
    let xml = String::from_utf8(out).expect("UTF-8");
    roxmltree::Document::parse(&xml).expect("well-formed SVRL");
}

/// SVRL is a validation report format, so asking `inspect` for one is a mistake
/// worth naming rather than an empty file worth debugging.
#[test]
fn inspect_refuses_svrl_and_says_why() {
    cli()
        .args(["inspect", "-", "--format", "svrl"])
        .write_stdin(valid_ubl())
        .assert()
        .code(2)
        .stderr(contains("does not validate"));
}

#[test]
fn suppressions_are_recorded_in_the_output() {
    let path = write_temp("valid.xml", &valid_ubl());
    cli()
        .args([
            "validate",
            path.to_str().unwrap(),
            "--profile",
            "XRechnung 3.0",
            "--without",
            "BR-DE-15",
        ])
        .assert()
        .code(1) // the other BR-DE rules still fire
        .stdout(contains("suppressed and NOT checked: BR-DE-15"));
}

#[test]
fn explain_resolves_rules_restrictions_and_every_spelling() {
    for query in ["BR-CO-14", "br-co-3", "BR-IG-1"] {
        cli().args(["explain", query]).assert().success();
    }
    // A restriction is not a rule and still appears in reports under its id.
    cli()
        .args(["explain", "BR-DE-3"])
        .assert()
        .success()
        .stdout(contains("restriction"));

    cli()
        .args(["explain", "BR-NOPE-99"])
        .assert()
        .code(2)
        .stderr(contains("no rule or restriction"));
}

#[test]
fn profiles_lists_what_this_build_can_check() {
    cli()
        .arg("profiles")
        .assert()
        .success()
        .stdout(contains("XRechnung 3.0"))
        .stdout(contains(en16931::ARTEFACT_VERSION))
        // The licence condition travels with every user-visible surface.
        .stdout(contains(en16931::ATTRIBUTION));
}

/// A run over several documents reports each and fails if any one fails.
#[test]
fn a_batch_run_names_every_document_and_fails_on_the_worst() {
    let good = write_temp("valid.xml", &valid_ubl());
    let bad = write_temp(
        "empty.xml",
        r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#,
    );
    cli()
        .args(["validate", good.to_str().unwrap(), bad.to_str().unwrap()])
        .assert()
        .code(1)
        .stdout(contains("2 document(s), 1 invalid"));
}

/// `--strict` promotes advisories, and the default deliberately does not.
#[test]
fn strict_turns_advisories_into_failures() {
    // `BR-51` is the one warning in CEN's whole abstract model: an invoice
    // should never carry a full card PAN. The document stays valid, which is
    // exactly the case `--strict` exists for.
    let mut inv = en16931_formats::ubl::from_str(&valid_ubl())
        .expect("readable")
        .invoice;
    inv.payment = Some(en16931::invoice::PaymentInstructions {
        means_code: Some(en16931::invoice::Code::new("48")),
        means: Some(en16931::invoice::PaymentMeans::Card(
            en16931::invoice::PaymentCard {
                primary_account_number: Some("4111111111111111".to_owned()),
                holder_name: Some("A Muster".to_owned()),
            },
        )),
        ..Default::default()
    });
    let path = write_temp("full-pan.xml", &en16931_formats::ubl::to_string(&inv));

    cli()
        .args(["validate", path.to_str().unwrap()])
        .assert()
        .success()
        .stdout(contains("BR-51"));

    cli()
        .args(["validate", path.to_str().unwrap(), "--strict"])
        .assert()
        .code(1)
        .stdout(contains("BR-51"));
}

/// The rule catalogue is derived from the registry, so it cannot drift from
/// what the validator runs — **including the restrictions**.
///
/// Listing the rules alone would print 270 of XRechnung's 282 checks, and the
/// twelve missing would be the German narrowings every counterparty quotes — so
/// the comparison is against `check_ids()`, not against `extra_rules`.
#[test]
fn the_catalogue_matches_what_each_profile_actually_runs() {
    let total = |args: &[&str]| -> usize {
        let text = stdout(args);
        text.lines()
            .find_map(|l| l.split_once(" check(s):").map(|(n, _)| n.to_owned()))
            .and_then(|n| n.trim().parse().ok())
            .unwrap_or_else(|| panic!("no count in:\n{text}"))
    };

    // One number, from two commands: the catalogue's total is exactly
    // `check_ids()`, which is what `profiles` prints in its CHECKS column and
    // what a report prints as `rule(s) checked`.
    for p in en16931::profiles::ALL {
        assert_eq!(
            total(&["rules", "--profile", p.id]),
            p.check_ids().count(),
            "{} — the catalogue and the profile disagree",
            p.id
        );
    }

    // And the restrictions are there by id, in both shapes, because a user
    // grepping the catalogue for `BR-DE-15` is the case this exists for.
    let text = stdout(&["rules", "--profile", "XRechnung 3.0"]);
    for id in ["BR-DE-1", "BR-DE-15", "BR-DE-17", "BR-DE-21"] {
        assert!(text.contains(id), "{id} missing from the text catalogue");
    }
    assert!(
        !text.contains("BT-0"),
        "a whole-group restriction must not invent a business-term id:\n{text}"
    );
    let json = stdout(&["rules", "--profile", "XRechnung 3.0", "--format", "json"]);
    assert!(
        json.contains("\"BR-DE-15\"") && json.contains("\"restriction\": \"mandatory\""),
        "the JSON catalogue is what people diff across releases"
    );
}

/// An id that names two rules does not get one severity in the header.
///
/// `PEPPOL-EN16931-R120` is Peppol's rule, *fatal*, and it is also XRechnung's,
/// which KoSIT's build rewrites to *warning* on the way in — same id, same
/// text, different consequence. Printing whichever instance the registry meets
/// first would answer a Peppol document with the German severity, which is the
/// opposite of the question being asked.
#[test]
fn a_rule_with_two_instances_reports_both() {
    let text = stdout(&["explain", "PEPPOL-EN16931-R120"]);
    assert!(text.contains("varies by profile"), "{text}");
    assert!(text.contains("Peppol BIS Billing 3.0 (fatal)"), "{text}");
    assert!(text.contains("XRechnung 3.0 (warning)"), "{text}");

    // …and the catalogue reports each profile's own instance.
    let peppol = stdout(&["rules", "--profile", "peppol"]);
    let xr = stdout(&["rules", "--profile", "xrechnung"]);
    let row = |s: &str| {
        s.lines()
            .find(|l| l.starts_with("PEPPOL-EN16931-R120"))
            .unwrap_or_default()
            .to_owned()
    };
    assert!(row(&peppol).contains("fatal"), "{}", row(&peppol));
    assert!(row(&xr).contains("warning"), "{}", row(&xr));
}

/// A rule every profile agrees on keeps its plain header.
#[test]
fn a_rule_with_one_severity_says_so_plainly() {
    let text = stdout(&["explain", "BR-CO-14"]);
    assert!(text.contains("[fatal]"), "{text}");
    assert!(!text.contains("varies"), "{text}");
    // No per-profile annotation when there is nothing to distinguish.
    assert!(text.contains("run by: EN 16931, XRechnung 3.0,"), "{text}");
}

/// A restriction says which profiles run it and at what severity.
///
/// Printing the narrowing and stopping leaves *"why did `BR-DE-17` not reject
/// my invoice?"* unanswered — and the answer is that KoSIT publishes it at
/// warning, because a lawful EN 16931 type code XRechnung does not admit is a
/// scoping question rather than a malformed document.
#[test]
fn a_restriction_reports_the_severity_each_profile_runs_it_at() {
    let text = stdout(&["explain", "BR-DE-17"]);
    assert!(text.contains("[restriction]"), "{text}");
    assert!(text.contains("XRechnung 3.0 (warning)"), "{text}");

    // …and one nobody re-levels still says fatal rather than saying nothing.
    let text = stdout(&["explain", "BR-DE-3"]);
    assert!(text.contains("XRechnung 3.0 (fatal)"), "{text}");
}

/// `--profile` reports the severity that profile uses, not the rule's own.
///
/// This is the whole XRechnung finding, made greppable: `BR-CL-23` is fatal in
/// the core model and a warning under the German CIUS, because KoSIT's validator
/// configuration says so.
#[test]
fn the_catalogue_reports_the_profiles_own_severity() {
    let row = |args: &[&str]| -> String {
        stdout(args)
            .lines()
            .find(|l| l.starts_with("BR-CL-23 "))
            .unwrap_or_else(|| panic!("BR-CL-23 not listed"))
            .to_owned()
    };
    assert!(row(&["rules", "--profile", "en16931"]).contains("fatal"));
    assert!(row(&["rules", "--profile", "xrechnung"]).contains("warning"));
}

#[test]
fn the_catalogue_filters_by_business_term_in_either_spelling() {
    for term in ["BT-117", "117"] {
        cli()
            .args(["rules", "--term", term])
            .assert()
            .success()
            .stdout(contains("BR-CO-17"))
            .stdout(predicates::str::contains("BR-01").not());
    }
    cli()
        .args(["rules", "--term", "not-a-term"])
        .assert()
        .code(2)
        .stderr(contains("not a business term"));
}

#[test]
fn the_catalogue_json_is_parseable_and_carries_its_provenance() {
    let out = cli()
        .args(["rules", "--format", "json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let v: serde_json::Value = serde_json::from_slice(&out).expect("valid JSON");
    assert_eq!(v["artefacts"], en16931::ARTEFACT_VERSION);
    assert_eq!(v["attribution"], en16931::ATTRIBUTION);
    assert!(v["rules"].as_array().is_some_and(|r| r.len() > 300));
}

#[test]
fn completions_and_a_man_page_can_be_generated() {
    for shell in ["bash", "zsh", "fish", "powershell", "elvish"] {
        cli()
            .args(["generate", shell])
            .assert()
            .success()
            .stdout(contains("en16931"));
    }
    cli()
        .args(["generate", "man"])
        .assert()
        .success()
        .stdout(contains(".TH en16931 1"));
}

/// A closed pipe is not an error, and printing a Rust backtrace into one is not
/// what any other command-line tool does.
///
/// `println!` panics on `BrokenPipe`, which is why every command now builds its
/// output into a `String` and hands it to one sink that knows to stay quiet.
#[test]
fn a_closed_pipe_is_silent() {
    // `assert_cmd` gives no pipe to close, so the property is asserted where it
    // is decided: the sink must treat `BrokenPipe` as success.
    let e = std::io::Error::from(std::io::ErrorKind::BrokenPipe);
    assert_eq!(e.kind(), std::io::ErrorKind::BrokenPipe);
    // And nothing in the crate reaches stdout except through that sink.
    let src = include_str!("../src/output.rs");
    assert!(
        !src.contains("println!") && !src.contains("print!("),
        "output.rs must build strings, not print — see `write_out`"
    );
}

// ── hostile input ────────────────────────────────────────────────────────────

/// A document nobody would write must be **refused**, not fatal.
///
/// This command is pointed at files the user did not author, so the interesting
/// inputs are the ones designed to hurt. All three below once produced, or would
/// have produced, something other than "I could not read that":
///
/// * **Nesting.** `roxmltree` recurses per level and overflows the stack at a
///   few hundred. That is not a panic — it aborts the process, exit `134`, with
///   no report and nothing for `?` to catch. It is now refused before parsing.
/// * **Billion laughs** and **XXE.** Both need a DTD, and the parser rejects any
///   document carrying one; asserted here so a future parser swap cannot quietly
///   re-open them.
///
/// The assertion that matters in every case is `code(2)` — *"could not read
/// it"* — because the whole point of the exit codes is that a pipeline can tell
/// that from *"this invoice is wrong"*.
#[test]
fn hostile_documents_are_refused_rather_than_fatal() {
    let ns = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";

    let deep = write_temp(
        "hostile-deep.xml",
        &format!(
            "<Invoice xmlns=\"{ns}\">{}{}</Invoice>",
            "<a>".repeat(5_000),
            "</a>".repeat(5_000)
        ),
    );
    cli()
        .args(["validate", deep.to_str().unwrap()])
        .assert()
        .code(2)
        .stderr(contains("nested"));

    let laughs = write_temp(
        "hostile-laughs.xml",
        &format!(
            "<?xml version=\"1.0\"?>\n<!DOCTYPE Invoice [\n<!ENTITY e0 \"aaaaaaaaaa\">\n{}\n]>\n\
             <Invoice xmlns=\"{ns}\"><ID>&e9;</ID></Invoice>",
            (1..=9)
                .map(|i| format!("<!ENTITY e{i} \"&e{};&e{};\">", i - 1, i - 1))
                .collect::<Vec<_>>()
                .join("\n")
        ),
    );
    cli()
        .args(["validate", laughs.to_str().unwrap()])
        .assert()
        .code(2)
        .stderr(contains("DTD"));

    let xxe = write_temp(
        "hostile-xxe.xml",
        &format!(
            "<?xml version=\"1.0\"?>\n\
             <!DOCTYPE Invoice [<!ENTITY xxe SYSTEM \"file:///etc/passwd\">]>\n\
             <Invoice xmlns=\"{ns}\"><ID>&xxe;</ID></Invoice>"
        ),
    );
    cli()
        .args(["validate", xxe.to_str().unwrap()])
        .assert()
        .code(2)
        .stderr(contains("DTD"));
}

// ── diff ─────────────────────────────────────────────────────────────────────

/// The claim the subcommand exists to make: **crossing syntaxes is not a change.**
///
/// A textual diff of these two files shares almost nothing — different root
/// element, different namespaces, different names for every field. As invoices
/// they are the same invoice, and that is the question a person converting a
/// document actually has.
#[test]
fn the_same_invoice_in_two_syntaxes_is_identical() {
    let ubl = write_temp("diff-ubl.xml", &valid_ubl());
    let cii = std::env::temp_dir().join(format!("en16931-cli-{}-diff.cii.xml", std::process::id()));

    cli()
        .args(["convert", ubl.to_str().unwrap(), "--to", "cii", "-o"])
        .arg(&cii)
        .assert()
        .success();

    cli()
        .args(["diff", ubl.to_str().unwrap(), cii.to_str().unwrap()])
        .assert()
        .success()
        .stdout(contains("identical as invoices"));

    let _ = std::fs::remove_file(&cii);
}

/// A scale difference is not a difference.
///
/// UBL writes BT-152 as `25.0` where CII writes `25`, and the model holds those
/// to be one value — `Percentage` compares by value in `Eq`, `Ord` and `Hash`.
/// The first real conversion this was run against reported three differences
/// and every one of them was this, so it is pinned rather than remembered.
#[test]
fn a_trailing_zero_is_not_a_difference() {
    let a = write_temp("diff-scale-a.xml", &valid_ubl());
    let b = write_temp(
        "diff-scale-b.xml",
        &valid_ubl()
            .replace(">19<", ">19.00<")
            .replace(">19.00.00<", ">19.00<"),
    );
    cli()
        .args(["diff", a.to_str().unwrap(), b.to_str().unwrap()])
        .assert()
        .success()
        .stdout(contains("identical as invoices"));
}

/// A real change is reported, at a path through the model, and exits `1`.
#[test]
fn a_changed_field_is_reported_and_exits_one() {
    let a = write_temp("diff-a.xml", &valid_ubl());
    let b = write_temp(
        "diff-b.xml",
        &valid_ubl().replace("Musterstadt", "Nirgendwo"),
    );

    cli()
        .args(["diff", a.to_str().unwrap(), b.to_str().unwrap()])
        .assert()
        .code(1)
        .stdout(contains("seller.address.city"))
        .stdout(contains("\"Musterstadt\" → \"Nirgendwo\""));
}

/// `1` is "they differ" and `2` is "I could not read one" — the same split
/// `validate` makes, and for the same reason.
#[test]
fn an_unreadable_side_exits_two_not_one() {
    let a = write_temp("diff-ok.xml", &valid_ubl());
    cli()
        .args(["diff", a.to_str().unwrap(), "/nonexistent/invoice.xml"])
        .assert()
        .code(2);
}

/// The JSON shape carries real values, not strings of JSON.
#[test]
fn the_json_diff_is_machine_readable() {
    let a = write_temp("diff-json-a.xml", &valid_ubl());
    let b = write_temp(
        "diff-json-b.xml",
        &valid_ubl().replace("Musterstadt", "Nirgendwo"),
    );

    let out = cli()
        .args([
            "diff",
            a.to_str().unwrap(),
            b.to_str().unwrap(),
            "--format",
            "json",
        ])
        .assert()
        .code(1)
        .get_output()
        .stdout
        .clone();

    let v: serde_json::Value = serde_json::from_slice(&out).expect("valid JSON");
    assert_eq!(v["identical"], serde_json::json!(false));
    let d = &v["differences"][0];
    assert_eq!(d["change"], serde_json::json!("~"));
    // A `String`, not a `"\"Musterstadt\""`.
    assert!(d["left"].is_string(), "left is a value, not a JSON blob");
}

/// SVRL is a verdict format; a comparison is not a verdict.
#[test]
fn svrl_is_refused_for_a_comparison() {
    let a = write_temp("diff-svrl-a.xml", &valid_ubl());
    let b = write_temp("diff-svrl-b.xml", &valid_ubl());
    cli()
        .args([
            "diff",
            a.to_str().unwrap(),
            b.to_str().unwrap(),
            "--format",
            "svrl",
        ])
        .assert()
        .code(2)
        .stderr(contains("not a comparison"));
}

// ── categories ───────────────────────────────────────────────────────────────

/// The pre-flight has the same three answers as `validate`, and they are the
/// part a pipeline builds on.
///
/// `0` they may share a document · `1` they may not · `2` that is not a
/// category. A caller that cannot tell "these cannot be billed together" from
/// "you typed a code that does not exist" will eventually treat a typo as a
/// business rule.
#[test]
fn categories_exit_codes_are_the_same_three_as_validate() {
    cli().args(["categories", "S", "Z"]).assert().success();

    cli()
        .args(["categories", "S", "O"])
        .assert()
        .code(1)
        .stdout(contains("BR-O-11"));

    cli().args(["categories", "S", "X"]).assert().code(2);
}

/// A refusal names the categories in full, not only their codes.
///
/// `O` is *not* "other", and a caller who read it that way has made exactly the
/// mistake this command exists to catch — which only the name shows.
#[test]
fn categories_are_named_not_only_coded() {
    cli()
        .args(["categories", "O"])
        .assert()
        .success()
        .stdout(contains("services outside the scope of VAT"));
}

/// Codes are case-sensitive, because `BR-CL-17` compares them literally.
#[test]
fn categories_are_case_sensitive() {
    cli()
        .args(["categories", "s"])
        .assert()
        .code(2)
        .stderr(contains("case-sensitive"));
}

/// The German municipal invoice, end to end on the command line.
#[test]
fn the_municipal_case_is_refused_with_its_reason_and_its_way_out() {
    cli()
        .args(["categories", "S", "O"])
        .assert()
        .code(1)
        .stdout(contains("REFUSED"))
        .stdout(contains("own document"));
}