-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtests.py
More file actions
944 lines (761 loc) · 34 KB
/
Copy pathtests.py
File metadata and controls
944 lines (761 loc) · 34 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
import ast as stdlib_ast
import random
from foobar.ex import decrement_by_two
import ast as _ast
from mutation import (
AugAssignToAssign,
BreakToReturn,
Comparison,
DefinitionDrop,
ForceConditional,
InjectException,
MutateAssignment,
MutateCallArgs,
MutateContainment,
MutateContextManager,
MutateDefaultArgument,
MutateExceptionHandler,
MutateFString,
MutateGlobal,
MutateIdentity,
MutateIterator,
MutateKeyword,
MutateLambda,
MutateNumber,
MutateOperator,
MutateReturn,
MutateSlice,
MutateString,
MutateStringMethod,
MutateYield,
Mutation,
NegateCondition,
RemoveDecorator,
RemoveUnaryOp,
SwapArguments,
StatementDrop,
ZeroIteration,
iter_deltas,
Database,
diff_hash,
write_ignored_file,
mutation_ignored_gc,
CLASSIFICATION_REAL_GAP,
CLASSIFICATION_EQUIVALENT,
CLASSIFICATION_WONT_FIX,
)
from mutation import patch as mutation_patch
from mutation import cli_read
if hasattr(_ast, "Match"):
from mutation import MutateMatchCase
def test_one():
x = decrement_by_two(10)
# Example sloppy assert
assert x < 10
def test_two():
x = decrement_by_two(44)
assert x < 44
def test_mutate_string_method():
source = "def f(s):\n return s.lower()\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateStringMethod()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("s.upper()" in m for m in mutated)
def test_mutate_string_method_lstrip_multi_target():
# lstrip should produce both rstrip and removeprefix mutations
source = "def f(s):\n return s.lstrip('x')\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateStringMethod()]))
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("rstrip" in m for m in mutated)
assert any("removeprefix" in m for m in mutated)
def test_mutate_call_args():
source = "def f(a, b):\n return g(a, b)\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateCallArgs()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("g(None, b)" in m for m in mutated)
assert any("g(a, None)" in m for m in mutated)
assert any("g(b)" in m for m in mutated)
assert any("g(a)" in m for m in mutated)
def test_force_conditional():
source = "def f(x):\n if x > 0:\n return 1\n return 0\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [ForceConditional()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("if True" in m for m in mutated)
assert any("if False" in m for m in mutated)
def test_force_conditional_while():
source = "def f(x):\n while x > 0:\n x -= 1\n return x\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [ForceConditional()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("while True" in m for m in mutated)
assert any("while False" in m for m in mutated)
def test_force_conditional_assert():
source = "def f(x):\n assert x > 0\n return x\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [ForceConditional()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("assert True" in m for m in mutated)
assert any("assert False" in m for m in mutated)
def test_force_conditional_ifexp():
source = "def f(x):\n return 1 if x > 0 else 0\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [ForceConditional()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("1 if True else 0" in m for m in mutated)
assert any("1 if False else 0" in m for m in mutated)
def test_mutate_exception_handler():
source = "def f():\n try:\n pass\n except ValueError:\n pass\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateExceptionHandler()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("except Exception" in m for m in mutated)
assert all("except ValueError" not in m for m in mutated)
def test_zero_iteration():
source = "def f(items):\n for x in items:\n pass\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [ZeroIteration()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("for x in []" in m for m in mutated)
def test_remove_decorator():
source = "def decorator(f): return f\n\n@decorator\ndef f(): pass\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [RemoveDecorator()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("@decorator" not in m for m in mutated)
def test_negate_condition():
source = "def f(flag):\n if flag:\n return 1\n return 0\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [NegateCondition()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("if not flag" in m for m in mutated)
def test_mutate_return():
source = "def f(x):\n return x + 1\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateReturn()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("return None" in m for m in mutated)
assert any("return 0" in m for m in mutated)
assert any("return False" in m for m in mutated)
assert any("return ''" in m for m in mutated)
def test_mutate_lambda():
source = "f = lambda x: x * 2\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateLambda()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("lambda x: None" in m for m in mutated)
def test_mutate_assignment():
source = "def f():\n result = compute()\n return result\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateAssignment()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("result = None" in m for m in mutated)
def test_aug_assign_to_assign():
source = "def f():\n x = 0\n x += 1\n return x\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [AugAssignToAssign()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("+=" not in m and "x = 1" in m for m in mutated)
def test_remove_unary_op():
source = "def f(x):\n return not x\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [RemoveUnaryOp()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("return x" in m for m in mutated)
def test_mutate_identity():
source = "def f(x):\n return x is None\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateIdentity()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("is not" in m for m in mutated)
def test_mutate_containment():
source = "def f(x, c):\n return x in c\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateContainment()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("not in" in m for m in mutated)
def test_mutate_containment_not_in():
source = "def f(x, c):\n return x not in c\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateContainment()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("not in" not in m and "in" in m for m in mutated)
def test_break_to_return():
source = "def f():\n for x in range(10):\n break\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [BreakToReturn()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("return" in m for m in mutated)
assert all("break" not in m for m in mutated)
def test_mutate_global():
source = "x = 0\ndef f():\n global x\n x = 1\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateGlobal()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("global" not in m for m in mutated)
def test_mutate_nonlocal():
source = (
"def outer():\n x = 0\n def inner():\n nonlocal x\n x = 1\n"
)
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateGlobal()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("nonlocal" not in m for m in mutated)
def test_mutate_global_only_statement_skipped():
# sole statement in body — removing it would produce empty body → skipped
source = "x = 0\ndef f():\n global x\n"
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateGlobal()]))
assert not deltas
def test_mutate_fstring():
source = 'def f(name):\n return f"hello {name}"\n'
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateFString()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("{name}" not in m for m in mutated)
def test_mutate_fstring_multiple():
source = 'def f(a, b):\n return f"{a} and {b}"\n'
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateFString()]))
assert len(deltas) == 2
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("{a}" not in m and "{b}" in m for m in mutated)
assert any("{b}" not in m and "{a}" in m for m in mutated)
def test_mutate_context_manager():
source = "def f():\n with lock:\n do_stuff()\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateContextManager()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
# with stripped, body preserved
assert any("with" not in m.split("def")[1] for m in mutated)
assert any("do_stuff()" in m for m in mutated)
def test_mutate_context_manager_multi():
source = "def f():\n with a, b:\n pass\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateContextManager()]))
assert len(deltas) == 2
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("with a:" in m for m in mutated)
assert any("with b:" in m for m in mutated)
def test_mutate_default_argument():
source = "def f(x, y=1, z=2):\n return x + y + z\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateDefaultArgument()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("def f(x, y, z=2):" in m for m in mutated) # drop y's default
assert any("def f(x, y, z):" in m for m in mutated) # drop both defaults
def test_mutate_default_argument_kwonly():
source = "def f(x, *, y=1):\n return x + y\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateDefaultArgument()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("def f(x, *, y):" in m for m in mutated)
def test_mutate_iterator():
source = "def f(items):\n for x in items:\n pass\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateIterator()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("reversed(items)" in m for m in mutated)
assert any("shuffle" in m for m in mutated)
assert any("_mutation_seq_" in m for m in mutated)
def test_mutate_iterator_no_double_wrap():
source = "def f(items):\n for x in reversed(items):\n pass\n"
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateIterator()]))
assert not deltas
def test_mutate_iterator_async_for():
source = "async def f(items):\n async for x in items:\n pass\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateIterator()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("reversed(items)" in m for m in mutated)
def test_swap_arguments():
source = "def f(a, b):\n return g(a, b)\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [SwapArguments()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("g(b, a)" in m for m in mutated)
def test_mutate_slice():
source = "def f(a):\n return a[1:3]\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateSlice()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("a[:3]" in m for m in mutated)
assert any("a[1:]" in m for m in mutated)
def test_mutate_slice_step_negation():
# positive step → negated
source = "def f(a):\n return a[::2]\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateSlice()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("a[::-2]" in m for m in mutated)
def test_mutate_slice_step_negation_reverse():
# negative step (reversal idiom) → stripped to positive
source = "def f(a):\n return a[::-1]\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateSlice()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("a[::1]" in m for m in mutated)
def test_mutate_yield():
source = "def f():\n yield 42\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateYield()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("yield None" in m for m in mutated)
# -- regression tests for syntax-error mutations ------------------------------
def _full_coverage(source):
"""Return a coverage set spanning every line in source."""
return set(range(1, source.count("\n") + 2))
def test_no_syntax_error_mutations_empty_class_body():
"""DefinitionDrop on the sole method of a class produces an empty class
body, which is a SyntaxError. iter_deltas must not yield such deltas."""
source = "class Foo:\n def bar(self):\n pass\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
bad = []
for delta in iter_deltas(source, "test.py", coverage, list(Mutation.ALL)):
mutated = mutation_patch(delta, canonical)
try:
stdlib_ast.parse(mutated)
except SyntaxError:
bad.append(delta)
assert not bad, "iter_deltas yielded {:d} syntax-error mutation(s):\n{}".format(
len(bad), "\n---\n".join(bad)
)
def test_no_syntax_error_mutations_docstring():
"""Mutations on code with module- and function-level docstrings (the
structure of foobar/ex.py) must not produce syntax-error mutations."""
source = (
'"""Module docstring."""\n'
"\n"
"def decrement_by_two(a):\n"
' """Function docstring."""\n'
" return a - 2\n"
)
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
bad = []
for delta in iter_deltas(source, "test.py", coverage, list(Mutation.ALL)):
mutated = mutation_patch(delta, canonical)
try:
stdlib_ast.parse(mutated)
except SyntaxError:
bad.append(delta)
assert not bad, "iter_deltas yielded {:d} syntax-error mutation(s):\n{}".format(
len(bad), "\n---\n".join(bad)
)
def test_mutate_number():
source = "def f():\n return 100\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
random.seed(42)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateNumber()]))
assert deltas
for d in deltas:
m = mutation_patch(d, canonical)
assert "return 100" not in m
def test_mutate_string_skips_docstrings():
# Module, function, and class docstrings must not be mutated
source = (
'"""module doc"""\n'
"class C:\n"
' """class doc"""\n'
" def m(self):\n"
' """method doc"""\n'
" return 'payload'\n"
)
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateString()]))
mutated = [mutation_patch(d, canonical) for d in deltas]
# Only 'payload' should be mutated, never any docstring
assert all("mutated string module doc" not in m for m in mutated)
assert all("mutated string class doc" not in m for m in mutated)
assert all("mutated string method doc" not in m for m in mutated)
assert any("mutated string payload" in m for m in mutated)
def test_mutate_string():
source = "def f():\n return 'hello'\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateString()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("mutated string hello" in m for m in mutated)
def test_mutate_string_bytes():
source = "def f():\n return b'data'\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateString()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("coffeebad" in m for m in mutated)
def test_mutate_keyword_bool_constants():
source = "def f():\n return True\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateKeyword()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("return False" in m for m in mutated)
assert any("return None" in m for m in mutated)
def test_mutate_keyword_bool_op():
source = "def f(a, b):\n return a and b\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateKeyword()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("a or b" in m for m in mutated)
def test_mutate_keyword_flow():
source = "def f(items):\n for x in items:\n break\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateKeyword()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("continue" in m for m in mutated)
assert any("pass" in m for m in mutated)
def test_comparison():
source = "def f(x):\n return x > 0\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [Comparison()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("not (x > 0)" in m or "not x > 0" in m for m in mutated)
def test_mutate_operator_binop():
source = "def f(a, b):\n return a + b\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateOperator()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("a - b" in m for m in mutated)
assert any("a * b" in m for m in mutated)
def test_mutate_operator_compare():
source = "def f(a, b):\n return a < b\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateOperator()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("a > b" in m for m in mutated)
assert any("a <= b" in m for m in mutated)
assert any("a == b" in m for m in mutated)
# -- Database and helper tests -------------------------------------------------
def _make_db(tmp_path):
"""Create a Database at a temp path with one mutation and one result."""
import zlib
from mutation import make_uid
db = Database(str(tmp_path / "test.mutation.db"))
uid = make_uid()
diff = b"--- a/f.py\n+++ b/f.py\n@@ -1 +1 @@\n-x = 1\n+x = 2\n"
db.store_mutations([(uid, "f.py", zlib.compress(diff))])
db.set_result(uid, 0) # survived
return db, uid, diff
def test_diff_hash():
h = diff_hash("hello")
assert len(h) == 64 # sha256 hex digest
assert h == diff_hash("hello") # deterministic
assert h != diff_hash("world")
def test_write_ignored_file(tmp_path):
diff_text = "--- a/f.py\n+++ b/f.py\n@@ -1 +1 @@\n-x = 1\n+x = 2\n"
h = write_ignored_file(str(tmp_path), diff_text, "f.py", "always zero")
ignored = tmp_path / ".mutations.ignored" / "{}.diff".format(h)
assert ignored.exists()
content = ignored.read_text()
assert "Case 3: equivalent mutation" in content
assert "always zero" in content
assert diff_text in content
def test_write_ignored_file_no_reason(tmp_path):
diff_text = "--- a/f.py\n+++ b/f.py\n@@ -1 +1 @@\n-x = 1\n+x = 2\n"
h = write_ignored_file(str(tmp_path), diff_text, "f.py", "")
ignored = tmp_path / ".mutations.ignored" / "{}.diff".format(h)
content = ignored.read_text()
assert " \u2014 " not in content # no separator when no reason
def test_database_count_mutations(tmp_path):
db, uid, _ = _make_db(tmp_path)
with db:
assert db.count_mutations() == 1
def test_database_set_classification(tmp_path):
db, uid, _ = _make_db(tmp_path)
with db:
db.set_classification(uid, CLASSIFICATION_REAL_GAP)
counts = db.get_classification_counts()
assert counts[CLASSIFICATION_REAL_GAP] == 1
def test_database_list_results_for_replay_unclassified(tmp_path):
db, uid, _ = _make_db(tmp_path)
with db:
rows = db.list_results_for_replay()
assert any(r[0] == uid for r in rows)
def test_database_list_results_for_replay_wont_fix_excluded(tmp_path):
db, uid, _ = _make_db(tmp_path)
with db:
db.set_classification(uid, CLASSIFICATION_WONT_FIX)
rows = db.list_results_for_replay()
assert not any(r[0] == uid for r in rows)
def test_database_list_results_for_replay_equivalent_excluded(tmp_path):
db, uid, _ = _make_db(tmp_path)
with db:
db.set_classification(uid, CLASSIFICATION_EQUIVALENT)
rows = db.list_results_for_replay()
assert not any(r[0] == uid for r in rows)
def test_mutation_ignored_gc_removes_stale(tmp_path):
diff_text = "--- a/nosuchfile.py\n+++ b/nosuchfile.py\n@@ -1 +1 @@\n-x=1\n+x=2\n"
write_ignored_file(str(tmp_path), diff_text, "nosuchfile.py", "")
assert len(list((tmp_path / ".mutations.ignored").glob("*.diff"))) == 1
mutation_ignored_gc(str(tmp_path))
assert len(list((tmp_path / ".mutations.ignored").glob("*.diff"))) == 0
def test_mutation_ignored_gc_keeps_valid(tmp_path):
from difflib import unified_diff
py_file = tmp_path / "m.py"
py_file.write_text("x = 1\n")
source = stdlib_ast.unparse(stdlib_ast.parse("x = 1\n"))
target = stdlib_ast.unparse(stdlib_ast.parse("x = 2\n"))
diff_text = "\n".join(
unified_diff(
source.split("\n"),
target.split("\n"),
fromfile="a/m.py",
tofile="b/m.py",
lineterm="",
)
)
write_ignored_file(str(tmp_path), diff_text, "m.py", "")
mutation_ignored_gc(str(tmp_path))
assert len(list((tmp_path / ".mutations.ignored").glob("*.diff"))) == 1
def test_mutation_ignored_gc_no_dir(tmp_path):
# Should not raise when .mutations.ignored/ doesn't exist
mutation_ignored_gc(str(tmp_path))
# -- cli_read tests -----------------------------------------------------------
def test_cli_read_keywords_standalone_extra():
# ~check-cli-00: full form with '--' separator
keywords, standalone, extra = cli_read(
[
"--foo=bar",
"--qux",
"-vvv",
"positional",
"arguments",
"--",
"olive",
"extra",
]
)
assert keywords == [("--foo", "bar"), ("--qux", True), ("-vvv", True)]
assert standalone == ["positional", "arguments"]
assert extra == ["olive", "extra"]
def test_cli_read_no_extra():
# ~check-cli-01: no '--' separator → extra is empty
keywords, standalone, extra = cli_read(
["--foo=bar", "--qux", "-vvv", "positional", "arguments"]
)
assert keywords == [("--foo", "bar"), ("--qux", True), ("-vvv", True)]
assert standalone == ["positional", "arguments"]
assert extra == []
def test_cli_read_empty():
keywords, standalone, extra = cli_read([])
assert keywords == []
assert standalone == []
assert extra == []
def test_cli_read_only_positional():
keywords, standalone, extra = cli_read(["alpha", "bravo", "charlie"])
assert keywords == []
assert standalone == ["alpha", "bravo", "charlie"]
assert extra == []
def test_cli_read_only_keywords():
keywords, standalone, extra = cli_read(["--verbose", "--output=file.txt"])
assert keywords == [("--verbose", True), ("--output", "file.txt")]
assert standalone == []
assert extra == []
def test_cli_read_bare_separator():
# '--' with nothing after it → empty extra
keywords, standalone, extra = cli_read(["--flag", "pos", "--"])
assert keywords == [("--flag", True)]
assert standalone == ["pos"]
assert extra == []
def test_cli_read_separator_at_start():
# '--' at the start → everything after is extra, nothing before
keywords, standalone, extra = cli_read(["--", "a", "b"])
assert keywords == []
assert standalone == []
assert extra == ["a", "b"]
def test_cli_read_keyword_empty_value():
# '--key=' with empty string value
keywords, standalone, extra = cli_read(["--key="])
assert keywords == [("--key", "")]
assert standalone == []
assert extra == []
def test_cli_read_value_contains_equals():
# value itself contains '=' → only the first '=' splits key from value
keywords, standalone, extra = cli_read(["--expr=a=b"])
assert keywords == [("--expr", "a=b")]
assert standalone == []
assert extra == []
def test_cli_read_order_preserved():
# interleaved flags and positionals preserve insertion order
keywords, standalone, extra = cli_read(["pos1", "--a", "pos2", "--b=1", "pos3"])
assert keywords == [("--a", True), ("--b", "1")]
assert standalone == ["pos1", "pos2", "pos3"]
assert extra == []
def test_statement_drop():
source = "def f(x):\n x = x + 1\n return x\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [StatementDrop()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("pass" in m for m in mutated)
def test_statement_drop_skips_pass_and_expr():
# pass, bare expressions, and def/class nodes should not be dropped
source = "def f():\n pass\n"
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [StatementDrop()]))
assert not deltas
def test_definition_drop():
source = "def f(): pass\ndef g(): pass\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [DefinitionDrop()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("def f" not in m for m in mutated)
assert any("def g" not in m for m in mutated)
def test_definition_drop_sole_definition_skipped():
# Only one definition in body — removing it would leave an empty body.
source = "def f(): pass\n"
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [DefinitionDrop()]))
assert not deltas
def test_inject_exception_subscript_string_key():
source = "def f(d):\n return d['key']\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [InjectException()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("KeyError" in m for m in mutated)
def test_inject_exception_subscript_int_key():
source = "def f(lst):\n return lst[0]\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [InjectException()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("IndexError" in m for m in mutated)
def test_inject_exception_division():
source = "def f(a, b):\n return a / b\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [InjectException()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("ZeroDivisionError" in m for m in mutated)
def test_inject_exception_guarded_skipped():
# Exception injection inside a matching except handler should be skipped.
source = (
"def f(d):\n"
" try:\n"
" return d['key']\n"
" except KeyError:\n"
" return None\n"
)
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [InjectException()]))
mutated = [mutation_patch(d, canonical) for d in deltas]
assert all("KeyError" not in m for m in mutated)
def test_inject_exception_call_int():
source = "def f(s):\n return int(s)\n"
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [InjectException()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("ValueError" in m for m in mutated)
if hasattr(_ast, "Match"):
def test_mutate_match_case():
source = (
"def f(x):\n"
" match x:\n"
" case 1:\n"
" return 'one'\n"
" case 2:\n"
" return 'two'\n"
)
canonical = stdlib_ast.unparse(stdlib_ast.parse(source))
coverage = _full_coverage(source)
deltas = list(iter_deltas(source, "test.py", coverage, [MutateMatchCase()]))
assert deltas
mutated = [mutation_patch(d, canonical) for d in deltas]
assert any("case 1:" not in m for m in mutated)
assert any("case 2:" not in m for m in mutated)