-
Notifications
You must be signed in to change notification settings - Fork 644
Expand file tree
/
Copy pathRandomizerTest.py
More file actions
1247 lines (985 loc) · 39.5 KB
/
Copy pathRandomizerTest.py
File metadata and controls
1247 lines (985 loc) · 39.5 KB
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
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pyre-unsafe
from __future__ import absolute_import, division, print_function, unicode_literals
import itertools
import math
import unittest
import thrift.util.randomizer as randomizer
from fuzz import ttypes
from thrift import Thrift
class TestRandomizer:
iterations = 1024
def get_randomizer(self, ttypes, spec_args, constraints):
state = randomizer.RandomizerState({"global_constraint": 100})
return state.get_randomizer(ttypes, spec_args, constraints)
class TestBoolRandomizer(unittest.TestCase, TestRandomizer):
def test_always_true(self):
cls = self.__class__
constraints = {"p_true": 1.0}
gen = self.get_randomizer(Thrift.TType.BOOL, None, constraints)
for _ in range(cls.iterations):
self.assertTrue(gen.generate())
def test_always_false(self):
cls = self.__class__
constraints = {"p_true": 0.0}
gen = self.get_randomizer(Thrift.TType.BOOL, None, constraints)
for _ in range(cls.iterations):
self.assertFalse(gen.generate())
def test_seeded(self):
cls = self.__class__
constraints = {"seeds": [True], "p_random": 0, "p_fuzz": 0}
gen = self.get_randomizer(Thrift.TType.BOOL, None, constraints)
for _ in range(cls.iterations):
self.assertTrue(gen.generate())
def test_int_seeded(self):
cls = self.__class__
constraints = {"seeds": [1], "p_random": 0, "p_fuzz": 0}
gen = self.get_randomizer(Thrift.TType.BOOL, None, constraints)
for _ in range(cls.iterations):
self.assertTrue(gen.generate())
class TestEnumRandomizer(unittest.TestCase, TestRandomizer):
def test_always_valid(self):
cls = self.__class__
constraints = {"p_invalid": 0}
gen = self.get_randomizer(Thrift.TType.I32, ttypes.Color, constraints)
for _ in range(cls.iterations):
self.assertIn(gen.generate(), ttypes.Color._VALUES_TO_NAMES)
def test_never_valid(self):
cls = self.__class__
constraints = {"p_invalid": 1}
gen = self.get_randomizer(Thrift.TType.I32, ttypes.Color, constraints)
for _ in range(cls.iterations):
self.assertNotIn(gen.generate(), ttypes.Color._VALUES_TO_NAMES)
def test_choices(self):
cls = self.__class__
choices = ["RED", "BLUE", "BLACK"]
constraints = {"choices": choices}
gen = self.get_randomizer(Thrift.TType.I32, ttypes.Color, constraints)
for _ in range(cls.iterations):
val = gen.generate()
name = ttypes.Color._VALUES_TO_NAMES[val]
self.assertIn(name, choices)
def test_seeded(self):
cls = self.__class__
seeds = ["RED", "BLUE", "BLACK"]
constraints = {"seeds": seeds, "p_random": 0, "p_fuzz": 0}
gen = self.get_randomizer(Thrift.TType.I32, ttypes.Color, constraints)
for _ in range(cls.iterations):
val = gen.generate()
name = ttypes.Color._VALUES_TO_NAMES[val]
self.assertIn(name, seeds)
class TestIntRandomizer(TestRandomizer):
@classmethod
def _one_bit_flipped(cls, a, b):
"""Return true if a and b differ at most one bit position"""
diff = a ^ b # Bits set to 1 where a and b differ
# If diff has only one `1` bit, subtracting one will clear that bit
# Otherwise, the most significant 1 will not be cleared
return 0 == (diff & (diff - 1))
@classmethod
def _within_delta(cls, a, b, delta):
return delta >= abs(a - b)
@classmethod
def _is_fuzzed_single_seed(cls, seed, fuzzed, delta):
return cls._one_bit_flipped(seed, fuzzed) or cls._within_delta(
seed, fuzzed, delta
)
@classmethod
def is_fuzzed(cls, seeds, fuzzed, delta=None):
"""Check whether `fuzzed` could have been
generated by fuzzing any element of `seeds`"""
if delta is None:
# Find the default `fuzz_max_delta` constraint
randomizer_cls = randomizer.RandomizerState().get_randomizer(
# pyrefly: ignore [missing-attribute]
cls.ttype,
None,
{},
)
delta = randomizer_cls.default_constraints["fuzz_max_delta"]
return any(cls._is_fuzzed_single_seed(seed, fuzzed, delta) for seed in seeds)
@property
def min(self):
cls = self.__class__
# pyrefly: ignore [missing-attribute]
n_bits = cls.n_bits
return -(2 ** (n_bits - 1))
@property
def max(self):
cls = self.__class__
# pyrefly: ignore [missing-attribute]
n_bits = cls.n_bits
return (2 ** (n_bits - 1)) - 1
def testInRange(self):
cls = self.__class__
# pyrefly: ignore [missing-attribute]
ttype = cls.ttype
min_ = self.min
max_ = self.max
gen = self.get_randomizer(ttype, None, {})
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertGreaterEqual(val, min_)
# pyrefly: ignore [missing-attribute]
self.assertLessEqual(val, max_)
def testConstant(self):
cls = self.__class__
# pyrefly: ignore [missing-attribute]
ttype = cls.ttype
constant = 17
constraints = {"choices": [constant]}
gen = self.get_randomizer(ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertEqual(val, constant)
def testChoices(self):
cls = self.__class__
# pyrefly: ignore [missing-attribute]
ttype = cls.ttype
choices = [11, 17, 19]
constraints = {"choices": choices}
gen = self.get_randomizer(ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertIn(val, choices)
def testRange(self):
cls = self.__class__
# pyrefly: ignore [missing-attribute]
ttype = cls.ttype
range_ = [45, 55]
constraints = {"range": range_}
gen = self.get_randomizer(ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertGreaterEqual(val, range_[0])
# pyrefly: ignore [missing-attribute]
self.assertLessEqual(val, range_[1])
def testRangeChoicePrecedence(self):
cls = self.__class__
# pyrefly: ignore [missing-attribute]
ttype = cls.ttype
range_ = [45, 55]
choices = [11, 17, 19]
constraints = {"range": range_, "choices": choices}
gen = self.get_randomizer(ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertIn(val, choices)
def testSeeded(self):
cls = self.__class__
# pyrefly: ignore [missing-attribute]
ttype = cls.ttype
seeds = [11, 17, 19]
constraints = {"seeds": seeds, "p_random": 0, "p_fuzz": 0}
gen = self.get_randomizer(ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertIn(val, seeds)
def testFuzzing(self):
cls = self.__class__
# pyrefly: ignore [missing-attribute]
ttype = cls.ttype
min_ = self.min
max_ = self.max
max_delta = 4
seeds = [0, self.max - int(max_delta / 2), self.min + int(max_delta / 2)]
constraints = {
"seeds": seeds,
"p_random": 0,
"p_fuzz": 1,
"fuzz_max_delta": max_delta,
}
gen = self.get_randomizer(ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertGreaterEqual(val, min_)
# pyrefly: ignore [missing-attribute]
self.assertLessEqual(val, max_)
# pyrefly: ignore [missing-attribute]
self.assertTrue(cls.is_fuzzed(seeds, val, max_delta))
class TestByteRandomizer(TestIntRandomizer, unittest.TestCase):
ttype = Thrift.TType.BYTE
n_bits = 8
class TestI16Randomizer(TestIntRandomizer, unittest.TestCase):
ttype = Thrift.TType.I16
n_bits = 16
class TestI32Randomizer(TestIntRandomizer, unittest.TestCase):
ttype = Thrift.TType.I32
n_bits = 32
class TestI64Randomizer(TestIntRandomizer, unittest.TestCase):
ttype = Thrift.TType.I64
n_bits = 64
class TestFloatRandomizer(TestRandomizer):
@property
def randomizer_cls(self):
return self.__class__.randomizer_cls
def testZero(self):
cls = self.__class__
constraints = {"p_zero": 1, "p_unreal": 0}
gen = self.get_randomizer(self.randomizer_cls.ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertEqual(val, 0.0)
def testNonZero(self):
cls = self.__class__
constraints = {
"p_zero": 0,
}
gen = self.get_randomizer(self.randomizer_cls.ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertNotEqual(val, 0.0)
def testUnreal(self):
cls = self.__class__
constraints = {"p_unreal": 1}
gen = self.get_randomizer(self.randomizer_cls.ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertTrue(math.isnan(val) or math.isinf(val))
def testReal(self):
cls = self.__class__
constraints = {"p_unreal": 0}
gen = self.get_randomizer(self.randomizer_cls.ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertFalse(math.isnan(val) or math.isinf(val))
def testConstant(self):
cls = self.__class__
constant = 77.2
constraints = {"mean": constant, "std_deviation": 0, "p_unreal": 0, "p_zero": 0}
gen = self.get_randomizer(self.randomizer_cls.ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertEqual(val, constant)
def testChoices(self):
cls = self.__class__
choices = [float("-inf"), 0.0, 13.37]
constraints = {"choices": choices}
gen = self.get_randomizer(self.randomizer_cls.ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertIn(val, choices)
def testSeeded(self):
cls = self.__class__
seeds = [float("-inf"), 0.0, 13.37]
constraints = {"seeds": seeds, "p_random": 0, "p_fuzz": 0}
gen = self.get_randomizer(self.randomizer_cls.ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertIn(val, seeds)
def testIntSeeded(self):
cls = self.__class__
seeds = [1, 2, 3]
constraints = {"seeds": seeds, "p_random": 0, "p_fuzz": 0}
gen = self.get_randomizer(self.randomizer_cls.ttype, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# pyrefly: ignore [missing-attribute]
self.assertIn(val, seeds)
class TestSinglePrecisionRandomizer(TestFloatRandomizer, unittest.TestCase):
randomizer_cls = randomizer.SinglePrecisionFloatRandomizer
ttype = Thrift.TType.FLOAT
class TestDoublePrecisionRandomizer(TestFloatRandomizer, unittest.TestCase):
randomizer_cls = randomizer.DoublePrecisionFloatRandomizer
ttype = Thrift.TType.DOUBLE
class TestStringRandomizer(TestRandomizer, unittest.TestCase):
def testInRange(self):
cls = self.__class__
ascii_min, ascii_max = randomizer.StringRandomizer.ascii_range
gen = self.get_randomizer(Thrift.TType.STRING, None, {})
for _ in range(cls.iterations):
val = gen.generate()
for char in val:
self.assertTrue(ascii_min <= ord(char) <= ascii_max)
def testEmpty(self):
cls = self.__class__
constraints = {"mean_length": 0}
gen = self.get_randomizer(Thrift.TType.STRING, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
for _char in val:
self.assertEqual(0, len(val))
def testChoices(self):
cls = self.__class__
choices = ["foo", "bar"]
constraints = {"choices": choices}
gen = self.get_randomizer(Thrift.TType.STRING, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertIn(val, choices)
def testSeeded(self):
cls = self.__class__
seeds = ["foo", "bar"]
constraints = {"seeds": seeds, "p_random": 0, "p_fuzz": 0}
gen = self.get_randomizer(Thrift.TType.STRING, None, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertIn(val, seeds)
class TestListRandomizer(TestRandomizer, unittest.TestCase):
@classmethod
def _has_extra_element(cls, shorter, longer):
"""Return True if the list `longer` can be created by inserting
one element into `shorter`"""
assert len(shorter) + 1 == len(longer)
found_inserted = False
for i, elem in enumerate(shorter):
if found_inserted:
# Same element should be at greater index in `longer`
if elem != longer[i + 1]:
return False
else:
# Should be at the same index; otherwise we have found
# the inserted element
if elem != longer[i]:
found_inserted = True
return True
@classmethod
def _is_fuzzed_single_seed(cls, seed, fuzzed):
"""Check whether `fuzzed` could have been generated by fuzzing `seed`
Requires that the elements of the list are of type i32
"""
old_len = len(seed)
new_len = len(fuzzed)
len_delta = new_len - old_len
if len_delta == -1:
# An element was deleted. All other elements should be unaltered
return cls._has_extra_element(fuzzed, seed)
elif len_delta == 0:
# An element was fuzzed
different_elements = []
for old, new in zip(seed, fuzzed):
if old != new:
different_elements.append((old, new))
if len(different_elements) == 0:
# Fuzzed element was not changed
return True
elif len(different_elements) == 1:
# Element was fuzzed
seed_elem, fuzzed_elem = different_elements[0]
return TestI32Randomizer.is_fuzzed([seed_elem], fuzzed_elem)
else:
return False
elif len_delta == 1:
# An element was inserted. All other elements should be unaltered
return cls._has_extra_element(seed, fuzzed)
else:
return False
@classmethod
def is_fuzzed(cls, seeds, fuzzed):
"""Check whether `fuzzed` could have been generated by
fuzzing any element of `seeds`. Requires that the elements
of the list are of type i32"""
return any(cls._is_fuzzed_single_seed(seed, fuzzed) for seed in seeds)
def testEmpty(self):
cls = self.__class__
ttype = Thrift.TType.LIST
spec_args = (Thrift.TType.I32, None) # Elements are i32
constraints = {"mean_length": 0}
gen = self.get_randomizer(ttype, spec_args, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertEqual(len(val), 0)
def testMaxLength(self):
cls = self.__class__
ttype = Thrift.TType.LIST
spec_args = (Thrift.TType.I32, None) # Elements are i32
constraints = {"mean_length": 100, "max_length": 99}
gen = self.get_randomizer(ttype, spec_args, constraints)
# Test to make sure that max length is enforced.
#
# Generate a lot of lists that should never be over 99 long
for _ in range(cls.iterations):
val = gen.generate()
self.assertLessEqual(len(val), 99)
def testElementConstraints(self):
cls = self.__class__
ttype = Thrift.TType.LIST
spec_args = (Thrift.TType.BOOL, None)
constraints = {"element": {"p_true": 0}}
gen = self.get_randomizer(ttype, spec_args, constraints)
for _ in range(cls.iterations):
val = gen.generate()
for elem in val:
self.assertFalse(elem)
def testSeeded(self):
cls = self.__class__
seeds = [[True, False, True], [False, False], []]
ttype = Thrift.TType.LIST
spec_args = (Thrift.TType.BOOL, None)
constraints = {"seeds": seeds, "p_random": 0, "p_fuzz": 0}
gen = self.get_randomizer(ttype, spec_args, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertIn(val, seeds)
def testFuzzed(self):
cls = self.__class__
seeds = [[], [1], [1, 2], [1, 2, 3], [1, 1, 1, 2, 2, 2, 3, 3, 3], [1, 1]]
ttype = Thrift.TType.LIST
spec_args = (Thrift.TType.I32, None)
constraints = {
"seeds": seeds,
"p_random": 0,
"p_fuzz": 1,
"element": {"p_random": 0, "p_fuzz": 1},
}
gen = self.get_randomizer(ttype, spec_args, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertTrue(
cls.is_fuzzed(seeds, val), msg="val %s not generated by fuzzing" % val
)
class TestSetRandomizer(TestRandomizer, unittest.TestCase):
def testEmpty(self):
cls = self.__class__
ttype = Thrift.TType.SET
spec_args = (Thrift.TType.I32, None) # Elements are i32
constraints = {"mean_length": 0}
gen = self.get_randomizer(ttype, spec_args, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertEqual(len(val), 0)
def testElementConstraints(self):
cls = self.__class__
ttype = Thrift.TType.SET
spec_args = (Thrift.TType.BOOL, None)
constraints = {"element": {"p_true": 0}}
gen = self.get_randomizer(ttype, spec_args, constraints)
for _ in range(cls.iterations):
val = gen.generate()
for elem in val:
self.assertFalse(elem)
def testSeeded(self):
cls = self.__class__
seeds = [{1, 2, 3}, set(), {-1, -2, -3}]
ttype = Thrift.TType.SET
spec_args = (Thrift.TType.I32, None)
constraints = {"seeds": seeds, "p_random": 0, "p_fuzz": 0}
gen = self.get_randomizer(ttype, spec_args, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertIn(val, seeds)
class TestMapRandomizer(TestRandomizer, unittest.TestCase):
def testEmpty(self):
cls = self.__class__
ttype = Thrift.TType.MAP
spec_args = (Thrift.TType.I32, None, Thrift.TType.I16, None)
constraints = {"mean_length": 0}
gen = self.get_randomizer(ttype, spec_args, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertEqual(len(val), 0)
def testKeyConstraints(self):
cls = self.__class__
ttype = Thrift.TType.MAP
spec_args = (Thrift.TType.BOOL, None, Thrift.TType.I16, None)
constraints = {"key": {"p_true": 0}}
gen = self.get_randomizer(ttype, spec_args, constraints)
for _ in range(cls.iterations):
val = gen.generate()
for elem in val:
self.assertFalse(elem)
def testValConstraints(self):
cls = self.__class__
ttype = Thrift.TType.MAP
spec_args = (Thrift.TType.I32, None, Thrift.TType.I32, ttypes.Color)
constraints = {"value": {"p_invalid": 0}}
gen = self.get_randomizer(ttype, spec_args, constraints)
for _ in range(cls.iterations):
val = gen.generate()
for elem in val.values():
self.assertIn(elem, ttypes.Color._VALUES_TO_NAMES)
def testSeeded(self):
cls = self.__class__
seeds = [{1: "foo", 2: "fee", 3: "fwee"}, {}, {0: ""}]
ttype = Thrift.TType.MAP
spec_args = (Thrift.TType.I32, None, Thrift.TType.STRING, None)
constraints = {"seeds": seeds, "p_random": 0, "p_fuzz": 0}
gen = self.get_randomizer(ttype, spec_args, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertIn(val, seeds)
class TestStructRandomizer(TestRandomizer, unittest.TestCase):
def get_spec_args(self, ttype):
# (ttype, thrift_spec, is_union)
return (ttype, ttype.thrift_spec, ttype.isUnion())
def struct_randomizer(self, ttype=None, constraints=None):
if ttype is None:
# pyrefly: ignore [missing-attribute]
ttype = self.__class__.ttype
return self.get_randomizer(
Thrift.TType.STRUCT, self.get_spec_args(ttype), constraints or {}
)
def testNoFieldConstraints(self):
cls = self.__class__
constraints = {
"per_field": {"a": {"p_include": 0.0}, "b": {"p_include": 0.0}},
"p_include": 1.0,
}
gen = self.struct_randomizer(ttypes.StructWithOptionals, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertIsNotNone(val)
self.assertIsNone(val.a)
self.assertIsNone(val.b)
def testOneTrueFieldConstraints(self):
cls = self.__class__
constraints = {
"per_field": {"b": {"p_include": 0.0}},
"p_include": 1.0,
"a": {"p_true": 1.0},
}
gen = self.struct_randomizer(ttypes.StructWithOptionals, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertIsNotNone(val)
self.assertTrue(val.a)
self.assertIsNone(val.b)
def testStructSeed(self):
cls = self.__class__
constraints = {
"|Rainbow": {
"seeds": [ttypes.Rainbow(colors=[ttypes.Color.RED])],
},
"|NestedStructs": {
"seeds": [
ttypes.NestedStructs(
rainbow=ttypes.Rainbow(colors=[ttypes.Color.ORANGE])
)
],
},
}
gen = self.struct_randomizer(ttypes.NestedStructs, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertIsNotNone(val)
def testNestedConstraints(self):
cls = self.__class__
constraints = {
"per_field": {"b": {"p_include": 0.0}},
"p_include": 1.0,
"a": {"p_true": 1.0},
"c": {
"p_include": 1.0,
"per_field": {"b": {"p_include": 0.0}},
},
}
gen = self.struct_randomizer(ttypes.StructWithOptionals, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertIsNotNone(val)
self.assertTrue(val.a)
self.assertIsNone(val.b)
self.assertIsNotNone(val.c.a)
self.assertIsNone(val.c.b)
def testEmptyUnion(self):
cls = self.__class__
constraints = {}
gen = self.struct_randomizer(ttypes.EmptyUnion, constraints)
for _ in range(cls.iterations):
val = gen.generate()
# Because the enum has no valid fields it's hard to generate
# a reasonable value. So returning None from the
# randomizer is reasonable.
self.assertIsNone(val)
def testStructContainingDefaultUnion(self):
cls = self.__class__
constraints = {}
gen = self.struct_randomizer(ttypes.NumberUnionStruct, constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertIsNotNone(val)
def testSubRanomizersHaveDefaults(self):
# Have constraints with a field that is never
# used and won't come from the existing defaults.
# Then make sure that constraint for StructWithOptionals
# doesn't go everywhere.
targeted_key = "targeted_constraint"
constraints = {targeted_key: 100}
gen = self.struct_randomizer(ttypes.StructWithOptionals, constraints)
# Yes this is pretty ugly as we have
# to reach into a undercode field, but it
# does show what constraints get propagated and what don't
for _field_name, data in gen._field_rules.items():
# The targeted key will only apply to the first randomizer
self.assertNotIn(targeted_key, data["randomizer"].constraints.keys())
# The global one is propagated to everything.
self.assertIn("global_constraint", data["randomizer"].constraints)
class TestUnionRandomizer(TestStructRandomizer, unittest.TestCase):
ttype = ttypes.IntUnion
def testAlwaysInclude(self):
cls = self.__class__
constraints = {"p_include": 1}
gen = self.struct_randomizer(constraints=constraints)
for _ in range(cls.iterations):
val = gen.generate()
# Check that field is nonzero, indicating a field is set
self.assertNotEqual(val.field, 0)
def testNeverInclude(self):
cls = self.__class__
constraints = {"p_include": 0}
gen = self.struct_randomizer(constraints=constraints)
for _ in range(cls.iterations):
val = gen.generate()
# Check that field is zero, indicating no fields are set
self.assertIsNone(
val,
(
"Because there's no way to add fields of a "
"union there should be no way to create the union."
),
)
def testSeededFuzz(self):
cls = self.__class__
seeds = [ttypes.IntUnion(a=20), ttypes.IntUnion(b=40)]
constraints = {"seeds": seeds, "p_random": 0}
gen = self.struct_randomizer(constraints=constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertIsNotNone(
val,
(
"The union should always be created. "
"We don't know the expected values, "
"just that they exist"
),
)
def testSeeded(self):
cls = self.__class__
seeds = [
{"a": 2},
{"b": 4},
ttypes.IntUnion(a=2),
ttypes.IntUnion(b=4),
]
constraints = {"seeds": seeds, "p_random": 0, "p_fuzz": 0}
gen = self.struct_randomizer(constraints=constraints)
def is_seed(val):
if val.field == 1:
return val.value == 2
elif val.field == 2:
return val.value == 4
return False
for _ in range(cls.iterations):
val = gen.generate()
self.assertTrue(
is_seed(val), msg="Not a seed: %s (%s)" % (val, val.__dict__)
)
class TestListStructRandomizer(TestStructRandomizer, unittest.TestCase):
"""
Verify that this struct type is generated correctly
struct ListStruct {
1: list<bool> a;
2: list<i16> b;
3: list<double> c;
4: list<string> d;
5: list<list<i32>> e;
6: list<map<i32, i32>> f;
7: list<set<string>> g;
}
"""
ttype = ttypes.ListStruct
def testGeneration(self):
gen = self.struct_randomizer()
val = gen.generate()
if val.a is not None:
self.assertIsInstance(val.a, list)
for elem in val.a:
self.assertIsInstance(elem, bool)
if val.b is not None:
self.assertIsInstance(val.b, list)
for elem in val.b:
self.assertIsInstance(elem, int)
if val.c is not None:
self.assertIsInstance(val.c, list)
for elem in val.c:
self.assertIsInstance(elem, float)
if val.d is not None:
self.assertIsInstance(val.d, list)
for elem in val.d:
self.assertIsInstance(elem, str)
if val.e is not None:
self.assertIsInstance(val.e, list)
for elem in val.e:
self.assertIsInstance(elem, list)
for sub_elem in elem:
self.assertIsInstance(sub_elem, int)
if val.f is not None:
self.assertIsInstance(val.f, list)
for elem in val.f:
self.assertIsInstance(elem, dict)
for k, v in elem.items():
self.assertIsInstance(k, int)
self.assertIsInstance(v, int)
if val.g is not None:
self.assertIsInstance(val.g, list)
for elem in val.g:
self.assertIsInstance(elem, set)
for sub_elem in elem:
self.assertIsInstance(sub_elem, str)
def testFieldConstraints(self):
cls = self.__class__
constraints = {
"p_include": 1.0,
"a": {"element": {"p_true": 1.0}},
"b": {"mean_length": 0.0},
"d": {"element": {"mean_length": 0.0}},
"e": {"element": {"mean_length": 0.0}},
}
gen = self.struct_randomizer(constraints=constraints)
for _ in range(cls.iterations):
val = gen.generate()
self.assertIsNotNone(val)
self.assertIsNotNone(val.a)
self.assertIsNotNone(val.b)
self.assertIsNotNone(val.c)
self.assertIsNotNone(val.d)
self.assertIsNotNone(val.e)
self.assertIsNotNone(val.f)
self.assertIsNotNone(val.g)
for elem in val.a:
self.assertTrue(elem)
self.assertEqual(len(val.b), 0)
for elem in val.d:
self.assertEqual(len(elem), 0)
for elem in val.e:
self.assertEqual(len(elem), 0)
def testSeeded(self):
seeds = [
{
"a": [True, False, False],
"b": [1, 2, 3],
"c": [1.2, 2.3],
"d": ["foo", "bar"],
"e": [[]],
"f": [{1: 2}, {3: 4}],
"g": [{"foo", "bar"}],
}
]
constraints = {"seeds": seeds, "p_random": 0, "p_fuzz": 0}
gen = self.struct_randomizer(constraints=constraints)
val = gen.generate()
for key, expected in seeds[0].items():
self.assertEqual(
expected, getattr(val, key, None), msg="%s, %s" % (val, dir(val))
)
def testFuzz(self):
cls = self.__class__