-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathtest_processor.py
2146 lines (1959 loc) · 69.1 KB
/
test_processor.py
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
import pytest
from datetime import date, datetime
from types import SimpleNamespace
from collections import OrderedDict
from ruamel.yaml import YAML
from ruamel.yaml.comments import TaggedScalar
from yamlpath.patches.timestamp import (
AnchoredTimeStamp,
AnchoredDate,
)
from yamlpath.func import unwrap_node_coords
from yamlpath.exceptions import YAMLPathException
from yamlpath.enums import (
PathSeparators,
PathSegmentTypes,
PathSearchMethods,
YAMLValueFormats,
)
from yamlpath.path import SearchTerms
from yamlpath.wrappers import ConsolePrinter
from yamlpath import YAMLPath, Processor
class Test_Processor():
"""Tests for the Processor class."""
def test_get_none_data_nodes(self, quiet_logger):
processor = Processor(quiet_logger, None)
yamlpath = YAMLPath("abc")
optional_matches = 0
must_exist_matches = 0
req_node_matches = 0
traversal_matches = 0
for node in processor.get_nodes(yamlpath, mustexist=False):
optional_matches += 1
for node in processor.get_nodes(yamlpath, mustexist=True):
must_exist_matches += 1
for node in processor._get_required_nodes(None, yamlpath):
req_node_matches += 1
for node in processor._get_nodes_by_traversal(None, yamlpath, 0):
traversal_matches += 1
assert optional_matches == 0
assert must_exist_matches == 0
assert req_node_matches == 0
assert traversal_matches == 1 # A None node traverses into null
@pytest.mark.parametrize("yamlpath,results,mustexist,default", [
("aliases[&aliasAnchorOne]", ["Anchored Scalar Value"], True, None),
("aliases[&newAlias]", ["Not in the original data"], False, "Not in the original data"),
("aliases[0]", ["Anchored Scalar Value"], True, None),
("aliases.0", ["Anchored Scalar Value"], True, None),
("(array_of_hashes.name)+(rollback_hashes.on_condition.failure.name)", [["one", "two", "three", "four"]], True, None),
("/array_of_hashes/name", ["one", "two"], True, None),
("aliases[1:2]", [["Hey, Number Two!"]], True, None),
("aliases[1:1]", [["Hey, Number Two!"]], True, None),
("squads[bravo:charlie]", [2.2, 3.3], True, None),
("/&arrayOfHashes/1/step", [2], True, None),
("&arrayOfHashes[step=1].name", ["one"], True, None),
("squads[.!=""][.=1.1]", [1.1], True, None),
("squads[.!=""][.>1.1][.<3.3]", [2.2], True, None),
("aliases[.^Hey]", ["Hey, Number Two!"], True, None),
("aliases[.$Value]", ["Anchored Scalar Value"], True, None),
("aliases[.%Value]", ["Anchored Scalar Value"], True, None),
("&arrayOfHashes[step>1].name", ["two"], True, None),
("&arrayOfHashes[step<2].name", ["one"], True, None),
("squads[.>charlie]", [4.4], True, None),
("squads[.>=charlie]", [3.3, 4.4], True, None),
("squads[.<bravo]", [1.1], True, None),
("squads[.<=bravo]", [1.1, 2.2], True, None),
(r"squads[.=~/^\w{6,}$/]", [3.3], True, None),
("squads[alpha=1.1]", [1.1], True, None),
("(&arrayOfHashes.step)+(/rollback_hashes/on_condition/failure/step)-(disabled_steps)", [[1, 4]], True, None),
("(&arrayOfHashes.step)+((/rollback_hashes/on_condition/failure/step)-(disabled_steps))", [[1, 2, 4]], True, None),
("(disabled_steps)+(&arrayOfHashes.step)", [[2, 3, 1, 2]], True, None),
("(&arrayOfHashes.step)+(disabled_steps)[1]", [2], True, None),
("((&arrayOfHashes.step)[1])[0]", [2], True, None),
("does.not.previously.exist[7]", ["Huzzah!"], False, "Huzzah!"),
("/number_keys/1", ["one"], True, None),
("**.[.^Hey]", ["Hey, Number Two!"], True, None),
("/**/Hey*", ["Hey, Number Two!"], True, None),
("lots_of_names.**.name", ["Name 1-1", "Name 2-1", "Name 3-1", "Name 4-1", "Name 4-2", "Name 4-3", "Name 4-4"], True, None),
("/array_of_hashes/**", [1, "one", 2, "two"], True, None),
("products_hash.*[dimensions.weight==4].(availability.start.date)+(availability.stop.date)", [[AnchoredDate(2020, 8, 1), AnchoredDate(2020, 9, 25)], [AnchoredDate(2020, 1, 1), AnchoredDate(2020, 1, 1)]], True, None),
("products_array[dimensions.weight==4].product", ["doohickey", "widget"], True, None),
("(products_hash.*.dimensions.weight)[max()][parent(2)].dimensions.weight", [10], True, None),
("/Locations/*/*", ["ny", "bstn"], True, None),
("/AoH_Locations/*/*/*", ["nyc", "bo"], True, None),
("/Weird_AoH_Locations/*/*/*", ["nyc", "bstn"], True, None),
("/Set_Locations/*/*", ["New York", "Boston"], True, None),
])
def test_get_nodes(self, quiet_logger, yamlpath, results, mustexist, default):
yamldata = """---
aliases:
- &aliasAnchorOne Anchored Scalar Value
- &aliasAnchorTwo Hey, Number Two!
array_of_hashes: &arrayOfHashes
- step: 1
name: one
- step: 2
name: two
rollback_hashes:
on_condition:
failure:
- step: 3
name: three
- step: 4
name: four
disabled_steps:
- 2
- 3
squads:
alpha: 1.1
bravo: 2.2
charlie: 3.3
delta: 4.4
number_keys:
1: one
2: two
3: three
# For traversal tests:
name: Name 0-0
lots_of_names:
name: Name 1-1
tier1:
name: Name 2-1
tier2:
name: Name 3-1
list_of_named_objects:
- name: Name 4-1
tag: Tag 4-1
other: Other 4-1
dude: Dude 4-1
- tag: Tag 4-2
name: Name 4-2
dude: Dude 4-2
other: Other 4-2
- other: Other 4-3
dude: Dude 4-3
tag: Tag 4-3
name: Name 4-3
- dude: Dude 4-4
tag: Tag 4-4
name: Name 4-4
other: Other 4-4
###############################################################################
# For descendent searching:
products_hash:
doodad:
availability:
start:
date: 2020-10-10
time: 08:00
stop:
date: 2020-10-29
time: 17:00
dimensions:
width: 5
height: 5
depth: 5
weight: 10
doohickey:
availability:
start:
date: 2020-08-01
time: 10:00
stop:
date: 2020-09-25
time: 10:00
dimensions:
width: 1
height: 2
depth: 3
weight: 4
widget:
availability:
start:
date: 2020-01-01
time: 12:00
stop:
date: 2020-01-01
time: 16:00
dimensions:
width: 9
height: 10
depth: 1
weight: 4
products_array:
- product: doodad
availability:
start:
date: 2020-10-10
time: 08:00
stop:
date: 2020-10-29
time: 17:00
dimensions:
width: 5
height: 5
depth: 5
weight: 10
- product: doohickey
availability:
start:
date: 2020-08-01
time: 10:00
stop:
date: 2020-09-25
time: 10:00
dimensions:
width: 1
height: 2
depth: 3
weight: 4
- product: widget
availability:
start:
date: 2020-01-01
time: 12:00
stop:
date: 2020-01-01
time: 16:00
dimensions:
width: 9
height: 10
depth: 1
weight: 4
###############################################################################
# For wildcard matching (#154)
Locations:
United States:
New York: ny
Boston: bstn
Canada: cnd
AoH_Locations:
- United States: us
New York:
New York City: nyc
Massachussets:
Boston: bo
- Canada: ca
# Weird Array-of-Hashes
Weird_AoH_Locations:
- United States:
New York: nyc
Boston: bstn
- Canada: cnd
Set_Locations:
United States: !!set
? New York
? Boston
Canada:
"""
yaml = YAML()
processor = Processor(quiet_logger, yaml.load(yamldata))
matchidx = 0
for node in processor.get_nodes(
yamlpath, mustexist=mustexist, default_value=default
):
assert unwrap_node_coords(node) == results[matchidx]
matchidx += 1
assert len(results) == matchidx
@pytest.mark.parametrize("mustexist,yamlpath,results,yp_error", [
(True, "baseball_legends", [set(['Mark McGwire', 'Sammy Sosa', 'Ty Cobb', 'Ken Griff'])], None),
(True, "baseball_legends.*bb", ["Ty Cobb"], None),
(True, "baseball_legends[A:S]", ["Mark McGwire", "Ken Griff"], None),
(True, "baseball_legends[2]", [], "Array indexing is invalid against unordered set"),
(True, "baseball_legends[&bl_anchor]", ["Ty Cobb"], None),
(True, "baseball_legends([A:M])+([T:Z])", [["Ken Griff", "Ty Cobb"]], None),
(True, "baseball_legends([A:Z])-([S:Z])", [["Mark McGwire", "Ken Griff"]], None),
(True, "**", ["Ty Cobb", "Mark McGwire", "Sammy Sosa", "Ty Cobb", "Ken Griff"], None),
(False, "baseball_legends", [set(['Mark McGwire', 'Sammy Sosa', 'Ty Cobb', 'Ken Griff'])], None),
(False, "baseball_legends.*bb", ["Ty Cobb"], None),
(False, "baseball_legends[A:S]", ["Mark McGwire", "Ken Griff"], None),
(False, "baseball_legends[2]", [], "Array indexing is invalid against unordered set"),
(False, "baseball_legends[&bl_anchor]", ["Ty Cobb"], None),
(False, "baseball_legends([A:M])+([T:Z])", [["Ken Griff", "Ty Cobb"]], None),
(False, "baseball_legends([A:Z])-([S:Z])", [["Mark McGwire", "Ken Griff"]], None),
(False, "**", ["Ty Cobb", "Mark McGwire", "Sammy Sosa", "Ty Cobb", "Ken Griff"], None),
(False, "baseball_legends(rbi)+(errate)", [], "Cannot add PathSegmentTypes.COLLECTOR subreference to sets"),
(False, r"baseball_legends.Ted\ Williams", [set(['Mark McGwire', 'Sammy Sosa', 'Ty Cobb', 'Ken Griff', "Ted Williams"])], None),
])
def test_get_from_sets(self, quiet_logger, mustexist, yamlpath, results, yp_error):
yamldata = """---
aliases:
- &bl_anchor Ty Cobb
baseball_legends: !!set
? Mark McGwire
? Sammy Sosa
? *bl_anchor
? Ken Griff
"""
yaml = YAML()
processor = Processor(quiet_logger, yaml.load(yamldata))
matchidx = 0
try:
for node in processor.get_nodes(yamlpath, mustexist=mustexist):
assert unwrap_node_coords(node) == results[matchidx]
matchidx += 1
except YAMLPathException as ex:
if yp_error is not None:
assert yp_error in str(ex)
else:
# Unexpected error
assert False
assert len(results) == matchidx
@pytest.mark.parametrize("setpath,value,verifypath,tally", [
("aliases[&bl_anchor]", "REPLACEMENT", "**.&bl_anchor", 2),
(r"baseball_legends.Sammy\ Sosa", "REPLACEMENT", "baseball_legends.REPLACEMENT", 1),
])
def test_change_values_in_sets(self, quiet_logger, setpath, value, verifypath, tally):
yamldata = """---
aliases:
- &bl_anchor Ty Cobb
baseball_legends: !!set
? Mark McGwire
? Sammy Sosa
? *bl_anchor
? Ken Griff
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
processor.set_value(setpath, value)
matchtally = 0
for node in processor.get_nodes(verifypath):
changed_value = unwrap_node_coords(node)
if isinstance(changed_value, list):
for result in changed_value:
assert result == value
matchtally += 1
continue
assert changed_value == value
matchtally += 1
assert matchtally == tally
@pytest.mark.parametrize("delete_yamlpath,old_deleted_nodes,new_flat_data", [
("**[&bl_anchor]", ["Ty Cobb", "Ty Cobb"], ["Mark McGwire", "Sammy Sosa", "Ken Griff"]),
(r"/baseball_legends/Ken\ Griff", ["Ken Griff"], ["Ty Cobb", "Mark McGwire", "Sammy Sosa", "Ty Cobb"]),
])
def test_delete_from_sets(self, quiet_logger, delete_yamlpath, old_deleted_nodes, new_flat_data):
yamldata = """---
aliases:
- &bl_anchor Ty Cobb
baseball_legends: !!set
? Mark McGwire
? Sammy Sosa
? *bl_anchor
? Ken Griff
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
# The return set must be received lest no nodes will be deleted
deleted_nodes = []
for nc in processor.delete_nodes(delete_yamlpath):
deleted_nodes.append(nc)
for (test_value, verify_node_coord) in zip(old_deleted_nodes, deleted_nodes):
assert test_value, unwrap_node_coords(verify_node_coord)
for (test_value, verify_node_coord) in zip(new_flat_data, processor.get_nodes("**")):
assert test_value, unwrap_node_coords(verify_node_coord)
def test_enforce_pathsep(self, quiet_logger):
yamldata = """---
aliases:
- &aliasAnchorOne Anchored Scalar Value
"""
yaml = YAML()
processor = Processor(quiet_logger, yaml.load(yamldata))
yamlpath = YAMLPath("aliases[&aliasAnchorOne]")
for node in processor.get_nodes(yamlpath, pathsep=PathSeparators.FSLASH):
assert unwrap_node_coords(node) == "Anchored Scalar Value"
@pytest.mark.parametrize("yamlpath,mustexist", [
("abc", True),
("/ints/[.=4F]", True),
("/ints/[.>4F]", True),
("/ints/[.<4F]", True),
("/ints/[.>=4F]", True),
("/ints/[.<=4F]", True),
("/floats/[.=4.F]", True),
("/floats/[.>4.F]", True),
("/floats/[.<4.F]", True),
("/floats/[.>=4.F]", True),
("/floats/[.<=4.F]", True),
("abc.**", True),
])
def test_get_impossible_nodes_error(self, quiet_logger, yamlpath, mustexist):
yamldata = """---
ints:
- 1
- 2
- 3
- 4
- 5
floats:
- 1.1
- 2.2
- 3.3
"""
yaml = YAML()
processor = Processor(quiet_logger, yaml.load(yamldata))
with pytest.raises(YAMLPathException) as ex:
nodes = list(processor.get_nodes(yamlpath, mustexist=mustexist))
assert -1 < str(ex.value).find("does not match any nodes")
def test_illegal_traversal_recursion(self, quiet_logger):
yamldata = """---
any: data
"""
yaml = YAML()
processor = Processor(quiet_logger, yaml.load(yamldata))
with pytest.raises(YAMLPathException) as ex:
nodes = list(processor.get_nodes("**.**"))
assert -1 < str(ex.value).find("Repeating traversals are not allowed")
def test_set_value_in_empty_data(self, capsys, quiet_logger):
import sys
yamldata = ""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
processor.set_value("abc", "void")
yaml.dump(data, sys.stdout)
assert -1 == capsys.readouterr().out.find("abc")
def test_set_value_in_none_data(self, capsys, quiet_logger):
import sys
yaml = YAML()
data = None
processor = Processor(quiet_logger, data)
processor._update_node(None, None, None, YAMLValueFormats.DEFAULT)
yaml.dump(data, sys.stdout)
assert -1 == capsys.readouterr().out.find("abc")
@pytest.mark.parametrize("yamlpath,value,tally,mustexist,vformat,pathsep", [
("aliases[&testAnchor]", "Updated Value", 1, True, YAMLValueFormats.DEFAULT, PathSeparators.AUTO),
(YAMLPath("top_scalar"), "New top-level value", 1, False, YAMLValueFormats.DEFAULT, PathSeparators.DOT),
("/top_array/2", 42, 1, False, YAMLValueFormats.INT, PathSeparators.FSLASH),
("/top_hash/positive_float", 0.009, 1, True, YAMLValueFormats.FLOAT, PathSeparators.FSLASH),
("/top_hash/negative_float", -0.009, 1, True, YAMLValueFormats.FLOAT, PathSeparators.FSLASH),
("/top_hash/positive_float", -2.71828, 1, True, YAMLValueFormats.FLOAT, PathSeparators.FSLASH),
("/top_hash/negative_float", 5283.4, 1, True, YAMLValueFormats.FLOAT, PathSeparators.FSLASH),
("/null_value", "No longer null", 1, True, YAMLValueFormats.DEFAULT, PathSeparators.FSLASH),
("(top_array[0])+(top_hash.negative_float)+(/null_value)", "REPLACEMENT", 3, True, YAMLValueFormats.DEFAULT, PathSeparators.FSLASH),
("(((top_array[0])+(top_hash.negative_float))+(/null_value))", "REPLACEMENT", 3, False, YAMLValueFormats.DEFAULT, PathSeparators.FSLASH),
])
def test_set_value(self, quiet_logger, yamlpath, value, tally, mustexist, vformat, pathsep):
yamldata = """---
aliases:
- &testAnchor Initial Value
top_array:
# Comment 1
- 1
# Comment 2
- 2
# Comment N
top_scalar: Top-level plain scalar string
top_hash:
positive_float: 3.14159265358
negative_float: -11.034
null_value:
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
processor.set_value(yamlpath, value, mustexist=mustexist, value_format=vformat, pathsep=pathsep)
matchtally = 0
for node in processor.get_nodes(yamlpath, mustexist=mustexist):
changed_value = unwrap_node_coords(node)
if isinstance(changed_value, list):
for result in changed_value:
assert result == value
matchtally += 1
continue
assert changed_value == value
matchtally += 1
assert matchtally == tally
@pytest.mark.parametrize("yamlpath,value,compare,tally,mustexist,vformat,pathsep", [
("/datetimes/date",
date(2022, 8, 2),
AnchoredDate(2022, 8, 2),
1,
True,
YAMLValueFormats.DATE,
PathSeparators.FSLASH,
),
("datetimes.date",
'2022-08-02',
AnchoredDate(2022, 8, 2),
1,
True,
YAMLValueFormats.DATE,
PathSeparators.DOT,
),
("datetimes.timestamp",
datetime(2022, 8, 2, 13, 22, 31),
AnchoredTimeStamp(2022, 8, 2, 13, 22, 31),
1,
True,
YAMLValueFormats.TIMESTAMP,
PathSeparators.DOT,
),
("/datetimes/timestamp",
'2022-08-02T13:22:31',
AnchoredTimeStamp(2022, 8, 2, 13, 22, 31),
1,
True,
YAMLValueFormats.TIMESTAMP,
PathSeparators.FSLASH,
),
("aliases[&date]",
'2022-08-02',
AnchoredDate(2022, 8, 2),
1,
True,
YAMLValueFormats.DATE,
PathSeparators.DOT,
),
("aliases[×tamp]",
datetime(2022, 8, 2, 13, 22, 31),
AnchoredTimeStamp(2022, 8, 2, 13, 22, 31),
1,
True,
YAMLValueFormats.TIMESTAMP,
PathSeparators.DOT,
),
])
def test_set_datetimes(self, quiet_logger, yamlpath, value, compare, tally, mustexist, vformat, pathsep):
yamldata = """---
aliases:
- &date 2022-02-21
- ×tamp 2022-11-20T15:14:13
datetimes:
date: 2022-09-23
timestamp: 2022-09-24T01:02:03.04000
reused:
date: *date
timestamp: *timestamp
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
processor.set_value(yamlpath, value, mustexist=mustexist, value_format=vformat, pathsep=pathsep)
matchtally = 0
for node in processor.get_nodes(yamlpath, mustexist=mustexist):
changed_value = unwrap_node_coords(node)
if isinstance(changed_value, list):
compare_idx = 0
for result in changed_value:
assert result == compare[compare_idx]
compare_idx += 1
matchtally += 1
continue
assert changed_value == compare
matchtally += 1
assert matchtally == tally
@pytest.mark.parametrize("yamlpath,value,vformat,exmsg", [
("/datetimes/date",
"2022.9.24",
YAMLValueFormats.DATE,
"not a YAML-compatible ISO8601 date"
),
("/datetimes/date",
"2022-90-24",
YAMLValueFormats.DATE,
"cannot be cast to an ISO8601 date"
),
("/datetimes/timestamp",
"2022-9-24 @ 7:41am",
YAMLValueFormats.TIMESTAMP,
"not a YAML-compatible ISO8601 timestamp"
),
("/datetimes/timestamp",
"2022-90-24T07:41:00",
YAMLValueFormats.TIMESTAMP,
"cannot be cast to an ISO8601 timestamp"
),
])
def test_cannot_set_impossible_datetimes(self, quiet_logger, yamlpath, value, vformat, exmsg):
yamldata = """---
datetimes:
date: 2022-09-23
timestamp: 2022-09-24T01:02:03.04000
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
with pytest.raises(YAMLPathException) as ex:
processor.set_value(yamlpath, value, value_format=vformat)
assert -1 < str(ex.value).find(exmsg)
def test_cannot_set_nonexistent_required_node_error(self, quiet_logger):
yamldata = """---
key: value
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
with pytest.raises(YAMLPathException) as ex:
processor.set_value("abc", "void", mustexist=True)
assert -1 < str(ex.value).find("No nodes matched")
def test_none_data_to_get_nodes_by_path_segment(self, capsys, quiet_logger):
import sys
yamldata = ""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
nodes = list(processor._get_nodes_by_path_segment(data, YAMLPath("abc"), 0))
yaml.dump(data, sys.stdout)
assert -1 == capsys.readouterr().out.find("abc")
def test_bad_segment_index_for_get_nodes_by_path_segment(self, capsys, quiet_logger):
import sys
yamldata = """---
key: value
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
nodes = list(processor._get_nodes_by_path_segment(data, YAMLPath("abc"), 10))
yaml.dump(data, sys.stdout)
assert -1 == capsys.readouterr().out.find("abc")
def test_get_nodes_by_unknown_path_segment_error(self, quiet_logger):
from collections import deque
from enum import Enum
from yamlpath.enums import PathSegmentTypes
names = [m.name for m in PathSegmentTypes] + ['DNF']
PathSegmentTypes = Enum('PathSegmentTypes', names)
yamldata = """---
key: value
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
path = YAMLPath("abc")
stringified = str(path) # Force Path to parse
path._escaped = deque([
(PathSegmentTypes.DNF, "abc"),
])
with pytest.raises(NotImplementedError):
nodes = list(processor._get_nodes_by_path_segment(data, path, 0))
def test_non_int_slice_error(self, quiet_logger):
yamldata = """---
- step: 1
- step: 2
- step: 3
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
with pytest.raises(YAMLPathException) as ex:
processor.set_value("[1:4F]", "")
assert -1 < str(ex.value).find("is not an integer array slice")
def test_non_int_array_index_error(self, quiet_logger):
from collections import deque
yamldata = """---
- 1
"""
yaml = YAML()
data = yaml.load(yamldata)
path = YAMLPath("[0]")
processor = Processor(quiet_logger, data)
strp = str(path)
path._escaped = deque([
(PathSegmentTypes.INDEX, "0F"),
])
path._unescaped = deque([
(PathSegmentTypes.INDEX, "0F"),
])
with pytest.raises(YAMLPathException) as ex:
nodes = list(processor._get_nodes_by_index(data, path, 0))
assert -1 < str(ex.value).find("is not an integer array index")
def test_nonexistant_path_search_method_error(self, quiet_logger):
from enum import Enum
from yamlpath.enums import PathSearchMethods
names = [m.name for m in PathSearchMethods] + ['DNF']
PathSearchMethods = Enum('PathSearchMethods', names)
yamldata = """---
top_scalar: value
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
with pytest.raises(NotImplementedError):
nodes = list(processor._get_nodes_by_search(
data,
SearchTerms(True, PathSearchMethods.DNF, ".", "top_scalar")
))
def test_adjoined_collectors_error(self, quiet_logger):
yamldata = """---
key: value
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
with pytest.raises(YAMLPathException) as ex:
nodes = list(processor.get_nodes("(&arrayOfHashes.step)(disabled_steps)"))
assert -1 < str(ex.value).find("has no meaning")
def test_no_attrs_to_arrays_error(self, quiet_logger):
yamldata = """---
array:
- one
- two
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
with pytest.raises(YAMLPathException) as ex:
nodes = list(processor.get_nodes("array.attr"))
assert -1 < str(ex.value).find("Cannot add")
def test_no_index_to_hashes_error(self, quiet_logger):
# Using [#] syntax is a disambiguated INDEX ELEMENT NUMBER. In
# DICTIONARY context, this would create an ambiguous request to access
# either the #th value or a value whose key is the literal #. As such,
# an error is deliberately generated when [#] syntax is used against
# dictionaries. When you actually want a DICTIONARY KEY that happens
# to be an integer, omit the square braces, [].
yamldata = """---
hash:
key: value
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
with pytest.raises(YAMLPathException) as ex:
nodes = list(processor.get_nodes("hash[6]"))
assert -1 < str(ex.value).find("Cannot add")
def test_get_nodes_array_impossible_type_error(self, quiet_logger):
yamldata = """---
array:
- 1
- 2
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
with pytest.raises(YAMLPathException) as ex:
nodes = list(processor.get_nodes(r"/array/(.=~/^.{3,4}$/)", default_value="New value"))
assert -1 < str(ex.value).find("Cannot add")
def test_no_attrs_to_scalars_errors(self, quiet_logger):
yamldata = """---
scalar: value
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
with pytest.raises(YAMLPathException) as ex:
nodes = list(processor.get_nodes("scalar[6]"))
assert -1 < str(ex.value).find("Cannot add")
with pytest.raises(YAMLPathException) as ex:
nodes = list(processor.get_nodes("scalar.key"))
assert -1 < str(ex.value).find("Cannot add")
@pytest.mark.parametrize("yamlpath,value,tally,mustexist,vformat,pathsep", [
("/anchorKeys[&keyOne]", "Set self-destruct", 1, True, YAMLValueFormats.DEFAULT, PathSeparators.AUTO),
("/hash[&keyTwo]", "Confirm", 1, True, YAMLValueFormats.DEFAULT, PathSeparators.AUTO),
("/anchorKeys[&recursiveAnchorKey]", "Recurse more", 1, True, YAMLValueFormats.DEFAULT, PathSeparators.AUTO),
("/hash[&recursiveAnchorKey]", "Recurse even more", 1, True, YAMLValueFormats.DEFAULT, PathSeparators.AUTO),
])
def test_key_anchor_changes(self, quiet_logger, yamlpath, value, tally, mustexist, vformat, pathsep):
yamldata = """---
anchorKeys:
&keyOne aliasOne: 11A1
&keyTwo aliasTwo: 22B2
&recursiveAnchorKey subjectKey: *recursiveAnchorKey
hash:
*keyOne :
subval: 1.1
*keyTwo :
subval: 2.2
*recursiveAnchorKey :
subval: 3.3
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
yamlpath = YAMLPath(yamlpath)
processor.set_value(yamlpath, value, mustexist=mustexist, value_format=vformat, pathsep=pathsep)
matchtally = 0
for node in processor.get_nodes(yamlpath):
assert unwrap_node_coords(node) == value
matchtally += 1
assert matchtally == tally
def test_key_anchor_children(self, quiet_logger):
yamldata = """---
anchorKeys:
&keyOne aliasOne: 1 1 Alpha 1
&keyTwo aliasTwo: 2 2 Beta 2
hash:
*keyOne :
subval: 1.1
*keyTwo :
subval: 2.2
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
yamlpath = YAMLPath("hash[&keyTwo].subval")
newvalue = "Mute audibles"
processor.set_value(yamlpath, newvalue, mustexist=True)
matchtally = 0
for node in processor.get_nodes(yamlpath):
assert unwrap_node_coords(node) == newvalue
matchtally += 1
assert matchtally == 1
def test_cannot_add_novel_alias_keys(self, quiet_logger):
yamldata = """---
anchorKeys:
&keyOne aliasOne: 1 1 Alpha 1
&keyTwo aliasTwo: 2 2 Beta 2
hash:
*keyOne :
subval: 1.1
*keyTwo :
subval: 2.2
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
yamlpath = YAMLPath("hash[&keyThree].subval")
newvalue = "Abort"
with pytest.raises(YAMLPathException) as ex:
nodes = list(processor.get_nodes(yamlpath))
assert -1 < str(ex.value).find("Cannot add")
@pytest.mark.parametrize("yamlpath,value,verifications", [
("number", 5280, [
("aliases[&alias_number]", 1),
("number", 5280),
("alias_number", 1),
("hash.number", 1),
("hash.alias_number", 1),
("complex.hash.number", 1),
("complex.hash.alias_number", 1),
]),
("aliases[&alias_number]", 5280, [
("aliases[&alias_number]", 5280),
("number", 1),
("alias_number", 5280),
("hash.number", 1),
("hash.alias_number", 5280),
("complex.hash.number", 1),
("complex.hash.alias_number", 5280),
]),
("bool", False, [
("aliases[&alias_bool]", True),
("bool", False),
("alias_bool", True),
("hash.bool", True),
("hash.alias_bool", True),
("complex.hash.bool", True),
("complex.hash.alias_bool", True),
]),
("aliases[&alias_bool]", False, [
("aliases[&alias_bool]", False),
("bool", True),
("alias_bool", False),
("hash.bool", True),
("hash.alias_bool", False),
("complex.hash.bool", True),
("complex.hash.alias_bool", False),
]),
])
def test_set_nonunique_values(self, quiet_logger, yamlpath, value, verifications):
yamldata = """---
aliases:
- &alias_number 1
- &alias_bool true
number: 1
bool: true
alias_number: *alias_number
alias_bool: *alias_bool
hash:
number: 1
bool: true
alias_number: *alias_number
alias_bool: *alias_bool
complex:
hash:
number: 1
bool: true
alias_number: *alias_number
alias_bool: *alias_bool
"""
yaml = YAML()
data = yaml.load(yamldata)
processor = Processor(quiet_logger, data)
processor.set_value(yamlpath, value)
for verification in verifications:
for verify_node_coord in processor.get_nodes(verification[0]):
assert unwrap_node_coords(verify_node_coord) == verification[1]
@pytest.mark.parametrize("yamlpath,results", [
("(temps[. >= 100]) - (temps[. > 110])", [[110, 100]]),
("(temps[. < 32]) - (temps[. >= 114])", [[0]]),
("(temps[. < 32]) + (temps[. > 110])", [[0, 114]]),
("(temps[. <= 32]) + (temps[. > 110])", [[32, 0, 114]]),
("(temps[. < 32]) + (temps[. >= 110])", [[0, 110, 114]]),
("(temps[. <= 32]) + (temps[. >= 110])", [[32, 0, 110, 114]]),
("(temps[. < 0]) + (temps[. >= 114])", [[114]]),
])
def test_get_singular_collectors(self, quiet_logger, yamlpath, results):
yamldata = """---
temps:
- 32
- 0
- 110
- 100
- 72
- 68
- 114
- 34
- 36
"""
yaml = YAML()
processor = Processor(quiet_logger, yaml.load(yamldata))
matchidx = 0
# Note that Collectors deal with virtual DOMs, so mustexist must always
# be set True. Otherwise, ephemeral virtual nodes would be created and
# discarded. Is this desirable? Maybe, but not today. For now, using
# Collectors without setting mustexist=True will be undefined behavior.
for node in processor.get_nodes(yamlpath, mustexist=True):
assert unwrap_node_coords(node) == results[matchidx]
matchidx += 1
assert len(results) == matchidx
@pytest.mark.parametrize("yamlpath,results", [
("(/list1) + (/list2)", [[1, 2, 3, 4, 5, 6]]),
("(/list1) - (/exclude)", [[1, 2]]),
("(/list2) - (/exclude)", [[5, 6]]),
("(/list1) + (/list2) - (/exclude)", [[1, 2, 5, 6]]),
("((/list1) + (/list2)) - (/exclude)", [[1, 2, 5, 6]]),
("(/list1) + ((/list2) - (/exclude))", [[1, 2, 3, 5, 6]]),
("((/list1) - (/exclude)) + ((/list2) - (/exclude))", [[1, 2, 5, 6]]),
("((/list1) - (/exclude)) + ((/list2) - (/exclude))*", [1, 2, 5, 6]),
("(((/list1) - (/exclude)) + ((/list2) - (/exclude)))[2]", [5]),
])
def test_scalar_collectors(self, quiet_logger, yamlpath, results):
yamldata = """---
list1:
- 1
- 2
- 3
list2:
- 4