-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtests.py
1943 lines (1790 loc) · 62.4 KB
/
tests.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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import tempfile
import traceback
import unittest
import yamlet
from contextlib import contextmanager
from ruamel.yaml.constructor import ConstructorError
def ParameterizedOnOpts(klass):
YO = yamlet.YamletOptions
YDO = yamlet._DebugOpts
# Create cloned classes with different Opts
def mkclass(name, caching_mode, preprocessing=None, traces=None):
# Dynamically create a new class extending the input ("parameterized") class
new_class = type(name, (klass,), {})
debug = YDO(preprocessing=preprocessing, traces=traces)
def Opts(self, **kwargs):
return yamlet.YamletOptions(**kwargs, caching=caching_mode,
_yamlet_debug_opts=debug)
new_class.Opts = Opts
return new_class
# Generate the three versions of the class with different caching modes
NoCacheClass = mkclass(f'{klass.__name__}_NoCaching', YO.CACHE_NOTHING)
NormalCacheClass = mkclass(f'{klass.__name__}_DefCaching', YO.CACHE_VALUES)
DebugCacheClass = mkclass(f'{klass.__name__}_DebugCaching',
YO.CACHE_DEBUG, traces=YDO.TRACE_PRETTY)
DebugAllClass = mkclass(f'{klass.__name__}_PreprocessAll',
YO.CACHE_DEBUG, YDO.PREPROCESS_EVERYTHING)
# Add the new classes to the global scope for unittest to pick up
for test_derivative in [NoCacheClass, NormalCacheClass, DebugCacheClass]:
globals()[test_derivative.__name__] = test_derivative
return DebugAllClass
def DefaultConfigOnly(klass):
def Opts(self, **kwargs): return yamlet.YamletOptions(**kwargs)
klass.Opts = Opts
return klass
def active(v):
if not v: return False
return v.lower() in {'on', 'yes', 'true', 'full'}
ParameterizedForStress = (
ParameterizedOnOpts if active(os.getenv('yamlet_stress'))
else DefaultConfigOnly)
@ParameterizedOnOpts
class TestTupleCompositing(unittest.TestCase):
def test_composited_fields(self):
YAMLET = '''# Yamlet
t1:
a:
ab:
aba: 121
abc: 123
ac:
acc: 133
c:
cb:
cba: 321
cbb: bad value
t2:
b:
bb:
bba: 221
bbb: 222
bc:
bca: 231
bcc: 233
c:
ca:
caa: 311
cab: 312
cac: 313
cb:
cbb: 322
cbc: 323
cc:
cca: 331
ccb: 332
ccc: 333
t3:
a:
aa:
aaa: 111
aab: 112
aac: 113
ab:
abb: 122
ac:
aca: 131
acb: 132
b:
ba:
baa: 211
bab: 212
bac: 213
bb:
bbc: 223
bc:
bcb: 232
comp1: !composite t1 t2 t3
comp2: !composite
- t1
- t2 t3
comp3: !expr t1 t2 t3
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
for compn in ['comp1', 'comp2', 'comp3']:
self.assertTrue(compn in y)
comp = y[compn]
for k1, v1 in {'a': 100, 'b': 200, 'c': 300}.items():
self.assertTrue(k1 in comp, f'{k1} in {compn}: {comp}')
comp1 = comp[k1]
for k2, v2 in {'a': 10, 'b': 20, 'c': 30}.items():
self.assertTrue((k1 + k2) in comp1, f'{k1 + k2} in {compn}: {comp1}')
comp2 = comp1[k1 + k2]
for k3, v3 in {'a': 1, 'b': 2, 'c': 3}.items():
self.assertTrue((k1 + k2 + k3) in comp2,
f'{k1 + k2 + k3} in {compn}: {comp2}')
self.assertEqual(comp2[k1 + k2 + k3], v1 + v2 + v3)
def test_partial_composition(self):
YAMLET = '''# YAMLET
t1:
val: world
deferred: !fmt Hello, {val}!
t2: !composite
- t1
- {
val: all you happy people
}
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['t1']['deferred'], 'Hello, world!')
self.assertEqual(y['t2']['deferred'], 'Hello, all you happy people!')
def test_parents_update(self):
YAMLET = '''# YAMLET
t1:
sub:
deferred: !fmt Hello, {val}!
t2: !composite
- t1
- {
val: world
}
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['t2']['sub']['deferred'], 'Hello, world!')
def test_parents_update_2(self):
'''Functions like the above test but also checks precedence.
It's assumed that the desirable behavior is that all variables in descendent
tuples take precedence over any values in the parent tuples. I left two
tests because even if someone changes this behavior to give the parent
priority, the above test should still pass.
'''
YAMLET = '''# YAMLET
t1:
val: doppelgänger
sub:
deferred: !fmt Hello, {val}!
t2: !composite
- t1
- {
val: world
}
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['t2']['sub']['deferred'], 'Hello, world!')
def test_parents_update_3(self):
YAMLET = '''# YAMLET
t1:
deferred: !fmt Hello, {val}!
t2:
val: world
sub: !expr t1 {}
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['t2']['sub']['deferred'], 'Hello, world!')
def test_parents_update_3b(self):
YAMLET = '''# YAMLET
t1:
deferred: !fmt Hello, {val}!
t2:
val: world
sub: !expr t1
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
with AssertRaisesCleanException(self, NameError):
val = y['t2']['sub']['deferred']
self.fail(f'Did not throw an exception; got `{val}`')
def test_parents_update_4(self):
YAMLET = '''# YAMLET
t1:
deferred: !fmt Hello, {val}!
t2:
val: world
sub: !composite
- t1
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['t2']['sub']['deferred'], 'Hello, world!')
def test_compositing_in_parenths(self):
YAMLET = '''# YAMLET
t1:
a: 10
b: 10
c: 30
val: !expr |
len(t1 {c: 30, d: 40, e:50})
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['val'], 5)
def test_overriding_inherited_tuples(self):
YAMLET = '''# YAMLET
t1:
shared_key: Value that appears in both tuples
sub:
t1_only_key: Value that only appears in t1
t1_only_key2: Second value that only appears in t1
sub2:
shared_key2: Nested value in both
t2: !composite
- t1
- t2_only_key: Value that only appears in t2
sub: !expr |
{ t2_only_key2: 'Second value that only appears in t1' }
sub2:
t2_only_key3: Nested value only in t2
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['t1']['shared_key'], 'Value that appears in both tuples')
self.assertEqual(y['t2']['shared_key'], 'Value that appears in both tuples')
self.assertEqual(y['t1']['sub'].keys(), {'t1_only_key', 't1_only_key2'})
self.assertEqual(y['t2']['sub'].keys(), {'t2_only_key2'})
self.assertEqual(y['t1']['sub2']['shared_key2'], 'Nested value in both')
self.assertEqual(y['t2']['sub2']['shared_key2'], 'Nested value in both')
self.assertEqual(y['t2']['sub2']['t2_only_key3'], 'Nested value only in t2')
self.assertEqual(y['t1']['sub2'].keys(), {'shared_key2'})
self.assertEqual(y['t2']['sub2'].keys(), {'shared_key2', 't2_only_key3'})
def test_overriding_inherited_tuples_with_ugliness(self):
YAMLET = '''# YAMLET
t1:
shared_key: Value that appears in both tuples
sub:
t1_only_key: Value that only appears in t1
t1_only_key2: Second value that only appears in t1
sub2:
shared_key2: Nested value in both
t2: !expr |
t1 {
t2_only_key: 'Value that only appears in t2',
sub: [{
t2_only_key2: 'Second value that only appears in t2'
}][0], # Trick to replace `sub` entirely
sub2: {
t2_only_key3: 'Nested value only in t2'
}
}
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['t1']['shared_key'], 'Value that appears in both tuples')
self.assertEqual(y['t2']['shared_key'], 'Value that appears in both tuples')
self.assertEqual(y['t1']['sub'].keys(), {'t1_only_key', 't1_only_key2'})
self.assertEqual(y['t2']['sub'].keys(), {'t2_only_key2'})
self.assertEqual(y['t1']['sub2']['shared_key2'], 'Nested value in both')
self.assertEqual(y['t2']['sub2']['shared_key2'], 'Nested value in both')
self.assertEqual(y['t2']['sub2']['t2_only_key3'], 'Nested value only in t2')
self.assertEqual(y['t1']['sub2'].keys(), {'shared_key2'})
self.assertEqual(y['t2']['sub2'].keys(), {'shared_key2', 't2_only_key3'})
def test_nullification(self):
YAMLET = '''# YAMLET
t1:
a: apple
b: boy
c: cat
d: dog
t2:
b: !null
c: !null
d: !external
t3: !expr t1 t2
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(len(y['t1']), 4)
self.assertEqual(len(y['t2']), 3)
self.assertEqual(len(y['t3']), 2)
self.assertEqual(y['t3'], {'a': 'apple', 'd': 'dog'})
def test_external_access(self):
YAMLET = '''# YAMLET
t1:
v: value
sub:
v: !external
exp: !expr v
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
with AssertRaisesCleanException(self, ValueError):
val = y['t1']['sub']['exp']
self.fail(f'Did not throw an exception; got `{val}`')
def test_null_access(self):
YAMLET = '''# YAMLET
t1:
v: value
sub:
v: !null
exp: !expr v
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual( y['t1']['sub']['exp'], 'value')
@ParameterizedOnOpts
class TestInheritance(unittest.TestCase):
def test_up_and_super(self):
YAMLET = '''# Yamlet
t1:
a: one
sub:
a: two
t2: !composite
- t1
- a: three
sub:
a: four
counting: !fmt '{up.super.a} {super.a} {up.a} {a}'
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['t2']['sub']['counting'], 'one two three four')
def test_invalid_up_super_usage(self):
YAMLET = '''# Yamlet
t:
a: !expr up.x
x: an actual value
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
with AssertRaisesCleanException(self, KeyError):
val = y['t']['a']
self.fail(f'Did not throw an exception; got `{val}`')
@ParameterizedOnOpts
class TestValueMechanics(unittest.TestCase):
def test_escaped_braces(self):
YAMLET = '''# Yamlet
v: Hello
v2: world
v3: !fmt '{{{v}}}, {{{{{v2}}}}}{{s}}!'
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['v3'], '{Hello}, {{world}}{s}!')
def test_array_comprehension(self):
YAMLET = '''# Yamlet
my_array: [1, 2, 'red', 'blue']
fishes: !expr "['{x} fish' for x in my_array]"
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(t['fishes'], ['1 fish', '2 fish', 'red fish', 'blue fish'])
def test_dict_comprehension(self):
YAMLET = '''# Yamlet
my_array: [1, 2, 'red', 'blue']
fishes: !expr "{x: 'fish' for x in my_array}"
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(t['fishes'],
{1: 'fish', 2: 'fish', 'red': 'fish', 'blue': 'fish'})
def test_array_comprehension_square(self):
YAMLET = '''# Yamlet
array1: [1, 2, 3, 4]
array2: ['red', 'green', 'blue', 'yellow']
fishes: !expr "['{x} {y} fish' for x in array1 for y in array2]"
filtered: !expr |
['{x} {y} fish' for x in array1 for y in array2 if x != len(y)]
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
fishes = t['fishes']
self.assertEqual(len(fishes), 16)
self.assertEqual(fishes[0], '1 red fish')
self.assertEqual(fishes[15], '4 yellow fish')
filtered = t['filtered']
self.assertEqual(len(filtered), 14)
self.assertEqual(filtered, [
'1 red fish', '1 green fish', '1 blue fish', '1 yellow fish',
'2 red fish', '2 green fish', '2 blue fish', '2 yellow fish',
'3 green fish', '3 blue fish', '3 yellow fish',
'4 red fish', '4 green fish', '4 yellow fish'])
def test_dict_literal(self):
YAMLET = '''# Yamlet
four: 4
mydict: !expr |
{1: 2, three: four}
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(set(t['mydict'].keys()), {1, 'three'})
self.assertEqual(t['mydict'][1], 2)
self.assertEqual(t['mydict']['three'], 4)
def test_set_literal(self):
YAMLET = '''# Yamlet
four: 4
myset: !expr |
{1, 2, 'three', four}
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(t['myset'], {1, 2, 'three', 4})
def test_pytuple_literal(self):
YAMLET = '''# Yamlet
four: 4
my_python_tuple: !expr |
(1, 2, 'three', four)
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(t['my_python_tuple'], (1, 2, 'three', 4))
def test_string_from_up(self):
YAMLET = '''# Yamlet
val: 1337
t:
val2: !expr up.val
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(t['t']['val2'], 1337)
def test_string_from_up_in_if(self):
YAMLET = '''# Yamlet
val: 1337
!if 1:
t:
val2: !expr val
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(t['t']['val2'], 1337)
def test_reference_other_scope(self):
YAMLET = '''# Yamlet
context:
not_in_evaluating_scope: Hello, world!
referenced: !fmt '{not_in_evaluating_scope}'
result: !expr context.referenced
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(t['result'], 'Hello, world!')
def test_reference_other_scope_2(self):
YAMLET = '''# Yamlet
context:
not_in_evaluating_scope: Hello, world!
referenced: !fmt '{not_in_evaluating_scope}'
context2:
inner_ref: !expr context
referenced_2: !expr inner_ref.referenced
result: !expr context2.referenced_2
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(t['result'], 'Hello, world!')
def test_reference_env(self):
YAMLET = '''# Yamlet
other_context:
not_inherited: Hello, world!
referenced: !fmt '{not_inherited}'
my_context:
my_variable: !expr other_context.referenced
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(t['my_context']['my_variable'], 'Hello, world!')
def test_reference_nested_env(self):
YAMLET = '''# Yamlet
other_context:
not_inherited: Hello, world!
subcontext:
referenced: !fmt '{not_inherited}'
my_context:
captured_subcontext: !expr other_context.subcontext
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(t['my_context']['captured_subcontext']['referenced'],
'Hello, world!')
def test_reference_nested_env_2(self):
YAMLET = '''# Yamlet
other_context:
not_inherited: Hello, world!
subcontext:
referenced: !fmt '{not_inherited}'
my_context:
captured_subcontext: !composite
- other_context.subcontext
- red: herring
not_inherited: 'Good night, moon!'
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(t['my_context']['captured_subcontext']['referenced'],
'Good night, moon!')
def test_reference_nested_env_3(self):
YAMLET = '''# Yamlet
other_context:
not_inherited: Hello, world!
subcontext:
referenced: !fmt '{not_inherited}'
my_context:
not_inherited: 'Good night, moon!'
captured_subcontext: !composite
- other_context.subcontext
- red: herring
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(t['my_context']['captured_subcontext']['referenced'],
'Good night, moon!')
def test_reference_nested_env_4(self):
YAMLET = '''# Yamlet
other_context:
not_inherited: Hello, world!
subcontext:
referenced: !fmt '{not_inherited}'
my_context:
captured_subcontext: !composite
- other_context.subcontext
- red: herring
test_probe: !expr my_context.captured_subcontext.super
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertTrue(t['test_probe'] is t['other_context']['subcontext'])
self.assertEqual(t['my_context']['captured_subcontext']['referenced'],
'Hello, world!')
def test_reference_nested_env_5(self):
YAMLET = '''# Yamlet
chain_1:
not_inherited: Hello, world!
subcontext:
referenced: !fmt '{not_inherited}'
chain_2:
captured_subcontext_1: !composite
- chain_1.subcontext
- red: herring
chain_3:
captured_subcontext_2: !composite
- chain_2.captured_subcontext_1
- hoax: value
chain_4:
captured_subcontext_3: !composite
- chain_3.captured_subcontext_2
- artifice: more junk
result: !fmt '{chain_4.captured_subcontext_3.referenced}'
'''
loader = yamlet.Loader(self.Opts())
t = loader.load(YAMLET)
self.assertEqual(t['result'], 'Hello, world!')
@ParameterizedOnOpts
class TestFunctions(unittest.TestCase):
def test_escaped_braces(self):
YAMLET = '''# Yamlet
t:
v: !expr func(x)
w: !expr func('I am not called.')
x: !expr func('Hello, ')
'''
side_effect = []
uniq = ['world!']
def func(x):
side_effect.append(x)
return uniq
loader = yamlet.Loader(self.Opts(functions={'func': func}))
y = loader.load(YAMLET)
self.assertTrue(y['t']['v'] is uniq)
self.assertEqual(side_effect, ['Hello, ', ['world!']])
@ParameterizedOnOpts
class TestConditionals(unittest.TestCase):
def test_cond_routine(self):
YAMLET = '''# Yamlet
t1:
color: !expr cond(blocked, 'red', 'green')
t2: !composite
- t1
- { blocked: True }
t3: !composite
- t1
- { blocked: False }
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['t2']['color'], 'red')
self.assertEqual(y['t3']['color'], 'green')
def test_cond_routine_2(self):
YAMLET = '''# Yamlet
t1:
conditionals: !expr |
cond(blocked, {
color: 'red'
}, {
color: 'green'
}) {
val: 'Color: {color}'
}
t2: !composite
- t1
- { blocked: True }
t3: !composite
- t1
- { blocked: False }
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['t2']['conditionals']['color'], 'red')
self.assertEqual(y['t2']['conditionals']['val'], 'Color: red')
self.assertEqual(y['t3']['conditionals']['val'], 'Color: green')
self.assertEqual(y['t3']['conditionals']['color'], 'green')
def test_if_statement_templating(self):
YAMLET = '''# Yamlet
t0:
!if animal == 'fish':
environment: water
!elif animal == 'dog':
attention: pats
toys: !expr ([favorite_toy])
!elif animal == 'cat':
diet: meat
!else:
recommendation: specialist
t1: !expr |
t0 { animal: 'cat' }
t2: !composite
- t0
- animal: dog
favorite_toy: squeaky ball
action: !expr attention
t3: !expr |
t0 { animal: 'fish' }
t4: !expr |
t0 { animal: 'squirrel' }
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['t1']['diet'], 'meat')
self.assertEqual(y['t2']['action'], 'pats')
self.assertEqual(y['t2']['attention'], 'pats')
self.assertEqual(y['t2']['toys'], ['squeaky ball'])
self.assertEqual(y['t3']['environment'], 'water')
self.assertEqual(y['t4']['recommendation'], 'specialist')
self.assertEqual(len(y['t1']), 2)
self.assertEqual(len(y['t2']), 5)
self.assertEqual(len(y['t3']), 2)
self.assertEqual(len(y['t4']), 2)
self.assertEqual(set(y['t1'].keys()), {'animal', 'diet'})
self.assertEqual(set(y['t2'].keys()), {
'animal', 'attention', 'toys', 'favorite_toy', 'action'})
self.assertEqual(set(y['t3'].keys()), {'animal', 'environment'})
self.assertEqual(set(y['t4'].keys()), {'animal', 'recommendation'})
def test_if_statement_templating_2(self):
YAMLET = '''# Yamlet
t0:
!if animal == 'fish':
environment: water
!elif animal == 'dog':
attention: pats
toys: !expr ([favorite_toy])
!elif animal == 'cat':
diet: meat
!else:
recommendation: specialist
t1: !expr |
t0 { animal: 'cat' }
t2: !composite
- t0
- animal: dog
favorite_toy: squeaky ball
action: !expr attention
t3: !expr |
t0 { animal: 'fish' }
t4: !expr |
t0 { animal: 'squirrel' }
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertEqual(y['t1'].evaluate_fully(), {
'animal': 'cat',
'diet': 'meat'})
self.assertEqual(y['t2'].evaluate_fully(), {
'animal': 'dog',
'action': 'pats',
'attention': 'pats',
'favorite_toy': 'squeaky ball',
'toys': ['squeaky ball']})
self.assertEqual(y['t3'].evaluate_fully(), {
'animal': 'fish',
'environment': 'water'})
self.assertEqual(y['t4'].evaluate_fully(), {
'animal': 'squirrel',
'recommendation': 'specialist'})
def test_if_statements(self):
YAMLET = '''# Yamlet
!if (1 + 1 == 2):
a: 10
b: { ba: 11 }
!else:
crap: value
!if ('shark' == 'fish'):
more-crap: values
!elif ('crab' == 'crab'):
b: { bb: 12 }
c: 13
!else:
still-crap: 10
!if ('fish' == 'fish'):
d: 14
!else:
crapagain: 2
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertTrue('a' in y)
self.assertTrue('b' in y)
self.assertTrue('c' in y)
self.assertTrue('d' in y)
self.assertEqual(y['a'], 10)
self.assertEqual(y['b']['ba'], 11)
self.assertEqual(y['c'], 13)
self.assertEqual(y['b']['bb'], 12)
self.assertEqual(y['d'], 14)
self.assertEqual(y.keys(), {'a', 'b', 'c', 'd'}, str(y))
self.assertFalse('crap' in y)
self.assertFalse('more-crap' in y)
self.assertFalse('crapagain' in y)
def test_buried_if(self):
YAMLET = '''# Yamlet
t:
!if (1 + 1 == 2):
a: 10
b: { ba: 11 }
!else:
crap: value
!if (2 + 2 == 6):
crap: value
!else:
b: { bb: 12 }
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
self.assertTrue('a' in y['t'])
self.assertTrue('b' in y['t'])
self.assertEqual(y['t']['a'], 10)
self.assertEqual(y['t']['b']['ba'], 11)
self.assertEqual(y['t']['b']['bb'], 12)
self.assertEqual(y['t'].keys(), {'a', 'b'})
self.assertFalse('crap' in y['t'])
def test_nested_if_statements(self):
# Another test from GPT, but this one, I asked for specifically. 😁
YAMLET = '''# Yamlet
t1:
!if outer == 'A':
!if inner == 'X':
result: 'AX'
!elif inner == 'Y':
result: 'AY'
!else:
result: 'A?'
!elif outer == 'B':
!if inner == 'X':
result: 'BX'
!elif inner == 'Y':
result: 'BY'
!else :
result: 'B?'
!else:
result: 'Unknown'
t2: !expr |
t1 { outer: 'A', inner: 'X' }
t3: !expr |
t1 { outer: 'A', inner: 'Z' }
t4: !expr |
t1 { outer: 'B', inner: 'Y' }
t5: !expr |
t1 { outer: 'B', inner: 'Z' }
t6: !expr |
t1 { outer: 'C', inner: 'X' }
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
# Check for various nested conditions
self.assertEqual(y['t2']['result'], 'AX') # outer == 'A', inner == 'X'
self.assertEqual(y['t3']['result'], 'A?') # outer == 'A', inner not matched
self.assertEqual(y['t4']['result'], 'BY') # outer == 'B', inner == 'Y'
self.assertEqual(y['t5']['result'], 'B?') # outer == 'B', inner not matched
self.assertEqual(y['t6']['result'], 'Unknown') # outer not matched
def test_double_nested_if_statements(self):
YAMLET = '''# Yamlet
one: 1
tp:
!if first == 'A':
!if middle == 'X':
!if last == 1:
result: !fmt AX{one}
!elif last == 2:
result: AX2
!else:
result: AX?
!elif middle == 'Y':
!if last == 1:
result: AY1
!elif last == 2:
result: AY2
!else :
result: AY?
!else:
result: 'A??'
!elif first == 'B':
!if middle == 'X':
!if last == 1:
result: BX1
!elif last == 2:
result: BX2
!else :
result: BX?
!elif middle == 'Y':
!if last == 1:
result: BY1
!elif last == 2:
result: BY2
!else:
result: BY?
!else:
result: 'B??'
!else:
result: '???'
ax1: !composite [tp, {first: 'A', middle: 'X', last: 1}]
ax2: !composite [tp, {first: 'A', middle: 'X', last: 2}]
ax3: !composite [tp, {first: 'A', middle: 'X', last: 3}]
ay1: !composite [tp, {first: 'A', middle: 'Y', last: 1}]
ay2: !composite [tp, {first: 'A', middle: 'Y', last: 2}]
ay3: !composite [tp, {first: 'A', middle: 'Y', last: 3}]
az1: !composite [tp, {first: 'A', middle: 'Z', last: 1}]
bx1: !composite [tp, {first: 'B', middle: 'X', last: 1}]
bx2: !composite [tp, {first: 'B', middle: 'X', last: 2}]
bx3: !composite [tp, {first: 'B', middle: 'X', last: 3}]
by1: !composite [tp, {first: 'B', middle: 'Y', last: 1}]
by2: !composite [tp, {first: 'B', middle: 'Y', last: 2}]
by3: !composite [tp, {first: 'B', middle: 'Y', last: 3}]
bz1: !composite [tp, {first: 'B', middle: 'Z', last: 1}]
cx1: !composite [tp, {first: 'C', middle: 'X', last: 1}]
'''
loader = yamlet.Loader(self.Opts())
y = loader.load(YAMLET)
# Check for various nested conditions
self.assertEqual(y['ax1']['result'], 'AX1')
self.assertEqual(y['ax2']['result'], 'AX2')
self.assertEqual(y['ax3']['result'], 'AX?')
self.assertEqual(y['ay1']['result'], 'AY1')
self.assertEqual(y['ay2']['result'], 'AY2')
self.assertEqual(y['ay3']['result'], 'AY?')
self.assertEqual(y['az1']['result'], 'A??')
self.assertEqual(y['bx1']['result'], 'BX1')
self.assertEqual(y['bx2']['result'], 'BX2')
self.assertEqual(y['bx3']['result'], 'BX?')
self.assertEqual(y['by1']['result'], 'BY1')
self.assertEqual(y['by2']['result'], 'BY2')
self.assertEqual(y['by3']['result'], 'BY?')
self.assertEqual(y['bz1']['result'], 'B??')
self.assertEqual(y['cx1']['result'], '???')
def test_fuzzy_if(self):
YAMLET = '''# Yamlet
!if fuzzy == 'rodent':
food: pellet
!if fuzzy == 'hamster':
habitat: tubes
!elif fuzzy == 'fish':
food: flake
!else:
food: kibble
'''
fuzzy = FuzzyAnimalComparator()
loader = yamlet.Loader(self.Opts(globals={'fuzzy': fuzzy}))
fuzzy.animal = 'hamster'
y = loader.load(YAMLET)
self.assertEqual(y.keys(), {'food', 'habitat'})
self.assertEqual(y['food'], 'pellet')
self.assertEqual(y['habitat'], 'tubes')
fuzzy.animal = 'betta'
y = loader.load(YAMLET)
self.assertEqual(y.keys(), {'food'})
self.assertEqual(y['food'], 'flake')
fuzzy.animal = 'dog'
y = loader.load(YAMLET)
self.assertEqual(y.keys(), {'food'})
self.assertEqual(y['food'], 'kibble')
fuzzy.animal = 'rat'
y = loader.load(YAMLET)
self.assertEqual(y['food'], 'pellet')
self.assertEqual(y.keys(), {'food'})
@ParameterizedForStress
class TestStress(unittest.TestCase):
def test_utter_insanity(self):
YAMLET = '''# Yamlet
name_number:
!if number > 1000:
name: !fmt '{lead.name} thousand{space}{remainder.name}'
lead: !expr |
name_number { number: up.number // 1000 }
space: !expr cond(lead and remainder.name, ' ', '')
remainder: !expr |
name_number { number: up.number % 1000 }
!elif number > 100:
name: !fmt '{lead.name} hundred{space}{remainder.name}'
lead: !expr |
name_number { number: up.number // 100 }
space: !expr cond(lead and remainder.name, ' ', '')
remainder: !expr |
name_number { number: up.number % 100 }
!elif number > 19:
name: !fmt '{lead}{hyphen}{remainder.name}'
lead: !expr |
['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty',
'seventy', 'eighty', 'ninety'][int(number / 10)] # Just2B different
hyphen: !expr cond(lead and remainder.name, '-', '')