cim-kit 0.6.0

IEC CIM/CGMES for power systems: CIM/XML I/O that reproduces the file set, profile-aware validation, typed RDF export
Documentation
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
//! The command line, run as a command line.
//!
//! `cim` is a shell over the public API, so most of what it does is covered by the library's
//! own tests. What is not is the part that *is* the tool rather than the library: which
//! stream each thing it writes goes to, and what it leaves on disk.
//!
//! `cim diff a b > change.xml` means the document is stdout, so anything else the command
//! has to say must go elsewhere or the file stops being a document.

#![cfg(all(feature = "cli", feature = "cgmes3"))]

mod common;

use std::path::Path;
use std::process::Command;

const NS: &str = "http://iec.ch/TC57/CIM100#";
const LOCATION: &str = "22222222-2222-4222-8222-222222222222";

fn cim() -> Command {
    Command::new(env!("CARGO_BIN_EXE_cim"))
}

/// A scratch directory named for the test using it, removed and recreated on entry.
fn scratch(name: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!("cim-cli-{}-{name}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

/// A one-object Geographical Location file whose address is a compound.
///
/// A compound is the one difference IEC 61970-552's statement syntax cannot carry, so
/// changing one is the shortest way to make `cim diff` have something to report. The
/// published conformity corpus contains no compound at all, which is why this is written
/// here rather than found there.
fn location_file(dir: &Path, postal_code: &str) {
    location_file_as(dir, postal_code, "11111111-1111-4111-8111-111111111111");
}

/// [`location_file`], with a header identifier of the caller's choosing.
fn location_file_as(dir: &Path, postal_code: &str, model: &str) {
    let text = format!(
        r##"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cim="{NS}"
         xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#">
  <md:FullModel rdf:about="urn:uuid:{model}">
    <md:Model.created>2024-01-01T00:00:00Z</md:Model.created>
    <md:Model.scenarioTime>2024-01-01T00:00:00Z</md:Model.scenarioTime>
    <md:Model.profile>http://iec.ch/TC57/ns/CIM/GeographicalLocation-EU/3.0</md:Model.profile>
  </md:FullModel>
  <cim:Location rdf:ID="_{LOCATION}">
    <cim:IdentifiedObject.mRID>{LOCATION}</cim:IdentifiedObject.mRID>
    <cim:Location.mainAddress rdf:parseType="Resource">
      <cim:StreetAddress.postalCode>{postal_code}</cim:StreetAddress.postalCode>
    </cim:Location.mainAddress>
  </cim:Location>
</rdf:RDF>
"##
    );
    std::fs::create_dir_all(dir).unwrap();
    std::fs::write(dir.join("GL.xml"), text).unwrap();
}

/// With no `--out`, the change set *is* standard output — so nothing else may go there.
#[test]
fn a_change_set_written_to_stdout_is_a_document_and_nothing_else() {
    let root = scratch("diff-stdout");
    location_file(&root.join("base"), "1000");
    location_file(&root.join("target"), "2000");

    let out = cim()
        .arg("diff")
        .arg(root.join("base"))
        .arg(root.join("target"))
        .output()
        .unwrap();
    assert!(out.status.success(), "cim diff failed: {out:?}");

    let document = String::from_utf8(out.stdout).unwrap();
    let stderr = String::from_utf8(out.stderr).unwrap();

    // The report exists — otherwise this test proves nothing — and it is on stderr.
    assert!(
        stderr.contains("CIM0015") && stderr.contains("compound"),
        "the compound change was not reported at all:\nstderr: {stderr}"
    );
    assert!(
        !document.contains("CIM0015"),
        "the diagnostics report was written into the document:\n{document}"
    );

    // And the document is a document, judged by the checker the corpus sweep uses rather
    // than by this crate's own tolerant reader.
    common::assert_well_formed("cim diff > change.xml", &document);
    assert!(document.trim_end().ends_with("</rdf:RDF>"), "{document}");

    let _ = std::fs::remove_dir_all(&root);
}

/// With `--out`, the document is a file and stdout is free to carry the report.
#[test]
fn a_change_set_written_to_a_file_leaves_stdout_for_the_report() {
    let root = scratch("diff-file");
    location_file(&root.join("base"), "1000");
    location_file(&root.join("target"), "2000");
    let path = root.join("change_DIFF.xml");

    let out = cim()
        .arg("diff")
        .arg(root.join("base"))
        .arg(root.join("target"))
        .arg("--out")
        .arg(&path)
        .output()
        .unwrap();
    assert!(out.status.success(), "cim diff --out failed: {out:?}");

    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("CIM0015"), "{stdout}");
    common::assert_well_formed("change_DIFF.xml", &std::fs::read_to_string(&path).unwrap());

    let _ = std::fs::remove_dir_all(&root);
}

/// `cim rdf` writes a graph for a profile the model describes, and none for one it does not.
///
/// A graph of nothing but the loaded files' headers is not an export of a profile: it looks
/// like one, it validates like one, and it says nothing about the model. Writing no file is
/// what lets a caller — `cargo xtask shacl` among them — tell "conformant" from "absent".
#[test]
fn rdf_writes_a_graph_only_for_a_profile_the_model_describes() {
    let root = scratch("rdf-empty");
    location_file(&root.join("model"), "1000");
    let graphs = root.join("graphs");

    let out = cim()
        .arg("rdf")
        .arg(root.join("model"))
        .arg("--out")
        .arg(&graphs)
        .arg("--ntriples")
        .output()
        .unwrap();
    assert!(out.status.success(), "cim rdf failed: {out:?}");

    assert!(graphs.join("GL.nt").is_file(), "the GL graph is missing");
    for absent in ["EQ.nt", "SSH.nt", "SV.nt", "TP.nt", "DY.nt", "FH.nt"] {
        assert!(
            !graphs.join(absent).is_file(),
            "{absent} was written for a profile this model says nothing about"
        );
    }
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(stderr.contains("no data for"), "{stderr}");

    // And the graph that was written carries this file's header and no other profile's.
    let gl = std::fs::read_to_string(graphs.join("GL.nt")).unwrap();
    assert!(gl.contains("GeographicalLocation-EU"), "{gl}");
    assert!(common::check_ntriples(&gl).unwrap() > 3, "{gl}");

    let _ = std::fs::remove_dir_all(&root);
}

/// The vintage comes from the document, not from which feature happens to be first.
///
/// Only reachable through the binary: the library takes a `&'static Schema` and so cannot
/// choose one. Reading a CGMES 2.4.15 model against the CGMES 3.0 tables resolves nothing,
/// and the result — an empty model, exit status 0 — reads as a successful load.
#[test]
#[cfg(feature = "cgmes2")]
fn the_vintage_is_detected_from_the_input() {
    let root = scratch("vintage");
    let model = root.join("model");
    std::fs::create_dir_all(&model).unwrap();
    std::fs::write(
        model.join("EQ.xml"),
        concat!(
            r#"<?xml version="1.0" encoding="UTF-8"?>"#,
            "\n",
            r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#""#,
            r#" xmlns:cim="http://iec.ch/TC57/2013/CIM-schema-cim16#""#,
            r#" xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#">"#,
            "\n",
            r#"  <md:FullModel rdf:about="urn:uuid:11111111-1111-4111-8111-111111111111">"#,
            r#"<md:Model.profile>http://entsoe.eu/CIM/EquipmentCore/3/1</md:Model.profile>"#,
            r#"</md:FullModel>"#,
            "\n",
            r#"  <cim:Substation rdf:ID="_22222222-2222-4222-8222-222222222222">"#,
            r#"<cim:IdentifiedObject.name>S1</cim:IdentifiedObject.name></cim:Substation>"#,
            "\n</rdf:RDF>\n"
        ),
    )
    .unwrap();

    // No `--vintage`: the document is read as what it says it is.
    let out = cim().arg("info").arg(&model).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
    assert!(stdout.contains("objects              1"), "{stdout}");
    assert!(!stdout.contains("CIM0021"), "{stdout}");

    // Forced to the wrong one, it says so rather than reporting an empty model as fine.
    let out = cim()
        .arg("info")
        .arg(&model)
        .args(["--vintage", "cgmes3"])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
    assert!(
        stdout.contains("CIM0021"),
        "no mismatch reported:\n{stdout}"
    );
    assert!(stdout.contains("objects              0"), "{stdout}");
    assert_eq!(
        out.status.code(),
        Some(1),
        "a model that read as nothing exited 0"
    );

    let _ = std::fs::remove_dir_all(&root);
}

/// A downloaded binary says which release it is.
#[test]
fn the_binary_says_which_release_it_is() {
    // The released binaries are built from the tag and downloaded on their own, detached
    // from the repository they came from, so this is the only thing that identifies one.
    for flag in ["--version", "-V"] {
        let out = cim().arg(flag).output().unwrap();
        assert_eq!(out.status.code(), Some(0), "{flag}: {out:?}");
        assert_eq!(
            String::from_utf8_lossy(&out.stdout).trim(),
            format!("cim {}", env!("CARGO_PKG_VERSION")),
            "{flag}"
        );
    }
}

/// An unknown flag is refused rather than taken for an input path.
#[test]
fn a_mistyped_flag_is_an_error_rather_than_a_silently_ignored_one() {
    let out = cim().arg("info").arg("-Q").arg(".").output().unwrap();
    assert_eq!(out.status.code(), Some(2), "{out:?}");
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("unknown option"),
        "{out:?}"
    );
}

/// Asked to export a model, the tool writes one — or says why not. It never does neither.
///
/// A document with no `md:FullModel` declares no profile, so there is no file set for
/// `save_as_loaded` to reproduce: every object was skipped, the output directory was left
/// empty, and the exit status was 0. A caller who checks the status — which is the one
/// thing a script checks — was told the export succeeded.
#[test]
fn exporting_a_model_whose_files_declare_no_profile_writes_it_anyway() {
    let dir = scratch("headerless");
    let input = dir.join("in");
    std::fs::create_dir_all(&input).unwrap();
    std::fs::write(
        input.join("model.xml"),
        format!(
            r##"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cim="{NS}">
  <cim:ACLineSegment rdf:ID="_{LOCATION}">
    <cim:IdentifiedObject.name>Line</cim:IdentifiedObject.name>
    <cim:ACLineSegment.r>2.2</cim:ACLineSegment.r>
  </cim:ACLineSegment>
</rdf:RDF>
"##
        ),
    )
    .unwrap();

    let out = dir.join("out");
    let result = cim()
        .args(["export"])
        .arg(&input)
        .arg("--out")
        .arg(&out)
        .output()
        .unwrap();
    assert!(
        result.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&result.stderr)
    );
    let written: Vec<_> = std::fs::read_dir(&out).unwrap().flatten().collect();
    assert_eq!(written.len(), 1, "expected one file, got {written:?}");
    let text = std::fs::read_to_string(written[0].path()).unwrap();
    assert!(text.contains("ACLineSegment"), "{text}");
    // The shape of the output is not the shape of the input, so it says so.
    assert!(
        String::from_utf8_lossy(&result.stderr).contains("no input file declares a profile"),
        "the fallback was silent: {:?}",
        String::from_utf8_lossy(&result.stderr)
    );
    common::assert_well_formed("fallback export", &text);

    // And the flag the note names does what the note says: the file comes back as itself,
    // under its own name, with a header declaring the profile the caller supplied.
    let named = dir.join("named");
    let result = cim()
        .args(["export"])
        .arg(&input)
        .args(["--assume-profile", "EQ"])
        .arg("--out")
        .arg(&named)
        .output()
        .unwrap();
    assert!(result.status.success());
    let text = std::fs::read_to_string(named.join("model.xml")).expect("model.xml");
    assert!(text.contains("<md:FullModel"), "{text}");
    assert!(
        text.contains("CoreEquipment-EU"),
        "the header does not declare the assumed profile:\n{text}"
    );
}

/// `diff` and `apply` are halves of one operation, so the tool is tested as one.
///
/// The library could read and apply a `dm:DifferenceModel` from the start and the tool
/// could only produce one, which made the shell a one-way door: the receiving half of IEC
/// 61970-552's incremental exchange — the half a consumer actually runs — had no command.
#[test]
fn a_change_set_computed_by_the_tool_can_be_applied_by_the_tool() {
    /// A one-object Equipment file — a scalar change, which is what a statement *can*
    /// carry. (`location_file`'s compound is deliberately the one that cannot.)
    fn named(dir: &Path, name: &str) {
        let text = format!(
            r##"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cim="{NS}"
         xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#">
  <md:FullModel rdf:about="urn:uuid:11111111-1111-4111-8111-111111111111">
    <md:Model.profile>http://iec.ch/TC57/ns/CIM/CoreEquipment-EU/3.0</md:Model.profile>
  </md:FullModel>
  <cim:Substation rdf:ID="_{LOCATION}">
    <cim:IdentifiedObject.mRID>{LOCATION}</cim:IdentifiedObject.mRID>
    <cim:IdentifiedObject.name>{name}</cim:IdentifiedObject.name>
  </cim:Substation>
</rdf:RDF>
"##
        );
        std::fs::create_dir_all(dir).unwrap();
        std::fs::write(dir.join("EQ.xml"), text).unwrap();
    }

    let dir = scratch("apply");
    let base = dir.join("base");
    let target = dir.join("target");
    named(&base, "before");
    named(&target, "after");

    let change = dir.join("change_DIFF.xml");
    let made = cim()
        .args(["diff"])
        .arg(&base)
        .arg(&target)
        .arg("--out")
        .arg(&change)
        .output()
        .unwrap();
    assert!(
        made.status.success(),
        "{}",
        String::from_utf8_lossy(&made.stderr)
    );

    let out = dir.join("out");
    let applied = cim()
        .args(["apply"])
        .arg(&base)
        .args(["--change"])
        .arg(&change)
        .arg("--out")
        .arg(&out)
        .output()
        .unwrap();
    assert!(
        applied.status.success(),
        "{}",
        String::from_utf8_lossy(&applied.stderr)
    );

    // The result is the target: same postal code, and a document a parser that is not ours
    // accepts.
    let written = std::fs::read_to_string(out.join("EQ.xml")).expect("EQ.xml");
    common::assert_well_formed("applied", &written);
    assert!(
        written.contains("<cim:IdentifiedObject.name>after<"),
        "{written}"
    );
    assert!(!written.contains("before"), "{written}");

    // And a change set is required rather than assumed.
    let missing = cim()
        .args(["apply"])
        .arg(&base)
        .arg("--out")
        .arg(&out)
        .output()
        .unwrap();
    assert_eq!(missing.status.code(), Some(2));
    assert!(
        String::from_utf8_lossy(&missing.stderr).contains("--change"),
        "{}",
        String::from_utf8_lossy(&missing.stderr)
    );
}

/// A safe default is only safe if hitting it tells the operator what to do next: the
/// message names the flag and a value to try, and the next run with it succeeds.
#[test]
fn an_input_over_the_budget_names_the_flag_that_raises_it() {
    let root = scratch("max-input");
    location_file(&root.join("model"), "1000");

    let out = cim()
        .args(["info"])
        .arg(root.join("model"))
        .args(["--max-input", "256B"])
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(2), "{out:?}");
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(stderr.contains("input budget"), "{stderr}");
    assert!(
        stderr.contains("--max-input 1KiB"),
        "suggests a value: {stderr}"
    );
    assert!(stderr.contains("GL.xml"), "names the file: {stderr}");
    assert!(
        !stderr.contains("ReadOptions"),
        "the library's remedy is not the operator's: {stderr}"
    );

    let out = cim()
        .args(["info"])
        .arg(root.join("model"))
        .args(["--max-input", "1KiB"])
        .output()
        .unwrap();
    // 1 is "the model has findings": the read itself succeeded.
    assert_ne!(
        out.status.code(),
        Some(2),
        "the suggested value works: {out:?}"
    );
}

/// An export that ran out of budget is a partial model, so it must not be written as if
/// it were the whole one.
#[test]
fn an_export_over_the_budget_writes_nothing() {
    let root = scratch("max-input-export");
    location_file(&root.join("model"), "1000");
    let dest = root.join("out");

    let out = cim()
        .args(["export"])
        .arg(root.join("model"))
        .arg("--out")
        .arg(&dest)
        .args(["--max-input", "100B"])
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(2), "{out:?}");
    let written = std::fs::read_dir(&dest).map_or(0, Iterator::count);
    assert_eq!(written, 0, "no file is written after the budget is hit");
}

#[test]
fn max_input_takes_sizes_the_way_people_write_them() {
    let root = scratch("max-input-forms");
    location_file(&root.join("model"), "1000");
    for size in ["8GiB", "512MB", "4096", "4kib", "unlimited", "0"] {
        let out = cim()
            .args(["info"])
            .arg(root.join("model"))
            .args(["--max-input", size])
            .output()
            .unwrap();
        assert_ne!(out.status.code(), Some(2), "{size}: {out:?}");
    }
    for size in ["banana", "1.5GiB", "12XB", "-1", ""] {
        let out = cim()
            .args(["info"])
            .arg(root.join("model"))
            .args(["--max-input", size])
            .output()
            .unwrap();
        assert_eq!(out.status.code(), Some(2), "{size} is refused");
        let stderr = String::from_utf8(out.stderr).unwrap();
        assert!(
            stderr.contains("GiB") && stderr.contains("unlimited"),
            "{stderr}"
        );
    }
}

/// A change set names the model it was computed against, so applying it to another one is
/// refused — and the tool says so, exits 1, and writes nothing rather than handing back the
/// unchanged input under the name of a result.
#[test]
fn a_change_set_applied_to_the_wrong_model_is_refused() {
    let root = scratch("apply-wrong-base");
    location_file_as(
        &root.join("base"),
        "1000",
        "aaaaaaaa-1111-4111-8111-111111111111",
    );
    location_file_as(
        &root.join("target"),
        "2000",
        "bbbbbbbb-2222-4222-8222-222222222222",
    );
    let change = root.join("change.xml");
    let out = cim()
        .arg("diff")
        .arg(root.join("base"))
        .arg(root.join("target"))
        .arg("--out")
        .arg(&change)
        .output()
        .unwrap();
    assert!(out.status.success(), "{out:?}");

    let dest = root.join("result");
    let out = cim()
        .arg("apply")
        .arg(root.join("target"))
        .arg("--change")
        .arg(&change)
        .arg("--out")
        .arg(&dest)
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(1), "{out:?}");
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(
        stderr.contains("CIM0014") && stderr.contains("aaaaaaaa"),
        "{stderr}"
    );
    assert_eq!(
        std::fs::read_dir(&dest).map_or(0, Iterator::count),
        0,
        "nothing written"
    );

    let out = cim()
        .arg("apply")
        .arg(root.join("base"))
        .arg("--change")
        .arg(&change)
        .arg("--out")
        .arg(&dest)
        .output()
        .unwrap();
    assert_ne!(
        out.status.code(),
        Some(2),
        "onto its own base it applies: {out:?}"
    );
    assert!(std::fs::read_dir(&dest).map_or(0, Iterator::count) > 0);
}

#[test]
fn a_truncated_file_is_named_with_where_it_stops() {
    let dir = scratch("truncated");
    location_file(&dir, "1000");
    let whole = std::fs::read_to_string(dir.join("GL.xml")).unwrap();
    let cut = whole.find("</cim:Location>").unwrap();
    std::fs::write(dir.join("GL_cut.xml"), &whole[..cut]).unwrap();
    std::fs::remove_file(dir.join("GL.xml")).unwrap();
    location_file_as(&dir, "1000", "33333333-3333-4333-8333-333333333333");

    // Lenient: the file is reported, nothing of it is used, and the run says so.
    let out = cim().arg("validate").arg(&dir).output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(out.status.code(), Some(1), "{stdout}");
    assert!(
        stdout.contains("error[CIM0022] GL_cut.xml@") && stdout.contains("truncated"),
        "{stdout}"
    );

    // Strict: the load itself fails, naming the file and the element left open.
    let out = cim()
        .args(["validate", "--strict"])
        .arg(&dir)
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert_eq!(out.status.code(), Some(2), "{stderr}");
    assert!(
        stderr.contains("truncated document GL_cut.xml") && stderr.contains("<cim:Location>"),
        "{stderr}"
    );
}

#[test]
fn single_description_reports_an_object_described_twice() {
    let dir = scratch("single-description");
    let file = dir.join("EQ.xml");
    std::fs::write(
        &file,
        format!(
            r##"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cim="{NS}">
  <cim:Terminal rdf:ID="_{LOCATION}"/>
  <cim:Terminal rdf:about="#_{LOCATION}"/>
</rdf:RDF>"##
        ),
    )
    .unwrap();
    let run = |flag: Option<&str>| {
        let out = cim()
            .args(["validate", "--rule", "CIM0005"])
            .args(flag)
            .arg(&file)
            .output()
            .unwrap();
        String::from_utf8_lossy(&out.stdout).into_owned()
    };
    assert!(!run(None).contains("error[CIM0005]"));
    let flagged = run(Some("--single-description"));
    assert!(
        flagged.contains("error[CIM0005] EQ.xml@") && flagged.contains("described again"),
        "{flagged}"
    );
}