fastxml 0.8.1

A fast, memory-efficient XML library with XPath and XSD validation support
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
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
//! Advanced identity constraint validation tests.
//!
//! Tests for identity constraints that are not covered in the main validation_test.rs:
//! - SelectorError
//! - FieldError
//! - Null value handling in different constraint types
//! - Multiple keyrefs referencing the same key
//! - Complex composite key scenarios

use fastxml::schema::xsd::constraints::{
    ConstraintError, ConstraintValidator, IdentityConstraint, KeyValue,
};

// =============================================================================
// Null Value Handling Tests
// =============================================================================

mod null_value_handling {
    use super::*;

    #[test]
    fn test_key_rejects_null_in_any_field() {
        let constraint =
            IdentityConstraint::key("composite-key", ".//item").with_fields(["@type", "@id"]);

        let mut validator = ConstraintValidator::new();
        validator.register_key("composite-key", 2);

        // First field is null
        let result =
            validator.add_key_value(&constraint, KeyValue::new(vec!["".into(), "123".into()]));
        assert!(
            matches!(
                &result,
                Err(ConstraintError::NullKeyValue {
                    constraint,
                    field_index: 0
                }) if constraint == "composite-key"
            ),
            "Key should reject null in first field, got: {:?}",
            result
        );

        // Second field is null
        let result =
            validator.add_key_value(&constraint, KeyValue::new(vec!["type1".into(), "".into()]));
        assert!(
            matches!(
                &result,
                Err(ConstraintError::NullKeyValue {
                    constraint,
                    field_index: 1
                }) if constraint == "composite-key"
            ),
            "Key should reject null in second field, got: {:?}",
            result
        );
    }

    #[test]
    fn test_unique_allows_null_values() {
        let constraint = IdentityConstraint::unique("unique-id", ".//item").with_field("@id");

        let mut validator = ConstraintValidator::new();

        // Multiple null values should be allowed for unique
        assert!(
            validator
                .add_key_value(&constraint, KeyValue::single(""))
                .is_ok(),
            "Unique should allow first null"
        );
        assert!(
            validator
                .add_key_value(&constraint, KeyValue::single(""))
                .is_ok(),
            "Unique should allow second null"
        );
        assert!(
            validator
                .add_key_value(&constraint, KeyValue::single(""))
                .is_ok(),
            "Unique should allow third null"
        );

        // Non-null values should still be unique
        assert!(
            validator
                .add_key_value(&constraint, KeyValue::single("value1"))
                .is_ok()
        );
        let result = validator.add_key_value(&constraint, KeyValue::single("value1"));
        assert!(
            matches!(&result, Err(ConstraintError::DuplicateKey { .. })),
            "Unique should still reject duplicate non-null values, got: {:?}",
            result
        );
    }

    #[test]
    fn test_unique_composite_with_partial_null() {
        let constraint =
            IdentityConstraint::unique("composite-unique", ".//item").with_fields(["@a", "@b"]);

        let mut validator = ConstraintValidator::new();

        // Composite with one null field - should be allowed (doesn't participate in uniqueness)
        assert!(
            validator
                .add_key_value(&constraint, KeyValue::new(vec!["value".into(), "".into()]))
                .is_ok()
        );
        assert!(
            validator
                .add_key_value(&constraint, KeyValue::new(vec!["value".into(), "".into()]))
                .is_ok()
        );
    }

    #[test]
    fn test_keyref_with_null_skipped() {
        let key = IdentityConstraint::key("person-id", ".//person").with_field("@id");
        let keyref =
            IdentityConstraint::keyref("order-person", ".//order", "person-id").with_field("@ref");

        let mut validator = ConstraintValidator::new();
        validator.register_key("person-id", 1);

        // Add a key
        validator
            .add_key_value(&key, KeyValue::single("p1"))
            .unwrap();

        // Null keyref should be skipped (not validated)
        validator.add_keyref_value(&keyref, KeyValue::single(""));

        // Validation should pass because null keyref is skipped
        let result = validator.validate_keyrefs();
        assert!(
            result.is_ok(),
            "Null keyref values should be skipped, got: {:?}",
            result
        );
    }
}

// =============================================================================
// Complex Composite Key Tests
// =============================================================================

mod composite_keys {
    use super::*;

    #[test]
    fn test_three_field_composite_key() {
        let constraint = IdentityConstraint::key("triple-key", ".//record")
            .with_fields(["@year", "@month", "@day"]);

        let mut validator = ConstraintValidator::new();
        validator.register_key("triple-key", 3);

        // Add several unique composite keys
        assert!(
            validator
                .add_key_value(
                    &constraint,
                    KeyValue::new(vec!["2024".into(), "01".into(), "01".into()])
                )
                .is_ok()
        );
        assert!(
            validator
                .add_key_value(
                    &constraint,
                    KeyValue::new(vec!["2024".into(), "01".into(), "02".into()])
                )
                .is_ok()
        );
        assert!(
            validator
                .add_key_value(
                    &constraint,
                    KeyValue::new(vec!["2024".into(), "02".into(), "01".into()])
                )
                .is_ok()
        );

        // Duplicate should fail
        let result = validator.add_key_value(
            &constraint,
            KeyValue::new(vec!["2024".into(), "01".into(), "01".into()]),
        );
        assert!(
            matches!(&result, Err(ConstraintError::DuplicateKey { .. })),
            "Duplicate composite key should fail, got: {:?}",
            result
        );
    }

    #[test]
    fn test_composite_keyref() {
        let key =
            IdentityConstraint::key("product-key", ".//product").with_fields(["@category", "@sku"]);
        let keyref = IdentityConstraint::keyref("order-product", ".//order-item", "product-key")
            .with_fields(["@cat", "@product-sku"]);

        let mut validator = ConstraintValidator::new();
        validator.register_key("product-key", 2);

        // Add keys
        validator
            .add_key_value(
                &key,
                KeyValue::new(vec!["electronics".into(), "TV-001".into()]),
            )
            .unwrap();
        validator
            .add_key_value(
                &key,
                KeyValue::new(vec!["electronics".into(), "TV-002".into()]),
            )
            .unwrap();

        // Valid keyref
        validator.add_keyref_value(
            &keyref,
            KeyValue::new(vec!["electronics".into(), "TV-001".into()]),
        );

        // Invalid keyref (wrong combination)
        validator.add_keyref_value(
            &keyref,
            KeyValue::new(vec!["electronics".into(), "TV-999".into()]),
        );

        let result = validator.validate_keyrefs();
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(
            matches!(
                &errors[0],
                ConstraintError::KeyRefNotFound {
                    constraint,
                    refer,
                    ..
                } if constraint == "order-product" && refer == "product-key"
            ),
            "Expected KeyRefNotFound for composite key, got: {:?}",
            errors[0]
        );
    }
}

// =============================================================================
// Multiple KeyRefs Tests
// =============================================================================

mod multiple_keyrefs {
    use super::*;

    #[test]
    fn test_multiple_keyrefs_same_key() {
        let key = IdentityConstraint::key("user-id", ".//user").with_field("@id");
        let keyref1 =
            IdentityConstraint::keyref("post-author", ".//post", "user-id").with_field("@author");
        let keyref2 =
            IdentityConstraint::keyref("comment-author", ".//comment", "user-id").with_field("@by");

        let mut validator = ConstraintValidator::new();
        validator.register_key("user-id", 1);

        // Add keys
        validator
            .add_key_value(&key, KeyValue::single("user1"))
            .unwrap();
        validator
            .add_key_value(&key, KeyValue::single("user2"))
            .unwrap();

        // Valid keyrefs from different constraints
        validator.add_keyref_value(&keyref1, KeyValue::single("user1"));
        validator.add_keyref_value(&keyref2, KeyValue::single("user2"));

        // Invalid keyref from first constraint
        validator.add_keyref_value(&keyref1, KeyValue::single("user999"));

        let result = validator.validate_keyrefs();
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(
            matches!(
                &errors[0],
                ConstraintError::KeyRefNotFound { constraint, .. } if constraint == "post-author"
            ),
            "Error should be from post-author keyref, got: {:?}",
            errors[0]
        );
    }

    #[test]
    fn test_keyref_to_nonexistent_key() {
        let keyref =
            IdentityConstraint::keyref("orphan-ref", ".//orphan", "missing-key").with_field("@ref");

        let mut validator = ConstraintValidator::new();
        // Don't register the key

        validator.add_keyref_value(&keyref, KeyValue::single("value"));

        let result = validator.validate_keyrefs();
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(
            matches!(
                &errors[0],
                ConstraintError::KeyRefNotFound { refer, .. } if refer == "missing-key"
            ),
            "Should report missing key, got: {:?}",
            errors[0]
        );
    }
}

// =============================================================================
// Key Value Set Tests
// =============================================================================

mod key_value_set {
    use super::*;
    use fastxml::schema::xsd::constraints::KeyValueSet;

    #[test]
    fn test_key_value_set_basic_operations() {
        let mut set = KeyValueSet::new("test-set", 1);

        assert!(set.is_empty());
        assert_eq!(set.len(), 0);

        // Add values
        assert!(set.add(KeyValue::single("a")).is_ok());
        assert!(set.add(KeyValue::single("b")).is_ok());

        assert!(!set.is_empty());
        assert_eq!(set.len(), 2);

        // Check contains
        assert!(set.contains(&KeyValue::single("a")));
        assert!(set.contains(&KeyValue::single("b")));
        assert!(!set.contains(&KeyValue::single("c")));
    }

    #[test]
    fn test_key_value_set_duplicate_detection() {
        let mut set = KeyValueSet::new("dup-test", 1);

        assert!(set.add(KeyValue::single("value")).is_ok());
        let result = set.add(KeyValue::single("value"));
        assert!(
            matches!(
                &result,
                Err(ConstraintError::DuplicateKey {
                    constraint,
                    value
                }) if constraint == "dup-test" && value.values == vec!["value".to_string()]
            ),
            "Should detect duplicate, got: {:?}",
            result
        );
    }

    #[test]
    fn test_key_value_set_iteration() {
        let mut set = KeyValueSet::new("iter-test", 1);

        set.add(KeyValue::single("x")).unwrap();
        set.add(KeyValue::single("y")).unwrap();
        set.add(KeyValue::single("z")).unwrap();

        let values: Vec<_> = set.values().collect();
        assert_eq!(values.len(), 3);

        // Check all values are present (order may vary due to HashSet)
        let value_strings: Vec<&str> = values.iter().map(|kv| kv.values[0].as_str()).collect();
        assert!(value_strings.contains(&"x"));
        assert!(value_strings.contains(&"y"));
        assert!(value_strings.contains(&"z"));
    }
}

// =============================================================================
// KeyValue Tests
// =============================================================================

mod key_value {
    use super::*;

    #[test]
    fn test_key_value_has_null() {
        let complete = KeyValue::new(vec!["a".into(), "b".into()]);
        assert!(!complete.has_null());

        let with_null = KeyValue::new(vec!["a".into(), "".into()]);
        assert!(with_null.has_null());

        let all_null = KeyValue::new(vec!["".into(), "".into()]);
        assert!(all_null.has_null());

        let empty = KeyValue::new(vec![]);
        assert!(!empty.has_null()); // No values means no nulls
    }

    #[test]
    fn test_key_value_is_complete() {
        let value = KeyValue::new(vec!["a".into(), "b".into()]);

        assert!(value.is_complete(2));
        assert!(!value.is_complete(3)); // Wrong field count

        let with_null = KeyValue::new(vec!["a".into(), "".into()]);
        assert!(!with_null.is_complete(2)); // Has null

        let too_few = KeyValue::new(vec!["a".into()]);
        assert!(!too_few.is_complete(2)); // Not enough fields
    }

    #[test]
    fn test_key_value_equality() {
        let a = KeyValue::new(vec!["x".into(), "y".into()]);
        let b = KeyValue::new(vec!["x".into(), "y".into()]);
        let c = KeyValue::new(vec!["x".into(), "z".into()]);

        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn test_key_value_hash() {
        use std::collections::HashSet;

        let mut set = HashSet::new();

        let a = KeyValue::new(vec!["x".into(), "y".into()]);
        let b = KeyValue::new(vec!["x".into(), "y".into()]);
        let c = KeyValue::new(vec!["x".into(), "z".into()]);

        set.insert(a.clone());
        assert!(set.contains(&b)); // Equal values should hash the same
        assert!(!set.contains(&c));

        set.insert(b);
        assert_eq!(set.len(), 1); // Should not add duplicate

        set.insert(c);
        assert_eq!(set.len(), 2);
    }
}

// =============================================================================
// Validator Reset and Reuse Tests
// =============================================================================

mod validator_lifecycle {
    use super::*;

    #[test]
    fn test_validator_reset() {
        let constraint = IdentityConstraint::unique("test-unique", ".//item").with_field("@id");

        let mut validator = ConstraintValidator::new();

        // Add some values
        validator
            .add_key_value(&constraint, KeyValue::single("a"))
            .unwrap();
        validator
            .add_key_value(&constraint, KeyValue::single("b"))
            .unwrap();

        // Verify values exist
        let set = validator.get_key_values("test-unique");
        assert!(set.is_some());
        assert_eq!(set.unwrap().len(), 2);

        // Reset
        validator.reset();

        // Values should be cleared
        let set = validator.get_key_values("test-unique");
        assert!(set.is_none());

        // Should be able to add values again
        validator
            .add_key_value(&constraint, KeyValue::single("a"))
            .unwrap();
        let _ = validator.add_key_value(&constraint, KeyValue::single("a")); // Would fail if state wasn't reset
    }

    #[test]
    fn test_validator_multiple_constraints() {
        let unique1 = IdentityConstraint::unique("unique1", ".//a").with_field("@id");
        let unique2 = IdentityConstraint::unique("unique2", ".//b").with_field("@id");

        let mut validator = ConstraintValidator::new();

        // Same value in different constraints should be allowed
        validator
            .add_key_value(&unique1, KeyValue::single("shared"))
            .unwrap();
        validator
            .add_key_value(&unique2, KeyValue::single("shared"))
            .unwrap();

        // But duplicate in same constraint should fail
        let result = validator.add_key_value(&unique1, KeyValue::single("shared"));
        assert!(
            matches!(&result, Err(ConstraintError::DuplicateKey { .. })),
            "Duplicate in same constraint should fail, got: {:?}",
            result
        );
    }

    #[test]
    fn test_get_key_values() {
        let constraint = IdentityConstraint::key("test-key", ".//item").with_field("@id");

        let mut validator = ConstraintValidator::new();
        validator.register_key("test-key", 1);

        // Before adding values
        let set = validator.get_key_values("test-key");
        assert!(set.is_some());
        assert!(set.unwrap().is_empty());

        // After adding values
        validator
            .add_key_value(&constraint, KeyValue::single("v1"))
            .unwrap();
        validator
            .add_key_value(&constraint, KeyValue::single("v2"))
            .unwrap();

        let set = validator.get_key_values("test-key");
        assert!(set.is_some());
        assert_eq!(set.unwrap().len(), 2);

        // Non-existent constraint
        let set = validator.get_key_values("nonexistent");
        assert!(set.is_none());
    }
}

// =============================================================================
// Error Display Tests
// =============================================================================

mod error_display {
    use super::*;

    #[test]
    fn test_duplicate_key_error_display() {
        let err = ConstraintError::DuplicateKey {
            constraint: "user-id".to_string(),
            value: KeyValue::single("duplicate"),
        };

        let msg = err.to_string();
        assert!(msg.contains("duplicate"));
        assert!(msg.contains("user-id"));
    }

    #[test]
    fn test_null_key_error_display() {
        let err = ConstraintError::NullKeyValue {
            constraint: "required-key".to_string(),
            field_index: 2,
        };

        let msg = err.to_string();
        assert!(msg.contains("null"));
        assert!(msg.contains("required-key"));
        assert!(msg.contains("2"));
    }

    #[test]
    fn test_keyref_not_found_error_display() {
        let err = ConstraintError::KeyRefNotFound {
            constraint: "order-ref".to_string(),
            refer: "product-key".to_string(),
            value: KeyValue::new(vec!["missing".into()]),
        };

        let msg = err.to_string();
        assert!(msg.contains("order-ref"));
        assert!(msg.contains("product-key"));
        assert!(msg.contains("missing"));
    }

    #[test]
    fn test_selector_error_display() {
        let err = ConstraintError::SelectorError {
            constraint: "bad-selector".to_string(),
            message: "Invalid XPath expression".to_string(),
        };

        let msg = err.to_string();
        assert!(msg.contains("bad-selector"));
        assert!(msg.contains("Invalid XPath"));
    }

    #[test]
    fn test_field_error_display() {
        let err = ConstraintError::FieldError {
            constraint: "bad-field".to_string(),
            field_index: 0,
            message: "Field not found".to_string(),
        };

        let msg = err.to_string();
        assert!(msg.contains("bad-field"));
        assert!(msg.contains("0"));
        assert!(msg.contains("Field not found"));
    }
}

// =============================================================================
// Identity Constraint Builder Tests
// =============================================================================

mod constraint_builder {
    use super::*;

    #[test]
    fn test_unique_builder() {
        let constraint = IdentityConstraint::unique("my-unique", ".//item")
            .with_field("@id")
            .with_field("@name");

        assert_eq!(constraint.name, "my-unique");
        assert_eq!(constraint.selector, ".//item");
        assert_eq!(constraint.fields, vec!["@id", "@name"]);
        assert!(constraint.refer.is_none());
    }

    #[test]
    fn test_key_builder() {
        let constraint =
            IdentityConstraint::key("my-key", ".//record").with_fields(["@year", "@month", "@day"]);

        assert_eq!(constraint.name, "my-key");
        assert_eq!(constraint.selector, ".//record");
        assert_eq!(constraint.fields, vec!["@year", "@month", "@day"]);
        assert!(constraint.refer.is_none());
    }

    #[test]
    fn test_keyref_builder() {
        let constraint = IdentityConstraint::keyref("my-keyref", ".//reference", "target-key")
            .with_field("@ref");

        assert_eq!(constraint.name, "my-keyref");
        assert_eq!(constraint.selector, ".//reference");
        assert_eq!(constraint.fields, vec!["@ref"]);
        assert_eq!(constraint.refer, Some("target-key".to_string()));
    }
}