xmlschema 0.0.5

XML Schema (XSD) validation for Rust, with zero unsafe code
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
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 xmlschema. All rights reserved.

//! Restriction facets.
//!
//! A facet that is parsed but never enforced is worse than one that is
//! missing: the schema says the constraint exists and nothing applies
//! it. Each is checked against a value it must accept and one it must
//! reject, and the rejection message is checked for the bound itself,
//! since that is what tells an author what to change.

use xmlschema::{parse_schema, validate};

/// Build a schema whose `v` element restricts `base` with `facets`.
fn restricted(base: &str, facets: &str) -> xmlschema::Schema {
    let xsd = format!(
        r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
             <xs:element name="v">
               <xs:simpleType>
                 <xs:restriction base="{base}">{facets}</xs:restriction>
               </xs:simpleType>
             </xs:element>
           </xs:schema>"#
    );
    parse_schema(&xsd).expect("valid schema")
}

fn report(schema: &xmlschema::Schema, value: &str) -> xmlschema::Report {
    let doc = oxml::parse(&format!("<v>{value}</v>")).expect("well-formed");
    validate(&doc, schema)
}

fn accepts(schema: &xmlschema::Schema, value: &str) -> bool {
    report(schema, value).violations.is_empty()
}

#[test]
fn enumeration_admits_only_listed_values() {
    let s = restricted(
        "xs:string",
        r#"<xs:enumeration value="red"/><xs:enumeration value="green"/>"#,
    );
    assert!(accepts(&s, "red"));
    assert!(accepts(&s, "green"));
    assert!(!accepts(&s, "blue"));
    assert!(!accepts(&s, ""));
    assert!(!accepts(&s, "RED"), "enumeration is case sensitive");
}

#[test]
fn an_enumeration_violation_lists_the_permitted_values() {
    let s = restricted(
        "xs:string",
        r#"<xs:enumeration value="red"/><xs:enumeration value="green"/>"#,
    );
    let text = report(&s, "blue").to_string();
    assert!(text.contains("red"), "{text}");
    assert!(text.contains("green"), "{text}");
}

#[test]
fn length_requires_exactly_that_many_characters() {
    let s = restricted("xs:string", r#"<xs:length value="3"/>"#);
    assert!(accepts(&s, "abc"));
    assert!(!accepts(&s, "ab"));
    assert!(!accepts(&s, "abcd"));
    let text = report(&s, "ab").to_string();
    assert!(text.contains('3'), "{text}");
}

#[test]
fn min_and_max_length_bound_each_end() {
    let s = restricted(
        "xs:string",
        r#"<xs:minLength value="2"/><xs:maxLength value="4"/>"#,
    );
    assert!(!accepts(&s, "a"));
    assert!(accepts(&s, "ab"));
    assert!(accepts(&s, "abcd"));
    assert!(!accepts(&s, "abcde"));

    assert!(report(&s, "a").to_string().contains('2'));
    assert!(report(&s, "abcde").to_string().contains('4'));
}

#[test]
fn length_counts_characters_not_bytes() {
    // A multi-byte character is one character; counting bytes would
    // reject valid values in every non-ASCII document.
    let s = restricted("xs:string", r#"<xs:length value="3"/>"#);
    assert!(
        accepts(&s, "é中x"),
        "three characters, more than three bytes"
    );
    assert!(!accepts(&s, "é中"));
}

#[test]
fn inclusive_bounds_include_their_endpoints() {
    let s = restricted(
        "xs:integer",
        r#"<xs:minInclusive value="1"/><xs:maxInclusive value="10"/>"#,
    );
    assert!(!accepts(&s, "0"));
    assert!(accepts(&s, "1"), "minInclusive must admit its endpoint");
    assert!(accepts(&s, "10"), "maxInclusive must admit its endpoint");
    assert!(!accepts(&s, "11"));
}

#[test]
fn exclusive_bounds_exclude_their_endpoints() {
    let s = restricted(
        "xs:integer",
        r#"<xs:minExclusive value="1"/><xs:maxExclusive value="10"/>"#,
    );
    assert!(!accepts(&s, "1"), "minExclusive must reject its endpoint");
    assert!(accepts(&s, "2"));
    assert!(accepts(&s, "9"));
    assert!(!accepts(&s, "10"), "maxExclusive must reject its endpoint");
}

#[test]
fn a_bound_violation_names_the_bound() {
    let s = restricted("xs:integer", r#"<xs:maxInclusive value="10"/>"#);
    let text = report(&s, "11").to_string();
    assert!(text.contains("10"), "{text}");
}

#[test]
fn a_pattern_facet_is_enforced() {
    let s =
        restricted("xs:string", r#"<xs:pattern value="[A-Z]{2}[0-9]{3}"/>"#);
    assert!(accepts(&s, "AB123"));
    assert!(!accepts(&s, "ab123"));
    assert!(!accepts(&s, "AB12"));
    assert!(!accepts(&s, "XAB123"), "patterns are anchored");
}

#[test]
fn facets_compose_and_every_failure_is_reported() {
    let s = restricted(
        "xs:string",
        r#"<xs:minLength value="3"/><xs:pattern value="[a-z]+"/>"#,
    );
    assert!(accepts(&s, "abc"));
    assert!(!accepts(&s, "ab"), "too short");
    assert!(!accepts(&s, "ABC"), "wrong pattern");
}

#[test]
fn an_attribute_is_validated_against_its_type() {
    let xsd = r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xs:element name="r">
          <xs:complexType>
            <xs:sequence/>
            <xs:attribute name="n" type="xs:integer" use="required"/>
          </xs:complexType>
        </xs:element>
      </xs:schema>"#;
    let s = parse_schema(xsd).expect("valid schema");

    let ok = oxml::parse(r#"<r n="42"/>"#).expect("well-formed");
    assert!(validate(&ok, &s).violations.is_empty());

    let bad = oxml::parse(r#"<r n="forty"/>"#).expect("well-formed");
    assert!(!validate(&bad, &s).violations.is_empty());

    let missing = oxml::parse("<r/>").expect("well-formed");
    let report = validate(&missing, &s);
    assert!(!report.violations.is_empty(), "required attribute absent");
    assert!(report.to_string().contains('n'), "{report}");
}

#[test]
fn an_attribute_with_an_inline_simple_type_is_constrained() {
    let xsd = r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xs:element name="r">
          <xs:complexType>
            <xs:sequence/>
            <xs:attribute name="code">
              <xs:simpleType>
                <xs:restriction base="xs:string">
                  <xs:enumeration value="A"/>
                </xs:restriction>
              </xs:simpleType>
            </xs:attribute>
          </xs:complexType>
        </xs:element>
      </xs:schema>"#;
    let s = parse_schema(xsd).expect("valid schema");

    let ok = oxml::parse(r#"<r code="A"/>"#).expect("well-formed");
    assert!(validate(&ok, &s).violations.is_empty());

    let bad = oxml::parse(r#"<r code="B"/>"#).expect("well-formed");
    assert!(!validate(&bad, &s).violations.is_empty());
}

#[test]
fn an_attribute_with_no_declared_type_accepts_anything() {
    let xsd = r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xs:element name="r">
          <xs:complexType>
            <xs:sequence/>
            <xs:attribute name="free"/>
          </xs:complexType>
        </xs:element>
      </xs:schema>"#;
    let s = parse_schema(xsd).expect("valid schema");
    let doc = oxml::parse(r#"<r free="anything at all"/>"#).expect("ok");
    assert!(validate(&doc, &s).violations.is_empty());
}

#[test]
fn an_unrecognised_base_type_falls_back_to_string() {
    // An unknown base must not silently reject every value.
    let s = restricted("xs:madeUpType", r#"<xs:minLength value="2"/>"#);
    assert!(accepts(&s, "ab"));
    assert!(!accepts(&s, "a"));
}

/// `xs:totalDigits` and `xs:fractionDigits` count *significant*
/// digits, which is a property of the value and not of how it was
/// written.
#[test]
fn digit_facets_count_significant_digits() {
    let xsd = r#"
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="v">
    <xs:simpleType>
      <xs:restriction base="xs:decimal">
        <xs:totalDigits value="3"/>
        <xs:fractionDigits value="1"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:element>
</xs:schema>"#;
    let schema = parse_schema(xsd).expect("schema parses");
    let accepts = |v: &str| {
        let doc = oxml::parse(&format!("<v>{v}</v>")).expect("well-formed");
        validate(&doc, &schema).is_valid()
    };
    assert!(accepts("12.3"), "three total, one fraction");
    assert!(
        accepts("1.0"),
        "trailing fraction zeros are not significant"
    );
    assert!(accepts("012.3"), "leading zeros are not significant");
    assert!(accepts("0"), "zero has one significant digit");
    assert!(accepts("-12.3"), "the sign is not a digit");
    assert!(!accepts("1234"), "four total digits");
    assert!(!accepts("1.23"), "two fraction digits");
}

/// `xs:whiteSpace` decides what the value *is*, so it applies before
/// every other check.
#[test]
fn the_whitespace_facet_applies_before_validation() {
    let with = |rule: &str| {
        format!(
            r#"
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="v">
    <xs:simpleType>
      <xs:restriction base="xs:string">
        <xs:whiteSpace value="{rule}"/>
        <xs:maxLength value="3"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:element>
</xs:schema>"#
        )
    };
    let accepts = |rule: &str, v: &str| {
        let schema = parse_schema(&with(rule)).expect("schema parses");
        let doc = oxml::parse(&format!("<v>{v}</v>")).expect("well-formed");
        validate(&doc, &schema).is_valid()
    };
    // "  a  " is five characters preserved, one collapsed.
    assert!(!accepts("preserve", "  a  "), "five characters");
    assert!(accepts("collapse", "  a  "), "collapses to one");
    // Replace turns tabs into spaces without collapsing them.
    assert!(!accepts("replace", "\ta\tb\t"), "still five characters");
    assert!(accepts("collapse", "\ta\tb\t"), "collapses to three");
}

/// Bounds apply to dates, times and durations, not only to numbers.
///
/// They were stored as `f64`, so `minInclusive="2000-01-01"` failed to
/// parse and the facet was dropped in silence — the schema looked
/// constrained and enforced nothing.
#[test]
fn bounds_apply_to_temporal_types() {
    let bounded = |ty: &str, min: &str, max: &str| {
        format!(
            r#"
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="v">
    <xs:simpleType>
      <xs:restriction base="xs:{ty}">
        <xs:minInclusive value="{min}"/>
        <xs:maxInclusive value="{max}"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:element>
</xs:schema>"#
        )
    };
    let accepts = |ty: &str, min: &str, max: &str, v: &str| {
        let schema = parse_schema(&bounded(ty, min, max)).expect("parses");
        let doc = oxml::parse(&format!("<v>{v}</v>")).expect("well-formed");
        validate(&doc, &schema).is_valid()
    };

    // date
    assert!(accepts("date", "2000-01-01", "2000-12-31", "2000-06-15"));
    assert!(!accepts("date", "2000-01-01", "2000-12-31", "1999-12-31"));
    assert!(!accepts("date", "2000-01-01", "2000-12-31", "2001-01-01"));
    // The boundaries themselves are inclusive.
    assert!(accepts("date", "2000-01-01", "2000-12-31", "2000-01-01"));
    assert!(accepts("date", "2000-01-01", "2000-12-31", "2000-12-31"));

    // dateTime orders within a day, not just across days.
    assert!(accepts(
        "dateTime",
        "2000-01-01T00:00:00",
        "2000-01-01T12:00:00",
        "2000-01-01T06:00:00"
    ));
    assert!(!accepts(
        "dateTime",
        "2000-01-01T00:00:00",
        "2000-01-01T12:00:00",
        "2000-01-01T18:00:00"
    ));

    // duration, where a year outranks a day.
    assert!(accepts("duration", "P1D", "P1Y", "P6M"));
    assert!(!accepts("duration", "P1D", "P1Y", "P2Y"));

    // gYear and gMonth are ordered too.
    assert!(accepts("gYear", "1999", "2001", "2000"));
    assert!(!accepts("gYear", "1999", "2001", "2002"));
    assert!(accepts("gMonth", "--03", "--09", "--06"));
    assert!(!accepts("gMonth", "--03", "--09", "--11"));

    // And the numeric case still works.
    assert!(accepts("integer", "1", "10", "5"));
    assert!(!accepts("integer", "1", "10", "11"));
}

/// Decimals compare exactly, not through `f64`.
///
/// `xs:integer` is unbounded and `xs:decimal` has no precision limit,
/// so an eighteen-digit bound compared through a float made two
/// distinct values equal — and a value that must be *less than* its
/// neighbour was reported as violating it.
#[test]
fn large_decimals_compare_without_losing_precision() {
    let xsd = r#"
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="v">
    <xs:simpleType>
      <xs:restriction base="xs:integer">
        <xs:maxExclusive value="999999999999999999"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:element>
</xs:schema>"#;
    let schema = parse_schema(xsd).expect("schema parses");
    let accepts = |v: &str| {
        let doc = oxml::parse(&format!("<v>{v}</v>")).expect("well-formed");
        validate(&doc, &schema).is_valid()
    };
    // Both are past 2^53, where an f64 cannot tell them apart.
    assert!(accepts("999999999999999998"), "one less than the bound");
    assert!(!accepts("999999999999999999"), "the bound is exclusive");
    assert!(!accepts("1000000000000000000"), "past the bound");
    // Sign, leading zeros and trailing fraction zeros do not change
    // the value.
    assert!(accepts("-999999999999999999"));
    assert!(accepts("000000000000000001"));
}

/// A pattern on a list constrains the whole space-separated value.
///
/// It was not applied at all, which left every `list-<type>-pattern`
/// schema accepting anything — around five hundred tests in the W3C
/// suite.
#[test]
fn a_pattern_on_a_list_applies_to_the_whole_value() {
    let xsd = r#"
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="v">
    <xs:simpleType>
      <xs:restriction>
        <xs:simpleType><xs:list itemType="xs:integer"/></xs:simpleType>
        <xs:pattern value="[0-9]+ [0-9]+"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:element>
</xs:schema>"#;
    let schema = parse_schema(xsd).expect("schema parses");
    let accepts = |v: &str| {
        let doc = oxml::parse(&format!("<v>{v}</v>")).expect("well-formed");
        validate(&doc, &schema).is_valid()
    };
    assert!(accepts("12 34"), "two integers, as the pattern requires");
    assert!(!accepts("12"), "one item does not match the whole form");
    assert!(!accepts("12 34 56"), "three do not either");
}

/// `xs:NMTOKENS` is a list type, so its length facets count items.
#[test]
fn built_in_list_types_count_items_not_characters() {
    let xsd = r#"
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="v">
    <xs:simpleType>
      <xs:restriction base="xs:NMTOKENS">
        <xs:minLength value="2"/>
        <xs:maxLength value="3"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:element>
</xs:schema>"#;
    let schema = parse_schema(xsd).expect("schema parses");
    let accepts = |v: &str| {
        let doc = oxml::parse(&format!("<v>{v}</v>")).expect("well-formed");
        validate(&doc, &schema).is_valid()
    };
    assert!(accepts("aa bb"), "two items");
    assert!(accepts("aa bb cc"), "three items");
    // One item, but four characters — a character count would pass it.
    assert!(!accepts("abcd"), "one item is fewer than two");
    assert!(!accepts("a b c d"), "four items is more than three");
}