yaml-edit 0.3.3

A lossless parser and editor for YAML files
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
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
//! Validating documents against the failsafe, JSON and core schemas and
//! custom ones: which values each schema accepts, coercion and error paths.

use yaml_edit::{
    CustomSchema, CustomValidationResult, Document, ScalarType, Schema, SchemaValidator,
    ValidationError, ValidationErrorKind, YamlFile,
};

#[test]
fn schema_names() {
    assert_eq!(Schema::Failsafe.name(), "failsafe");
    assert_eq!(Schema::Json.name(), "json");
    assert_eq!(Schema::Core.name(), "core");
}

#[test]
fn failsafe_schema_allows_only_strings() {
    let schema = Schema::Failsafe;

    assert!(schema.allows_scalar_type(ScalarType::String));
    assert!(!schema.allows_scalar_type(ScalarType::Integer));
    assert!(!schema.allows_scalar_type(ScalarType::Float));
    assert!(!schema.allows_scalar_type(ScalarType::Boolean));
    assert!(!schema.allows_scalar_type(ScalarType::Null));
    #[cfg(feature = "base64")]
    assert!(!schema.allows_scalar_type(ScalarType::Binary));
    assert!(!schema.allows_scalar_type(ScalarType::Timestamp));
    assert!(!schema.allows_scalar_type(ScalarType::Regex));
}

#[test]
fn json_schema_allows_json_types() {
    let schema = Schema::Json;

    assert!(schema.allows_scalar_type(ScalarType::String));
    assert!(schema.allows_scalar_type(ScalarType::Integer));
    assert!(schema.allows_scalar_type(ScalarType::Float));
    assert!(schema.allows_scalar_type(ScalarType::Boolean));
    assert!(schema.allows_scalar_type(ScalarType::Null));
    #[cfg(feature = "base64")]
    assert!(!schema.allows_scalar_type(ScalarType::Binary));
    assert!(!schema.allows_scalar_type(ScalarType::Timestamp));
    assert!(!schema.allows_scalar_type(ScalarType::Regex));
}

#[test]
fn core_schema_allows_all_types() {
    let schema = Schema::Core;

    assert!(schema.allows_scalar_type(ScalarType::String));
    assert!(schema.allows_scalar_type(ScalarType::Integer));
    assert!(schema.allows_scalar_type(ScalarType::Float));
    assert!(schema.allows_scalar_type(ScalarType::Boolean));
    assert!(schema.allows_scalar_type(ScalarType::Null));
    #[cfg(feature = "base64")]
    assert!(schema.allows_scalar_type(ScalarType::Binary));
    assert!(schema.allows_scalar_type(ScalarType::Timestamp));
    assert!(schema.allows_scalar_type(ScalarType::Regex));
}

#[test]
fn validation_error_display() {
    let error = ValidationError::type_not_allowed(
        "root.items[0]",
        "test-schema",
        ScalarType::Integer,
        vec![ScalarType::String],
    );

    assert_eq!(
            format!("{}", error),
            "Validation error at root.items[0]: type Integer not allowed in test-schema schema, expected one of [String]"
        );
}

fn create_test_document(content: &str) -> Document {
    let parsed = content
        .parse::<YamlFile>()
        .expect("Failed to parse test YAML");
    parsed.document().expect("Expected a document")
}

#[test]
fn failsafe_validation_success() {
    let yaml_str = r#"
name: "John Doe"
items:
  - "item1"
  - "item2"
nested:
  key: "value"
"#;
    let document = create_test_document(yaml_str);
    let validator = SchemaValidator::failsafe();

    assert!(validator.validate(&document).is_ok());
}

#[test]
fn json_validation_success() {
    let yaml_str = r#"
name: "John Doe"
age: 30
height: 5.9
active: true
metadata: null
items:
  - "item1"
  - 42
  - true
"#;
    let document = create_test_document(yaml_str);
    let validator = SchemaValidator::json();

    assert!(validator.validate(&document).is_ok());
}

#[test]
fn core_validation_success() {
    let yaml_str = "\nname: \"John Doe\" \nage: 30\nbirth_date: !!timestamp \"2001-12-15T02:59:43.1Z\"\npattern: !!regex '\\d{3}-\\d{4}'\n";
    let document = create_test_document(yaml_str);
    let validator = SchemaValidator::core();

    assert!(validator.validate(&document).is_ok());
}

#[test]
fn failsafe_validation_failure() {
    let yaml_str = r#"
name: "John"
age: 30
active: true
"#;
    let document = create_test_document(yaml_str);
    let validator = SchemaValidator::failsafe().strict();

    let result = validator.validate(&document);
    // Should fail because age (integer) and active (boolean) are not allowed in failsafe schema
    assert!(result.is_err());
    let errors = result.unwrap_err();
    assert!(!errors.is_empty());

    // Should have errors for integer and boolean types
    assert!(errors.iter().all(|e| e.schema_name == "failsafe"));
    assert!(errors
        .iter()
        .all(|e| matches!(&e.kind, ValidationErrorKind::TypeNotAllowed { .. })));
}

#[test]
fn validation_error_paths() {
    let yaml_str =
        "\nusers:\n  - name: \"John\"\n    age: 30\n  - name: \"Jane\" \n    active: true\n";
    let document = create_test_document(yaml_str);
    let validator = SchemaValidator::failsafe();

    let result = validator.validate(&document);
    if let Err(errors) = result {
        // Check that error paths are meaningful and start with "root"
        for error in &errors {
            assert!(!error.path.is_empty());
            assert!(
                error.path.starts_with("root"),
                "expected path to start with 'root', got: {:?}",
                error.path
            );
        }
    }
}

#[test]
fn schema_type_lists() {
    assert_eq!(
        Schema::Failsafe.allowed_scalar_types(),
        vec![ScalarType::String]
    );

    assert_eq!(
        Schema::Json.allowed_scalar_types(),
        vec![
            ScalarType::String,
            ScalarType::Integer,
            ScalarType::Float,
            ScalarType::Boolean,
            ScalarType::Null,
        ]
    );

    let core_types = Schema::Core.allowed_scalar_types();
    // Core includes at minimum: String, Integer, Float, Boolean, Null, Timestamp, Regex
    // (plus Binary if the base64 feature is enabled)
    #[cfg_attr(not(feature = "base64"), allow(unused_mut))]
    let mut expected_core = vec![
        ScalarType::String,
        ScalarType::Integer,
        ScalarType::Float,
        ScalarType::Boolean,
        ScalarType::Null,
        ScalarType::Timestamp,
        ScalarType::Regex,
    ];
    #[cfg(feature = "base64")]
    expected_core.insert(5, ScalarType::Binary);
    assert_eq!(core_types, expected_core);
}

#[test]
fn deep_sequence_validation() {
    let yaml_str = r#"
numbers:
  - 1
  - 2.5
  - "three"
  - true
"#;
    let document = create_test_document(yaml_str);

    // Failsafe should fail for non-string types in the sequence
    let failsafe_validator = SchemaValidator::failsafe().strict();
    let result = failsafe_validator.validate(&document);
    assert!(result.is_err());
    let errors = result.unwrap_err();
    assert!(!errors.is_empty());

    // JSON should succeed since all types are JSON-compatible
    let json_validator = SchemaValidator::json();
    let result = json_validator.validate(&document);
    assert!(result.is_ok());

    // Core should succeed since all types are allowed
    let core_validator = SchemaValidator::core();
    let result = core_validator.validate(&document);
    assert!(result.is_ok());
}

#[test]
fn deep_nested_mapping_validation() {
    let yaml_str = r#"
user:
  name: "John"
  details:
    age: 30
    active: true
    scores:
      - 95
      - 87.5
"#;
    let document = create_test_document(yaml_str);

    // Failsafe should fail due to nested integers and booleans
    let failsafe_validator = SchemaValidator::failsafe().strict();
    let result = failsafe_validator.validate(&document);
    assert!(result.is_err());
    let errors = result.unwrap_err();
    assert!(!errors.is_empty());
    // Check that errors have meaningful paths
    let paths: Vec<&str> = errors.iter().map(|e| e.path.as_str()).collect();
    assert!(paths.contains(&"root.user.details.age"));
    assert!(paths.contains(&"root.user.details.scores[0]"));

    // JSON should succeed
    let json_validator = SchemaValidator::json();
    let result = json_validator.validate(&document);
    assert!(result.is_ok());
}

#[test]
fn complex_yaml_types_validation() {
    let yaml_str = r#"
metadata:
  created: !!timestamp "2023-12-25T10:30:45Z"
  pattern: !!regex '\d{3}-\d{4}'
values:
  - !!timestamp "2023-01-01"
  - !!regex '[a-zA-Z]+'
"#;
    let document = create_test_document(yaml_str);

    // Failsafe should fail
    let failsafe_validator = SchemaValidator::failsafe().strict();
    let result = failsafe_validator.validate(&document);
    assert!(result.is_err());

    // JSON should fail
    let json_validator = SchemaValidator::json().strict();
    let result = json_validator.validate(&document);
    assert!(result.is_err());

    // Core should succeed
    let core_validator = SchemaValidator::core();
    let result = core_validator.validate(&document);
    assert!(result.is_ok());
}

#[test]
fn coercion_deep_validation() {
    let yaml_str = "\nconfig:\n  timeout: \"30\"  # string that looks like number\n  enabled: \"true\"  # string that looks like boolean  \n  items:\n    - \"42\"\n    - \"false\"\n";
    let document = create_test_document(yaml_str);

    // Non-strict JSON validation should pass via coercion
    let json_validator = SchemaValidator::json();
    let result = json_validator.can_coerce(&document);
    assert!(result.is_ok());

    // Strict JSON validation should fail (strings are not the exact types)
    let strict_json_validator = SchemaValidator::json().strict();
    let result = strict_json_validator.validate(&document);
    // Actually strings are allowed in JSON schema, so this should pass
    assert!(result.is_ok());

    // But if we put non-JSON types, strict mode should fail
    let problematic_yaml = r#"
data:
  timestamp: !!timestamp "2023-12-25"
"#;
    let problematic_doc = create_test_document(problematic_yaml);
    let result = strict_json_validator.validate(&problematic_doc);
    assert!(result.is_err());
}

#[test]
fn validation_error_paths_nested() {
    let yaml_str = r#"
users:
  - name: "Alice"
    metadata:
      created: !!timestamp "2023-01-01"
      tags:
        - "admin"
        - 42  # This should fail in failsafe
  - name: "Bob"
    active: true  # This should fail in failsafe
"#;
    let document = create_test_document(yaml_str);
    let validator = SchemaValidator::failsafe().strict();

    let result = validator.validate(&document);
    assert!(result.is_err());
    let errors = result.unwrap_err();
    assert!(!errors.is_empty());

    // Check that we have errors with proper path information
    let paths: Vec<&str> = errors.iter().map(|e| e.path.as_str()).collect();

    // Should have paths that show the nested structure
    assert!(paths.contains(&"root.users[0].metadata.created"));
    assert!(paths.contains(&"root.users[0].metadata.tags[1]"));
    assert!(paths.contains(&"root.users[1].active"));

    // Print paths for debugging if needed
    for error in &errors {
        println!("Error at {}: {}", error.path, error.message());
    }
}

#[test]
fn yaml_1_2_spec_compliance() {
    // Test that our schemas match YAML 1.2 specification requirements

    // 1. Failsafe Schema - Should only allow strings, mappings, and sequences
    let failsafe = Schema::Failsafe;
    assert!(failsafe.allows_scalar_type(ScalarType::String));
    assert!(!failsafe.allows_scalar_type(ScalarType::Integer));
    assert!(!failsafe.allows_scalar_type(ScalarType::Float));
    assert!(!failsafe.allows_scalar_type(ScalarType::Boolean));
    assert!(!failsafe.allows_scalar_type(ScalarType::Null));
    assert!(!failsafe.allows_scalar_type(ScalarType::Timestamp));

    // 2. JSON Schema - Should allow JSON-compatible types
    let json = Schema::Json;
    assert!(json.allows_scalar_type(ScalarType::String));
    assert!(json.allows_scalar_type(ScalarType::Integer));
    assert!(json.allows_scalar_type(ScalarType::Float));
    assert!(json.allows_scalar_type(ScalarType::Boolean));
    assert!(json.allows_scalar_type(ScalarType::Null));
    assert!(!json.allows_scalar_type(ScalarType::Timestamp)); // Not in JSON
    assert!(!json.allows_scalar_type(ScalarType::Regex)); // Not in JSON
    #[cfg(feature = "base64")]
    assert!(!json.allows_scalar_type(ScalarType::Binary)); // Not in JSON

    // 3. Core Schema - Should allow all YAML types
    let core = Schema::Core;
    assert!(core.allows_scalar_type(ScalarType::String));
    assert!(core.allows_scalar_type(ScalarType::Integer));
    assert!(core.allows_scalar_type(ScalarType::Float));
    assert!(core.allows_scalar_type(ScalarType::Boolean));
    assert!(core.allows_scalar_type(ScalarType::Null));
    assert!(core.allows_scalar_type(ScalarType::Timestamp));
    assert!(core.allows_scalar_type(ScalarType::Regex));
    #[cfg(feature = "base64")]
    assert!(core.allows_scalar_type(ScalarType::Binary));

    // Test schema names match spec
    assert_eq!(failsafe.name(), "failsafe");
    assert_eq!(json.name(), "json");
    assert_eq!(core.name(), "core");
}

#[test]
fn spec_compliant_validation_examples() {
    // Examples from YAML 1.2 specification

    // Failsafe: Should accept plain strings but reject typed values
    let failsafe_yaml = r#"
string: hello
number_as_string: "123"
"#;
    let failsafe_doc = create_test_document(failsafe_yaml);
    let failsafe_validator = SchemaValidator::failsafe();
    // Non-strict mode allows coercion
    assert!(failsafe_validator.validate(&failsafe_doc).is_ok());

    // JSON: Should accept JSON-compatible types
    let json_yaml = r#"
string: "hello"
number: 42
float: 3.14
boolean: true
null_value: null
"#;
    let json_doc = create_test_document(json_yaml);
    let json_validator = SchemaValidator::json();
    assert!(json_validator.validate(&json_doc).is_ok());

    // Core: Should accept all YAML types including timestamps
    let core_yaml = r#"
timestamp: 2023-01-01T00:00:00Z
regex: !!regex '[0-9]+'
binary: !!binary "SGVsbG8gV29ybGQ="
"#;
    let core_doc = create_test_document(core_yaml);
    let core_validator = SchemaValidator::core();
    assert!(core_validator.validate(&core_doc).is_ok());

    // JSON should reject YAML-specific types
    let json_strict = SchemaValidator::json().strict();
    assert!(json_strict.validate(&core_doc).is_err());
}

#[test]
fn custom_schema_basic() {
    // Create a custom schema that only allows strings and integers (strict mode to prevent coercion)
    let custom_schema = CustomSchema::new("test")
        .allow_types(&[ScalarType::String, ScalarType::Integer])
        .strict(); // No coercion

    let validator = SchemaValidator::custom(custom_schema);

    // Test with allowed types
    let valid_yaml = r#"
name: hello world
count: 42
"#;
    let valid_doc = create_test_document(valid_yaml);
    let result = validator.validate(&valid_doc);
    if let Err(ref errors) = result {
        for error in errors {
            println!("Valid test error: {}", error);
        }
    }
    assert!(result.is_ok());

    // Test with disallowed type
    let invalid_yaml = r#"
name: hello world
enabled: true  # boolean not allowed
"#;
    let invalid_doc = create_test_document(invalid_yaml);
    let result = validator.validate(&invalid_doc);
    assert!(result.is_err());

    let errors = result.unwrap_err();
    assert_eq!(errors.len(), 1);
    assert_eq!(
        errors[0].message(),
        "type Boolean not allowed in test schema, expected one of [String, Integer]"
    );
}

#[test]
fn custom_schema_with_validators() {
    // Create a custom schema with string validators
    let custom_schema = CustomSchema::new("email-validation")
        .allow_type(ScalarType::String)
        .with_validator(ScalarType::String, |value, _path| {
            if value.contains('@') && value.contains('.') {
                CustomValidationResult::Valid
            } else {
                CustomValidationResult::invalid("email_format", "invalid email format")
            }
        });

    let validator = SchemaValidator::custom(custom_schema);

    // Test with valid email
    let valid_yaml = r#"
email: "user@example.com"
"#;
    let valid_doc = create_test_document(valid_yaml);
    assert!(validator.validate(&valid_doc).is_ok());

    // Test with invalid email
    let invalid_yaml = r#"
email: "not-an-email"
"#;
    let invalid_doc = create_test_document(invalid_yaml);
    let result = validator.validate(&invalid_doc);
    assert!(result.is_err());

    let errors = result.unwrap_err();
    assert_eq!(errors.len(), 1);
    assert_eq!(
        errors[0].message(),
        "custom constraint 'email_format: invalid email format' failed for value 'not-an-email'"
    );
}

#[test]
fn custom_schema_integer_range() {
    // Custom schema with integer range validation
    let custom_schema = CustomSchema::new("port-validation")
        .allow_type(ScalarType::Integer)
        .with_validator(ScalarType::Integer, |value, _path| {
            if let Ok(port) = value.parse::<u16>() {
                if (1024..=65535).contains(&port) {
                    CustomValidationResult::Valid
                } else {
                    CustomValidationResult::invalid(
                        "port_range",
                        format!("port {} must be between 1024 and 65535", port),
                    )
                }
            } else {
                CustomValidationResult::invalid(
                    "integer_format",
                    format!("invalid integer: {}", value),
                )
            }
        });

    let validator = SchemaValidator::custom(custom_schema);

    // Test with valid port
    let valid_yaml = r#"
port: 8080
"#;
    let valid_doc = create_test_document(valid_yaml);
    assert!(validator.validate(&valid_doc).is_ok());

    // Test with invalid port (too low)
    let invalid_yaml = r#"
port: 80
"#;
    let invalid_doc = create_test_document(invalid_yaml);
    let result = validator.validate(&invalid_doc);
    assert!(result.is_err());

    let errors = result.unwrap_err();
    assert!(!errors.is_empty());
    assert_eq!(
            errors[0].message(),
            "custom constraint 'port_range: port 80 must be between 1024 and 65535' failed for value '80'"
        );
}

#[test]
fn custom_schema_multiple_validators() {
    // Schema with multiple type validators
    let custom_schema = CustomSchema::new("config-validation")
        .allow_types(&[ScalarType::String, ScalarType::Integer])
        .with_validator(ScalarType::String, |value, _path| {
            if value.len() >= 3 {
                CustomValidationResult::Valid
            } else {
                CustomValidationResult::invalid(
                    "string_length",
                    format!("string too short: '{}'", value),
                )
            }
        })
        .with_validator(ScalarType::Integer, |value, _path| {
            if let Ok(num) = value.parse::<i32>() {
                if num >= 0 {
                    CustomValidationResult::Valid
                } else {
                    CustomValidationResult::invalid(
                        "negative_number",
                        format!("negative numbers not allowed: {}", num),
                    )
                }
            } else {
                CustomValidationResult::invalid(
                    "integer_format",
                    format!("invalid integer: {}", value),
                )
            }
        });

    let validator = SchemaValidator::custom(custom_schema);

    // Test with valid values
    let valid_yaml = r#"
name: "valid-name"
count: 100
"#;
    let valid_doc = create_test_document(valid_yaml);
    assert!(validator.validate(&valid_doc).is_ok());

    // Test with invalid string (too short)
    let invalid_yaml = r#"
name: "ab"
count: 100
"#;
    let invalid_doc = create_test_document(invalid_yaml);
    let result = validator.validate(&invalid_doc);
    assert!(result.is_err());

    let errors = result.unwrap_err();
    assert_eq!(errors.len(), 1);
    assert_eq!(
        errors[0].message(),
        "custom constraint 'string_length: string too short: 'ab'' failed for value 'ab'"
    );
}

#[test]
fn custom_schema_strict_mode() {
    let custom_schema = CustomSchema::new("strict-test")
        .allow_type(ScalarType::String)
        .strict();

    let validator = SchemaValidator::custom(custom_schema);

    // Test that even valid integers are rejected in strict mode
    let yaml_with_int = r#"
value: 42
"#;
    let doc = create_test_document(yaml_with_int);
    let result = validator.validate(&doc);
    assert!(result.is_err());

    let errors = result.unwrap_err();
    assert_eq!(errors.len(), 1);
    assert_eq!(
        errors[0].message(),
        "type Integer not allowed in strict-test schema, expected one of [String]"
    );
}

#[test]
fn custom_schema_name() {
    let custom_schema = CustomSchema::new("my-custom-schema").allow_type(ScalarType::String);
    let schema = Schema::Custom(custom_schema);

    assert_eq!(schema.name(), "my-custom-schema");
}

#[test]
fn quoted_scalars_are_strings() {
    let document = create_test_document("a: \"123\"\nb: 'true'\nc: \"null\"\n");
    assert_eq!(
        SchemaValidator::failsafe().strict().validate(&document),
        Ok(())
    );
    assert_eq!(SchemaValidator::failsafe().can_coerce(&document), Ok(()));
}

#[test]
fn plain_base64_like_word_is_string() {
    let document = create_test_document("k: test\n");
    assert_eq!(SchemaValidator::json().strict().validate(&document), Ok(()));
    assert_eq!(
        SchemaValidator::failsafe().strict().validate(&document),
        Ok(())
    );
}

#[test]
fn quoted_date_is_string() {
    let document = create_test_document("k: \"2023-01-01\"\n");
    assert_eq!(SchemaValidator::json().strict().validate(&document), Ok(()));
}

#[test]
fn custom_schema_quoted_integer_is_string() {
    let custom_schema = CustomSchema::new("strings")
        .allow_type(ScalarType::String)
        .strict();
    let validator = SchemaValidator::custom(custom_schema);
    let document = create_test_document("k: \"123\"\n");
    assert_eq!(validator.validate(&document), Ok(()));
    let document = create_test_document("k: 123\n");
    assert_eq!(
        validator.validate(&document),
        Err(vec![ValidationError::type_not_allowed(
            "root.k",
            "strings",
            ScalarType::Integer,
            vec![ScalarType::String],
        )])
    );
}

#[test]
fn plain_integer_still_rejected_by_failsafe_strict() {
    let document = create_test_document("k: 123\n");
    assert_eq!(
        SchemaValidator::failsafe().strict().validate(&document),
        Err(vec![ValidationError::type_not_allowed(
            "root.k",
            "failsafe",
            ScalarType::Integer,
            vec![ScalarType::String],
        )])
    );
}

#[test]
fn verbatim_tags_validate_as_shorthand() {
    let validate = |yaml: &str| {
        SchemaValidator::json()
            .strict()
            .validate(&create_test_document(yaml))
    };
    let shorthand = validate("t: !!timestamp \"2023-12-25\"\nr: !!regex '\\d+'\n");
    assert_eq!(shorthand.as_ref().map_err(|e| e.len()), Err(2));
    assert_eq!(
            validate(
                "t: !<tag:yaml.org,2002:timestamp> \"2023-12-25\"\nr: !<tag:yaml.org,2002:regex> '\\d+'\n"
            ),
            shorthand,
        );
}

fn json_types() -> Vec<ScalarType> {
    Schema::Json.allowed_scalar_types()
}

#[test]
fn tagged_root_scalar_validated() {
    let document = create_test_document("--- !!timestamp 2001-01-01\n");
    let expected = Err(vec![ValidationError::type_not_allowed(
        "root",
        "json",
        ScalarType::Timestamp,
        json_types(),
    )]);
    assert_eq!(
        SchemaValidator::json().strict().validate(&document),
        expected
    );
    assert_eq!(SchemaValidator::json().can_coerce(&document), expected);
}

#[test]
fn core_tag_sets_scalar_type() {
    let document = create_test_document("a: !!int 5\n");
    let expected = Err(vec![ValidationError::type_not_allowed(
        "root.a",
        "failsafe",
        ScalarType::Integer,
        vec![ScalarType::String],
    )]);
    assert_eq!(
        SchemaValidator::failsafe().strict().validate(&document),
        expected
    );
    assert_eq!(SchemaValidator::failsafe().can_coerce(&document), expected);
    let document = create_test_document("a: !!str 5\n");
    assert_eq!(
        SchemaValidator::failsafe().strict().validate(&document),
        Ok(())
    );
}

#[test]
fn custom_schema_tagged_scalar_uses_content() {
    let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let seen_in = seen.clone();
    let custom_schema = CustomSchema::new("ints")
        .allow_type(ScalarType::Integer)
        .with_validator(ScalarType::Integer, move |value, path| {
            seen_in
                .lock()
                .unwrap()
                .push((value.to_string(), path.to_string()));
            CustomValidationResult::Valid
        })
        .strict();
    let validator = SchemaValidator::custom(custom_schema);
    let document = create_test_document("a: !!int 42\n");
    assert_eq!(validator.validate(&document), Ok(()));
    assert_eq!(
        *seen.lock().unwrap(),
        vec![("42".to_string(), "root.a".to_string())]
    );
}

#[test]
fn tagged_collection_contents_validated() {
    let document = create_test_document("a: !foo [x, !!timestamp 2001-01-01]\n");
    let expected = Err(vec![ValidationError::type_not_allowed(
        "root.a[1]",
        "json",
        ScalarType::Timestamp,
        json_types(),
    )]);
    assert_eq!(
        SchemaValidator::json().strict().validate(&document),
        expected
    );
    assert_eq!(SchemaValidator::json().can_coerce(&document), expected);
    let document = create_test_document("a: !foo {b: !!timestamp 2001-01-01}\n");
    assert_eq!(
        SchemaValidator::json().strict().validate(&document),
        Err(vec![ValidationError::type_not_allowed(
            "root.a.b",
            "json",
            ScalarType::Timestamp,
            json_types(),
        )])
    );
}

#[test]
fn coercion_failed_error() {
    let error = ValidationError::coercion_failed(
        "root.a",
        "bools",
        ScalarType::String,
        vec![ScalarType::Boolean],
    );
    assert_eq!(
        error.kind,
        ValidationErrorKind::CoercionFailed {
            from_type: ScalarType::String,
            to_types: vec![ScalarType::Boolean],
        }
    );
    assert_eq!(
        error.to_string(),
        "Validation error at root.a: cannot coerce String to any of [Boolean] in bools schema"
    );
}

#[test]
fn custom_constraint_failed_display() {
    let error = ValidationError::custom_constraint_failed("root.p", "ports", "range", "80");
    assert_eq!(
        error.to_string(),
        "Validation error at root.p: custom constraint 'range' failed for value '80'"
    );
}

#[test]
fn custom_validation_result_predicates() {
    assert!(CustomValidationResult::Valid.is_valid());
    assert!(!CustomValidationResult::Valid.is_invalid());
    let invalid = CustomValidationResult::invalid("c", "r");
    assert!(!invalid.is_valid());
    assert!(invalid.is_invalid());
    assert_eq!(
        invalid,
        CustomValidationResult::Invalid {
            constraint: "c".to_string(),
            reason: "r".to_string(),
        }
    );
}

#[test]
fn custom_schema_debug() {
    let schema = CustomSchema::new("dbg")
        .allow_types(&[ScalarType::String, ScalarType::String, ScalarType::Integer])
        .allow_type(ScalarType::Integer)
        .with_validator(ScalarType::String, |_, _| CustomValidationResult::Valid)
        .strict();
    assert_eq!(
            format!("{schema:?}"),
            "CustomSchema { name: \"dbg\", allowed_types: [String, Integer], allow_coercion: false, validators: \"<1 validators>\" }"
        );
}

#[test]
fn custom_schema_equality_and_types() {
    let a = Schema::Custom(CustomSchema::new("same").allow_type(ScalarType::String));
    let b = Schema::Custom(CustomSchema::new("same").allow_type(ScalarType::Integer));
    let c = Schema::Custom(CustomSchema::new("other"));
    assert_eq!(a, b);
    assert_ne!(a, c);
    assert_ne!(a, Schema::Core);
    assert_eq!(b.allowed_scalar_types(), vec![ScalarType::Integer]);
    assert!(b.allows_scalar_type(ScalarType::Integer));
    assert!(!b.allows_scalar_type(ScalarType::String));
}

#[test]
fn custom_schema_validate_scalar() {
    let schema = CustomSchema::new("ints")
        .allow_type(ScalarType::Integer)
        .strict();
    assert_eq!(schema.validate_scalar(" 42 ", "p"), Ok(()));
    assert_eq!(
        schema.validate_scalar("true", "p"),
        Err(ValidationError::type_not_allowed(
            "p",
            "ints",
            ScalarType::Boolean,
            vec![ScalarType::Integer],
        ))
    );
}

#[test]
fn custom_schema_coercion() {
    let validator =
        SchemaValidator::custom(CustomSchema::new("bools").allow_type(ScalarType::Boolean));
    assert_eq!(
        validator.validate(&create_test_document("a: yes\nb: 0\n")),
        Ok(())
    );
    let document = create_test_document("a: hello\n");
    let expected = Err(vec![ValidationError::coercion_failed(
        "root.a",
        "bools",
        ScalarType::String,
        vec![ScalarType::Boolean],
    )]);
    assert_eq!(validator.validate(&document), expected);
    assert_eq!(validator.can_coerce(&document), expected);
}

#[test]
fn custom_schema_can_coerce_skips_validators() {
    let validator = SchemaValidator::custom(
        CustomSchema::new("never")
            .allow_type(ScalarType::String)
            .with_validator(ScalarType::String, |_, _| {
                CustomValidationResult::invalid("never", "always fails")
            })
            .strict(),
    );
    let document = create_test_document("a: 42\n");
    assert_eq!(
        validator.validate(&document),
        Err(vec![ValidationError::type_not_allowed(
            "root.a",
            "never",
            ScalarType::Integer,
            vec![ScalarType::String],
        )])
    );
    assert_eq!(validator.can_coerce(&document), Ok(()));
    let document = create_test_document("a: x\n");
    assert_eq!(
        validator.validate(&document),
        Err(vec![ValidationError::custom_constraint_failed(
            "root.a",
            "never",
            "never: always fails",
            "x",
        )])
    );
    assert_eq!(validator.can_coerce(&document), Ok(()));
}

#[test]
fn custom_schema_can_coerce_tagged() {
    let validator =
        SchemaValidator::custom(CustomSchema::new("strings").allow_type(ScalarType::String));
    let document = create_test_document("a: !!timestamp 2001-01-01\n");
    assert_eq!(
        validator.can_coerce(&document),
        Err(vec![ValidationError::type_not_allowed(
            "root.a",
            "strings",
            ScalarType::Timestamp,
            vec![ScalarType::String],
        )])
    );
}

#[test]
fn root_scalar_and_sequence_paths() {
    let failsafe = SchemaValidator::failsafe().strict();
    let int_error = |path: &str| {
        ValidationError::type_not_allowed(
            path,
            "failsafe",
            ScalarType::Integer,
            vec![ScalarType::String],
        )
    };
    assert_eq!(
        failsafe.validate(&create_test_document("5\n")),
        Err(vec![int_error("root")])
    );
    assert_eq!(
        failsafe.validate(&create_test_document("- x\n- 1\n- [2]\n")),
        Err(vec![int_error("root[1]"), int_error("root[2][0]")])
    );
    assert_eq!(
        failsafe.can_coerce(&create_test_document("- x\n- {a: 1}\n")),
        Err(vec![int_error("root[1].a")])
    );
}

#[test]
fn standard_schema_coerces_untagged_scalars() {
    let document = create_test_document("a: 1\nb: [true, ~]\nc: {d: 2001-01-01}\n");
    assert_eq!(SchemaValidator::failsafe().validate(&document), Ok(()));
    assert_eq!(SchemaValidator::failsafe().can_coerce(&document), Ok(()));
    let document = create_test_document("a: [!!timestamp 2001-01-01]\nb: {c: !!regex x}\n");
    assert_eq!(
        SchemaValidator::json().can_coerce(&document),
        Err(vec![
            ValidationError::type_not_allowed(
                "root.a[0]",
                "json",
                ScalarType::Timestamp,
                json_types(),
            ),
            ValidationError::type_not_allowed("root.b.c", "json", ScalarType::Regex, json_types(),),
        ])
    );
}

#[test]
#[cfg(feature = "base64")]
fn binary_tag() {
    let document = create_test_document("a: !!binary aGk=\n");
    assert_eq!(
        SchemaValidator::json().validate(&document),
        Err(vec![ValidationError::type_not_allowed(
            "root.a",
            "json",
            ScalarType::Binary,
            json_types(),
        )])
    );
    assert_eq!(SchemaValidator::core().validate(&document), Ok(()));
}

#[test]
fn custom_schema_tagged_scalar_has_tagged_type() {
    let validator = SchemaValidator::custom(
        CustomSchema::new("ints")
            .allow_type(ScalarType::Integer)
            .strict(),
    );
    assert_eq!(
        validator.validate(&create_test_document("k: !!int 5\n")),
        Ok(())
    );
    assert_eq!(
        validator.validate(&create_test_document("k: !!str 5\n")),
        Err(vec![ValidationError::type_not_allowed(
            "root.k",
            "ints",
            ScalarType::String,
            vec![ScalarType::Integer],
        )])
    );
}

#[test]
fn custom_validator_gets_tagged_scalar_content() {
    let validator = SchemaValidator::custom(
        CustomSchema::new("dates")
            .allow_type(ScalarType::Timestamp)
            .with_validator(ScalarType::Timestamp, |value, _| {
                if value == "2001-12-14" {
                    CustomValidationResult::Valid
                } else {
                    CustomValidationResult::invalid("date", value)
                }
            }),
    );
    let document = create_test_document("k: !!timestamp 2001-12-14\n");
    assert_eq!(validator.validate(&document), Ok(()));
}

#[test]
fn failsafe_strict_rejects_tagged_integer() {
    let document = create_test_document("k: !!int 123\n");
    assert_eq!(
        SchemaValidator::failsafe().strict().validate(&document),
        Err(vec![ValidationError::type_not_allowed(
            "root.k",
            "failsafe",
            ScalarType::Integer,
            vec![ScalarType::String],
        )])
    );
}

#[test]
fn tagged_collection_contents_are_validated() {
    let validator = SchemaValidator::failsafe().strict();
    let expected = |path: &str| {
        Err(vec![ValidationError::type_not_allowed(
            path,
            "failsafe",
            ScalarType::Integer,
            vec![ScalarType::String],
        )])
    };
    assert_eq!(
        validator.validate(&create_test_document("k: !!map {a: 1}\n")),
        expected("root.k.a")
    );
    assert_eq!(
        validator.validate(&create_test_document("k: !!seq [1]\n")),
        expected("root.k[0]")
    );
}

#[test]
fn json_validation_with_yaml_specific_types() {
    let yaml_str = r#"
timestamp: !!timestamp "2023-12-25T10:30:45Z"
pattern: !!regex '\d+'
"#;
    let document = create_test_document(yaml_str);
    let validator = SchemaValidator::json().strict();
    let json_types = vec![
        ScalarType::String,
        ScalarType::Integer,
        ScalarType::Float,
        ScalarType::Boolean,
        ScalarType::Null,
    ];
    assert_eq!(
        validator.validate(&document),
        Err(vec![
            ValidationError::type_not_allowed(
                "root.timestamp",
                "json",
                ScalarType::Timestamp,
                json_types.clone()
            ),
            ValidationError::type_not_allowed(
                "root.pattern",
                "json",
                ScalarType::Regex,
                json_types
            ),
        ])
    );
}

#[test]
fn strict_mode_validation() {
    let yaml_str = r#"
count: 42
active: true
"#;
    let document = create_test_document(yaml_str);

    // Non-strict failsafe passes via coercion, strict does not allow
    // integers and booleans.
    let validator = SchemaValidator::failsafe();
    assert!(validator.can_coerce(&document).is_ok());
    let strict_validator = SchemaValidator::failsafe().strict();
    assert_eq!(
        strict_validator.validate(&document),
        Err(vec![
            ValidationError::type_not_allowed(
                "root.count",
                "failsafe",
                ScalarType::Integer,
                vec![ScalarType::String]
            ),
            ValidationError::type_not_allowed(
                "root.active",
                "failsafe",
                ScalarType::Boolean,
                vec![ScalarType::String]
            ),
        ])
    );

    let string_yaml = r#"
name: hello
message: world
"#;
    let string_document = create_test_document(string_yaml);
    assert_eq!(validator.validate(&string_document), Ok(()));
    assert_eq!(strict_validator.validate(&string_document), Ok(()));
}

/// A type the schema does not allow, at `path`.
fn not_allowed(path: &str, schema: &str, found_type: ScalarType) -> ValidationError {
    let allowed = match schema {
        "failsafe" => vec![ScalarType::String],
        _ => json_types(),
    };
    ValidationError::type_not_allowed(path, schema, found_type, allowed)
}

/// What `schema` reports for a `!!binary` scalar at `path`. Without the
/// base64 feature there is no binary type, and the scalar is a string.
#[cfg(feature = "base64")]
fn binary_not_allowed(path: &str, schema: &str) -> Vec<ValidationError> {
    vec![not_allowed(path, schema, ScalarType::Binary)]
}

#[cfg(not(feature = "base64"))]
fn binary_not_allowed(_path: &str, _schema: &str) -> Vec<ValidationError> {
    vec![]
}

/// What each schema reports through `Document::validate_schema`, with the
/// path of every value it does not allow.
#[test]
fn document_validate_schema() {
    use ScalarType::*;
    let json_compatible = r#"
name: "John"
age: 30
active: true
items:
  - "apple"
  - 42
  - true
"#;
    let yaml_specific = r#"
name: "Test"
created: 2023-12-25T10:30:45Z
pattern: !!regex '\d+'
data: !!binary "SGVsbG8="
"#;
    let string_only = r#"
name: hello
message: world
items:
  - apple
  - banana
nested:
  key: value
"#;
    let nested = r#"
users:
  - name: "Alice"
    age: 25
    metadata:
      created: !!timestamp "2023-01-01"
      active: true
  - name: "Bob"
    score: 95.5
"#;
    let scalars = r#"
name: "HelloWorld"
count: 42
active: true
"#;
    let validators = [
        ("json", SchemaValidator::json()),
        ("core", SchemaValidator::core()),
        ("failsafe", SchemaValidator::failsafe()),
        ("strict failsafe", SchemaValidator::failsafe().strict()),
        ("strict json", SchemaValidator::json().strict()),
    ];
    for (yaml, expected) in [
        (
            json_compatible,
            [
                vec![],
                vec![],
                vec![],
                vec![
                    not_allowed("root.age", "failsafe", Integer),
                    not_allowed("root.active", "failsafe", Boolean),
                    not_allowed("root.items[1]", "failsafe", Integer),
                    not_allowed("root.items[2]", "failsafe", Boolean),
                ],
                vec![],
            ],
        ),
        (
            yaml_specific,
            [
                [
                    vec![not_allowed("root.pattern", "json", Regex)],
                    binary_not_allowed("root.data", "json"),
                ]
                .concat(),
                vec![],
                [
                    vec![not_allowed("root.pattern", "failsafe", Regex)],
                    binary_not_allowed("root.data", "failsafe"),
                ]
                .concat(),
                [
                    vec![not_allowed("root.pattern", "failsafe", Regex)],
                    binary_not_allowed("root.data", "failsafe"),
                ]
                .concat(),
                [
                    vec![not_allowed("root.pattern", "json", Regex)],
                    binary_not_allowed("root.data", "json"),
                ]
                .concat(),
            ],
        ),
        (string_only, [vec![], vec![], vec![], vec![], vec![]]),
        (
            nested,
            [
                vec![not_allowed(
                    "root.users[0].metadata.created",
                    "json",
                    Timestamp,
                )],
                vec![],
                vec![not_allowed(
                    "root.users[0].metadata.created",
                    "failsafe",
                    Timestamp,
                )],
                vec![
                    not_allowed("root.users[0].age", "failsafe", Integer),
                    not_allowed("root.users[0].metadata.created", "failsafe", Timestamp),
                    not_allowed("root.users[0].metadata.active", "failsafe", Boolean),
                    not_allowed("root.users[1].score", "failsafe", Float),
                ],
                vec![not_allowed(
                    "root.users[0].metadata.created",
                    "json",
                    Timestamp,
                )],
            ],
        ),
        (
            scalars,
            [
                vec![],
                vec![],
                vec![],
                vec![
                    not_allowed("root.count", "failsafe", Integer),
                    not_allowed("root.active", "failsafe", Boolean),
                ],
                vec![],
            ],
        ),
    ] {
        let doc = create_test_document(yaml);
        for ((name, validator), errors) in validators.iter().zip(expected) {
            let expected = if errors.is_empty() {
                Ok(())
            } else {
                Err(errors)
            };
            assert_eq!(validator.validate(&doc), expected, "{name} on {yaml:?}");
            assert_eq!(
                doc.validate_schema(validator),
                expected,
                "{name} on {yaml:?}"
            );
        }
    }
}

#[test]
fn document_can_coerce() {
    let coercible = r#"
count: "42"
enabled: "true"
rate: "3.14"
items:
  - "100"
  - "false"
"#;
    let non_coercible = r#"
timestamp: !!timestamp "2023-01-01"
pattern: !!regex '\d+'
"#;
    let json_validator = SchemaValidator::json();
    assert_eq!(
        json_validator.can_coerce(&create_test_document(coercible)),
        Ok(())
    );
    assert_eq!(
        json_validator.can_coerce(&create_test_document(non_coercible)),
        Err(vec![
            not_allowed("root.timestamp", "json", ScalarType::Timestamp),
            not_allowed("root.pattern", "json", ScalarType::Regex),
        ])
    );
}