oxml-cli 0.0.19

Command-line XML querying, validation and formatting, powered by oxml
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
//! Unit tests for the command functions, kept out of `lib.rs` so the
//! library source stays under the 500-line file ceiling.

use super::parse_namespace_bindings;

fn args(list: &[&str]) -> Vec<String> {
    list.iter().map(|s| (*s).to_owned()).collect()
}

/// A scratch file, removed when the test ends.
struct Temp(std::path::PathBuf);

impl Temp {
    fn new(name: &str, contents: &str) -> Self {
        let path = std::env::temp_dir().join(name);
        std::fs::write(&path, contents).expect("write scratch file");
        Self(path)
    }
    fn path(&self) -> &str {
        self.0.to_str().expect("utf-8 path")
    }
}

impl Drop for Temp {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.0);
    }
}

/// Run a query and return what it printed alongside its code.
///
/// Before the library target existed these assertions could only
/// reach `is_ok()`: the output went straight to the process's
/// stdout, so a query that exited 0 having printed the wrong
/// answer passed.
fn query(
    doc: &str,
    expr: &str,
    text_only: bool,
    count_only: bool,
    ns: &[(String, String)],
) -> Result<(String, String), String> {
    let mut out = Vec::new();
    let code =
        super::cmd_query(doc, expr, text_only, count_only, ns, &mut out)?;
    Ok((String::from_utf8(out).expect("utf-8"), format!("{code:?}")))
}

#[test]
fn cmd_query_reports_matches_and_their_absence() {
    let doc = r"<r><t>one</t><t>two</t></r>";
    let success = format!("{:?}", std::process::ExitCode::SUCCESS);

    let (text, code) = query(doc, "//t", true, false, &[]).expect("valid");
    assert_eq!(text, "one\ntwo\n");
    assert_eq!(code, success);

    let (text, code) = query(doc, "//t", false, true, &[]).expect("valid");
    assert_eq!(text, "2\n");
    assert_eq!(code, success);

    // A non-node-set result prints as itself.
    let (text, code) =
        query(doc, "count(//t)", false, false, &[]).expect("valid");
    assert_eq!(text, "2\n");
    assert_eq!(code, success);

    // Exit 1 when nothing matched, so `if oxml query …` reads as a
    // question about the document -- and nothing is printed, so a
    // caller piping the output sees an empty result, not a blank
    // line.
    let (text, code) =
        query(doc, "//missing", true, false, &[]).expect("valid");
    assert_eq!(text, "");
    assert_eq!(code, format!("{:?}", std::process::ExitCode::from(1)));
}

#[test]
fn cmd_query_binds_namespaces_and_refuses_unbound_ones() {
    let doc = r#"<r xmlns:m="urn:u"><m:t>ns</m:t></r>"#;
    let bound = [(String::from("m"), String::from("urn:u"))];
    let (text, _) = query(doc, "//m:t", true, false, &bound).expect("bound");
    assert_eq!(text, "ns\n");

    let err = query(doc, "//m:t", true, false, &[]).expect_err("unbound");
    assert!(err.contains("--ns"), "{err}");
}

#[test]
fn cmd_validate_reads_a_schema_from_disk() {
    let schema = Temp::new(
        "oxml-cli-test-schema.xsd",
        r#"<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="r"/>
</xs:schema>"#,
    );
    let (mut out, mut err) = (Vec::new(), Vec::new());
    assert!(
        super::cmd_validate("<r/>", schema.path(), &mut out, &mut err).is_ok()
    );
    // A schema that is not there is a usage error, not a document
    // that failed to validate.
    assert!(
        super::cmd_validate("<r/>", "/nonexistent.xsd", &mut out, &mut err)
            .is_err()
    );
}

/// Drive `run` and hand back what each stream received.
fn drive(argv: &[String]) -> Result<(String, String, String), String> {
    let (mut out, mut err) = (Vec::new(), Vec::new());
    let code = super::run(argv, &mut out, &mut err)?;
    Ok((
        String::from_utf8(out).expect("utf-8"),
        String::from_utf8(err).expect("utf-8"),
        format!("{code:?}"),
    ))
}

#[test]
fn run_dispatches_each_command() {
    let doc = Temp::new("oxml-cli-test-doc.xml", "<r><t>x</t></r>");
    for command in [
        vec!["check", doc.path()],
        vec!["stats", doc.path()],
        vec!["query", "//t", doc.path()],
        vec!["query", "-t", "//t", doc.path()],
    ] {
        let owned = args(&command);
        let (out, _, _) = drive(&owned).expect("{command:?}");
        assert!(!out.is_empty(), "{command:?} printed nothing");
    }
}

#[test]
fn run_answers_help_and_version_without_reading_anything() {
    // These must not touch stdin: `oxml --help` in a terminal with
    // no input would otherwise hang.
    for flags in [vec!["--help"], vec!["-h"], vec!["--version"], vec!["-V"]] {
        let owned = args(&flags);
        let (out, _, _) = drive(&owned).expect("{flags:?}");
        assert!(!out.is_empty(), "{flags:?} printed nothing");
    }
}

#[test]
fn run_rejects_a_command_it_does_not_have() {
    let owned = args(&["frobnicate"]);
    let err = drive(&owned).expect_err("unknown");
    assert!(err.contains("unknown command"), "{err}");

    // And a command that needs an argument it was not given.
    let owned = args(&["query"]);
    assert!(drive(&owned).is_err());
    let owned = args(&["validate"]);
    assert!(drive(&owned).is_err());
    let owned: Vec<String> = Vec::new();
    let (usage, _, _) = drive(&owned).expect("no arguments prints usage");
    assert!(usage.contains("USAGE") || usage.contains("oxml"), "{usage}");
}

#[test]
fn truncate_keeps_short_strings_whole() {
    assert_eq!(super::truncate("short", 10), "short");
    assert_eq!(super::truncate("exactly10!", 10), "exactly10!");
}

#[test]
fn truncate_counts_characters_not_bytes() {
    // Cutting at a byte offset would split a multi-byte character
    // and panic. Five accented characters are ten bytes.
    assert_eq!(super::truncate("ééééé", 3), "ééé…");
    assert_eq!(super::truncate("ééééé", 5), "ééééé");
}

#[test]
fn describe_renders_each_node_kind() {
    let doc =
        super::parse_or_report(r#"<r a="1"><!--note--><?pi go?>text</r>"#)
            .expect("well-formed");
    let rendered: Vec<String> = doc
        .descendants()
        .map(|id| super::describe(&doc, id))
        .collect();
    let all = rendered.join("\n");
    assert!(
        all.contains("<r a=\"1\">"),
        "element with attributes: {all}"
    );
    assert!(all.contains("note"), "comment: {all}");
    // A processing instruction falls to the catch-all arm and
    // renders as nothing. Worth pinning: a summary that silently
    // omits a node kind is easy to grow and hard to notice.
    assert!(
        rendered.iter().any(String::is_empty),
        "a processing instruction renders empty: {rendered:?}"
    );
    assert!(all.contains("text"), "text: {all}");
}

#[test]
fn parse_or_report_explains_where_the_document_broke() {
    let err = super::parse_or_report("<a></b>").expect_err("mismatched");
    // A line and column, because a byte offset sends the reader
    // counting.
    assert!(err.contains("1:4"), "{err}");
}

#[test]
fn cmd_check_separates_a_bad_document_from_a_good_one() {
    let (mut out, mut err) = (Vec::new(), Vec::new());
    assert_eq!(
        format!("{:?}", super::cmd_check("<a/>", &mut out, &mut err)),
        format!("{:?}", std::process::ExitCode::SUCCESS)
    );
    assert!(
        String::from_utf8(out)
            .expect("utf-8")
            .contains("well-formed"),
        "a good document says so"
    );

    // Exit 1: the document has a problem. Exit 2 is reserved for
    // the caller having made a mistake.
    let (mut out, mut err) = (Vec::new(), Vec::new());
    assert_eq!(
        format!("{:?}", super::cmd_check("<a>", &mut out, &mut err)),
        format!("{:?}", std::process::ExitCode::from(1))
    );
    // The diagnosis goes to stderr, so `oxml check x.xml > out`
    // still shows the caller what was wrong.
    assert!(out.is_empty(), "a failure printed to stdout");
    assert!(
        String::from_utf8(err)
            .expect("utf-8")
            .contains("not well-formed"),
        "a bad document says why"
    );
}

#[test]
fn cmd_stats_counts_a_document_without_touching_the_filesystem() {
    let mut out = Vec::new();
    assert!(super::cmd_stats("<r><a/><b>x</b><!--c--></r>", &mut out).is_ok());
    let text = String::from_utf8(out).expect("utf-8");
    assert!(text.contains("elements    3"), "{text}");
    assert!(text.contains("comments    1"), "{text}");
    // A malformed document is reported rather than counted.
    let mut out = Vec::new();
    assert!(super::cmd_stats("<r>", &mut out).is_err());
}

#[test]
fn cmd_stats_accounts_for_every_node() {
    // The kind lines must sum to `nodes`. They did not before
    // 0.0.7: namespace nodes and the document root were counted
    // in the total and printed nowhere, so `stats` on any
    // namespaced document looked as though it could not add up.
    let doc = r#"<r xmlns:m="urn:u"><m:a k="v">x</m:a><!--c--></r>"#;
    let mut out = Vec::new();
    let _ = super::cmd_stats(doc, &mut out).expect("well-formed");
    let text = String::from_utf8(out).expect("utf-8");

    let value = |label: &str| -> usize {
        text.lines()
            .find(|l| l.starts_with(label))
            .and_then(|l| l.split_whitespace().last())
            .and_then(|n| n.parse().ok())
            .unwrap_or_else(|| panic!("no `{label}` line in {text}"))
    };
    let total = value("nodes");
    let parts = [
        "elements",
        "attributes",
        "text",
        "comments",
        "namespaces",
        "other",
    ]
    .iter()
    .map(|l| value(l))
    .sum::<usize>();
    assert_eq!(parts, total, "the breakdown does not add up:\n{text}");
    // And the namespaces are really counted: `m`, plus the
    // implicit `xml` binding every document carries.
    assert_eq!(value("namespaces"), 2, "{text}");
}

#[test]
fn an_option_value_is_not_a_positional_argument() {
    // Filtering on a leading `-` alone would have made
    // `urn:example` look like a command, because a URI does not
    // begin with a dash.
    let owned = args(&["query", "-n", "m=urn:example", "//m:x", "f.xml"]);
    let got = super::positional_args(&owned);
    let got: Vec<&str> = got.iter().map(|s| s.as_str()).collect();
    assert_eq!(got, ["query", "//m:x", "f.xml"]);
}

#[test]
fn ordinary_flags_are_still_dropped() {
    let owned = args(&["query", "-t", "//x", "-c", "f.xml"]);
    let got = super::positional_args(&owned);
    let got: Vec<&str> = got.iter().map(|s| s.as_str()).collect();
    assert_eq!(got, ["query", "//x", "f.xml"]);
}

#[test]
fn a_trailing_option_consumes_nothing_that_is_not_there() {
    let owned = args(&["query", "//x", "-n"]);
    let got = super::positional_args(&owned);
    let got: Vec<&str> = got.iter().map(|s| s.as_str()).collect();
    assert_eq!(got, ["query", "//x"]);
}

#[test]
fn the_long_option_form_also_takes_a_value() {
    let owned = args(&["query", "--ns", "m=urn:u", "//m:x"]);
    let got = super::positional_args(&owned);
    let got: Vec<&str> = got.iter().map(|s| s.as_str()).collect();
    assert_eq!(got, ["query", "//m:x"]);
}

#[test]
fn an_unbound_prefix_is_explained_in_terms_of_the_flag() {
    // The library says "bind it with
    // XPath::compile_with_namespaces", which is a Rust function.
    // Someone at a shell needs `--ns`.
    let err = oxml::XPath::compile("//m:item").expect_err("unbound");
    let said = super::explain_xpath_error(&err);
    assert!(said.contains("--ns m=URI"), "{said}");
    assert!(!said.contains("compile_with_namespaces"), "{said}");
}

#[test]
fn other_expression_errors_are_passed_through() {
    // Those messages already say where in the expression the
    // problem is; rewriting them would lose that.
    let err = oxml::XPath::compile("//[").expect_err("malformed");
    let said = super::explain_xpath_error(&err);
    assert!(said.starts_with("bad XPath: "), "{said}");
    assert!(!said.contains("--ns"), "{said}");
}

#[test]
fn a_binding_is_collected() {
    let got =
        parse_namespace_bindings(&args(&["query", "-n", "m=urn:u", "//m:x"]))
            .expect("valid");
    assert_eq!(got, vec![("m".to_owned(), "urn:u".to_owned())]);
}

#[test]
fn the_long_form_works_too() {
    let got =
        parse_namespace_bindings(&args(&["--ns", "m=urn:u"])).expect("valid");
    assert_eq!(got.len(), 1);
}

#[test]
fn bindings_accumulate_and_later_ones_win() {
    // Later wins, so a wrapper script can set defaults a caller
    // overrides on the same command line.
    let got = parse_namespace_bindings(&args(&[
        "-n",
        "a=urn:one",
        "-n",
        "b=urn:two",
        "-n",
        "a=urn:three",
    ]))
    .expect("valid");
    assert_eq!(
        got,
        vec![
            ("b".to_owned(), "urn:two".to_owned()),
            ("a".to_owned(), "urn:three".to_owned()),
        ]
    );
}

#[test]
fn a_uri_may_contain_an_equals_sign() {
    // Split on the *first* `=`; a URI with a query string is
    // ordinary and must not be truncated.
    let got = parse_namespace_bindings(&args(&["-n", "m=urn:u?a=b&c=d"]))
        .expect("valid");
    assert_eq!(got[0].1, "urn:u?a=b&c=d");
}

#[test]
fn an_empty_uri_is_allowed() {
    // Binding a prefix to the empty string is unusual but not a
    // usage error; the library decides what it means.
    let got = parse_namespace_bindings(&args(&["-n", "m="])).expect("valid");
    assert_eq!(got[0].1, "");
}

#[test]
fn a_binding_without_an_equals_sign_is_rejected() {
    let err =
        parse_namespace_bindings(&args(&["-n", "bogus"])).expect_err("no `=`");
    assert!(err.contains("PREFIX=URI"), "{err}");
}

#[test]
fn a_binding_needs_a_prefix() {
    let err = parse_namespace_bindings(&args(&["-n", "=urn:u"]))
        .expect_err("no prefix");
    assert!(err.contains("prefix"), "{err}");
}

#[test]
fn the_xml_prefix_may_not_be_rebound() {
    // Bound by the specification. Rebinding it is not something a
    // document can do either.
    let err = parse_namespace_bindings(&args(&["-n", "xml=urn:u"]))
        .expect_err("reserved");
    assert!(err.contains("xml"), "{err}");
}

#[test]
fn a_trailing_flag_with_no_value_is_rejected() {
    let err = parse_namespace_bindings(&args(&["query", "//x", "-n"]))
        .expect_err("no value");
    assert!(err.contains("PREFIX=URI"), "{err}");
}

#[test]
fn the_next_argument_is_taken_even_if_it_looks_like_a_flag() {
    // `-n -t` is a mistake worth reporting rather than silently
    // treating `-t` as a separate option and consuming the
    // argument after it.
    let err = parse_namespace_bindings(&args(&["-n", "-t", "//x"]))
        .expect_err("flag as value");
    assert!(err.contains("PREFIX=URI"), "{err}");
}

#[test]
fn no_bindings_is_not_an_error() {
    let got =
        parse_namespace_bindings(&args(&["query", "//x"])).expect("valid");
    assert!(got.is_empty());
}