-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathtest_auto_mark.py
More file actions
1085 lines (914 loc) · 36.8 KB
/
test_auto_mark.py
File metadata and controls
1085 lines (914 loc) · 36.8 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
"""Tests for auto_mark.py - test result parsing and auto-marking."""
import ast
import pathlib
import subprocess
import tempfile
import unittest
from unittest import mock
from update_lib.cmd_auto_mark import (
Test,
TestResult,
TestRunError,
_expand_stripped_to_children,
_is_super_call_only,
apply_test_changes,
auto_mark_directory,
auto_mark_file,
collect_test_changes,
extract_test_methods,
parse_results,
path_to_test_parts,
remove_expected_failures,
strip_reasonless_expected_failures,
)
from update_lib.patch_spec import COMMENT
def _make_result(stdout: str) -> subprocess.CompletedProcess:
return subprocess.CompletedProcess(
args=["test"], returncode=0, stdout=stdout, stderr=""
)
# -- fixtures shared across inheritance-aware tests --
BASE_TWO_CHILDREN = """import unittest
class Base:
def test_foo(self):
pass
class ChildA(Base, unittest.TestCase):
pass
class ChildB(Base, unittest.TestCase):
pass
"""
BASE_TWO_CHILDREN_ONE_OVERRIDE = """import unittest
class Base:
def test_foo(self):
pass
class ChildA(Base, unittest.TestCase):
pass
class ChildB(Base, unittest.TestCase):
def test_foo(self):
# own implementation
pass
"""
class TestParseResults(unittest.TestCase):
"""Tests for parse_results function."""
def test_parse_fail_and_error(self):
"""FAIL and ERROR are collected; ok is ignored."""
stdout = """\
Run 3 tests sequentially
test_one (test.test_example.TestA.test_one) ... FAIL
test_two (test.test_example.TestA.test_two) ... ok
test_three (test.test_example.TestB.test_three) ... ERROR
-----------
"""
result = parse_results(_make_result(stdout))
self.assertEqual(len(result.tests), 2)
by_name = {t.name: t for t in result.tests}
self.assertEqual(by_name["test_one"].path, "test.test_example.TestA.test_one")
self.assertEqual(by_name["test_one"].result, "fail")
self.assertEqual(by_name["test_three"].result, "error")
def test_parse_unexpected_success(self):
stdout = """\
Run 1 tests sequentially
test_foo (test.test_example.TestClass.test_foo) ... unexpected success
-----------
UNEXPECTED SUCCESS: test_foo (test.test_example.TestClass.test_foo)
"""
result = parse_results(_make_result(stdout))
self.assertEqual(len(result.unexpected_successes), 1)
self.assertEqual(result.unexpected_successes[0].name, "test_foo")
self.assertEqual(
result.unexpected_successes[0].path, "test.test_example.TestClass.test_foo"
)
def test_parse_tests_result(self):
result = parse_results(_make_result("== Tests result: FAILURE ==\n"))
self.assertEqual(result.tests_result, "FAILURE")
def test_parse_crashed_run_no_tests_result(self):
"""Test results are still parsed when the runner crashes (no Tests result line)."""
stdout = """\
Run 1 test sequentially in a single process
0:00:00 [1/1] test_ast
test_foo (test.test_ast.test_ast.TestA.test_foo) ... FAIL
test_bar (test.test_ast.test_ast.TestA.test_bar) ... ok
test_baz (test.test_ast.test_ast.TestB.test_baz) ... ERROR
"""
result = parse_results(_make_result(stdout))
self.assertEqual(result.tests_result, "")
self.assertEqual(len(result.tests), 2)
names = {t.name for t in result.tests}
self.assertIn("test_foo", names)
self.assertIn("test_baz", names)
def test_parse_crashed_run_has_unexpected_success(self):
"""Unexpected successes are parsed even without Tests result line."""
stdout = """\
Run 1 test sequentially in a single process
0:00:00 [1/1] test_ast
test_foo (test.test_ast.test_ast.TestA.test_foo) ... unexpected success
UNEXPECTED SUCCESS: test_foo (test.test_ast.test_ast.TestA.test_foo)
"""
result = parse_results(_make_result(stdout))
self.assertEqual(result.tests_result, "")
self.assertEqual(len(result.unexpected_successes), 1)
def test_parse_error_messages(self):
"""Single and multiple error messages are parsed from tracebacks."""
stdout = """\
Run 2 tests sequentially
test_foo (test.test_example.TestClass.test_foo) ... FAIL
test_bar (test.test_example.TestClass.test_bar) ... ERROR
-----------
======================================================================
FAIL: test_foo (test.test_example.TestClass.test_foo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test.py", line 10, in test_foo
self.assertEqual(1, 2)
AssertionError: 1 != 2
======================================================================
ERROR: test_bar (test.test_example.TestClass.test_bar)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test.py", line 20, in test_bar
raise ValueError("oops")
ValueError: oops
======================================================================
"""
result = parse_results(_make_result(stdout))
by_name = {t.name: t for t in result.tests}
self.assertEqual(by_name["test_foo"].error_message, "AssertionError: 1 != 2")
self.assertEqual(by_name["test_bar"].error_message, "ValueError: oops")
def test_parse_directory_test_multiple_submodules(self):
"""Failures across submodule boundaries are all detected."""
stdout = """\
Run 3 tests sequentially
0:00:00 [ 1/3] test_asyncio.test_buffered_proto
test_ok (test.test_asyncio.test_buffered_proto.TestProto.test_ok) ... ok
----------------------------------------------------------------------
Ran 1 tests in 0.1s
OK
0:00:01 [ 2/3] test_asyncio.test_events
test_create (test.test_asyncio.test_events.TestEvents.test_create) ... FAIL
----------------------------------------------------------------------
Ran 1 tests in 0.2s
FAILED (failures=1)
0:00:02 [ 3/3] test_asyncio.test_tasks
test_gather (test.test_asyncio.test_tasks.TestTasks.test_gather) ... ERROR
----------------------------------------------------------------------
Ran 1 tests in 0.3s
FAILED (errors=1)
== Tests result: FAILURE ==
"""
result = parse_results(_make_result(stdout))
self.assertEqual(len(result.tests), 2)
names = {t.name for t in result.tests}
self.assertIn("test_create", names)
self.assertIn("test_gather", names)
self.assertEqual(result.tests_result, "FAILURE")
def test_parse_multiline_test_with_docstring(self):
"""Two-line output (test_name + docstring ... RESULT) is handled."""
stdout = """\
Run 3 tests sequentially
test_ok (test.test_example.TestClass.test_ok) ... ok
test_with_doc (test.test_example.TestClass.test_with_doc)
Test that something works ... ERROR
test_normal_fail (test.test_example.TestClass.test_normal_fail) ... FAIL
"""
result = parse_results(_make_result(stdout))
self.assertEqual(len(result.tests), 2)
names = {t.name for t in result.tests}
self.assertIn("test_with_doc", names)
self.assertIn("test_normal_fail", names)
test_doc = next(t for t in result.tests if t.name == "test_with_doc")
self.assertEqual(test_doc.path, "test.test_example.TestClass.test_with_doc")
self.assertEqual(test_doc.result, "error")
class TestPathToTestParts(unittest.TestCase):
def test_simple_path(self):
self.assertEqual(
path_to_test_parts("test.test_foo.TestClass.test_method"),
["TestClass", "test_method"],
)
def test_nested_path(self):
self.assertEqual(
path_to_test_parts("test.test_foo.test_bar.TestClass.test_method"),
["TestClass", "test_method"],
)
class TestCollectTestChanges(unittest.TestCase):
def test_collect_failures_and_error_messages(self):
"""Failures and error messages are collected; empty messages are omitted."""
results = TestResult()
results.tests = [
Test(
name="test_foo",
path="test.test_example.TestClass.test_foo",
result="fail",
error_message="AssertionError: 1 != 2",
),
Test(
name="test_bar",
path="test.test_example.TestClass.test_bar",
result="error",
error_message="",
),
]
failing, successes, error_messages = collect_test_changes(results)
self.assertEqual(
failing, {("TestClass", "test_foo"), ("TestClass", "test_bar")}
)
self.assertEqual(successes, set())
self.assertEqual(len(error_messages), 1)
self.assertEqual(
error_messages[("TestClass", "test_foo")], "AssertionError: 1 != 2"
)
def test_collect_unexpected_successes(self):
results = TestResult()
results.unexpected_successes = [
Test(
name="test_foo",
path="test.test_example.TestClass.test_foo",
result="unexpected_success",
),
]
_, successes, _ = collect_test_changes(results)
self.assertEqual(successes, {("TestClass", "test_foo")})
def test_module_prefix_filtering(self):
"""Prefix filters with both short and 'test.' prefix formats."""
results = TestResult()
results.tests = [
Test(name="test_foo", path="test_a.TestClass.test_foo", result="fail"),
Test(
name="test_bar",
path="test.test_dataclasses.TestCase.test_bar",
result="fail",
),
Test(
name="test_baz",
path="test.test_other.TestOther.test_baz",
result="fail",
),
]
failing_a, _, _ = collect_test_changes(results, module_prefix="test_a.")
self.assertEqual(failing_a, {("TestClass", "test_foo")})
failing_dc, _, _ = collect_test_changes(
results, module_prefix="test.test_dataclasses."
)
self.assertEqual(failing_dc, {("TestCase", "test_bar")})
def test_collect_init_module_matching(self):
"""__init__.py tests match after stripping .__init__ from the prefix."""
results = TestResult()
results.tests = [
Test(
name="test_field_repr",
path="test.test_dataclasses.TestCase.test_field_repr",
result="fail",
),
]
module_prefix = "test_dataclasses.__init__"
if module_prefix.endswith(".__init__"):
module_prefix = module_prefix[:-9]
module_prefix = "test." + module_prefix + "."
failing, _, _ = collect_test_changes(results, module_prefix=module_prefix)
self.assertEqual(failing, {("TestCase", "test_field_repr")})
class TestExtractTestMethods(unittest.TestCase):
def test_extract_methods(self):
"""Extracts from single and multiple classes."""
code = """
class TestA(unittest.TestCase):
def test_a(self):
pass
class TestB(unittest.TestCase):
def test_b(self):
pass
"""
methods = extract_test_methods(code)
self.assertEqual(methods, {("TestA", "test_a"), ("TestB", "test_b")})
def test_extract_syntax_error_returns_empty(self):
self.assertEqual(extract_test_methods("this is not valid python {"), set())
class TestRemoveExpectedFailures(unittest.TestCase):
def test_remove_comment_before(self):
code = f"""import unittest
class TestFoo(unittest.TestCase):
# {COMMENT}
@unittest.expectedFailure
def test_one(self):
pass
"""
result = remove_expected_failures(code, {("TestFoo", "test_one")})
self.assertNotIn("@unittest.expectedFailure", result)
self.assertIn("def test_one(self):", result)
def test_remove_inline_comment(self):
code = f"""import unittest
class TestFoo(unittest.TestCase):
@unittest.expectedFailure # {COMMENT}
def test_one(self):
pass
"""
result = remove_expected_failures(code, {("TestFoo", "test_one")})
self.assertNotIn("@unittest.expectedFailure", result)
def test_remove_super_call_method(self):
"""Super-call-only override is removed entirely (sync)."""
code = f"""import unittest
class TestFoo(unittest.TestCase):
# {COMMENT}
@unittest.expectedFailure
def test_one(self):
return super().test_one()
"""
result = remove_expected_failures(code, {("TestFoo", "test_one")})
self.assertNotIn("def test_one", result)
def test_remove_async_super_call_override(self):
"""Super-call-only override is removed entirely (async)."""
code = f"""import unittest
class BaseTest:
async def test_async_one(self):
pass
class TestChild(BaseTest, unittest.TestCase):
# {COMMENT}
@unittest.expectedFailure
async def test_async_one(self):
return await super().test_async_one()
"""
result = remove_expected_failures(code, {("TestChild", "test_async_one")})
self.assertNotIn("return await super().test_async_one()", result)
self.assertNotIn("@unittest.expectedFailure", result)
self.assertIn("class TestChild", result)
self.assertIn("async def test_async_one(self):", result)
def test_remove_with_comment_after(self):
"""Reason comment on the line after the decorator is also removed."""
code = f"""import unittest
class TestFoo(unittest.TestCase):
@unittest.expectedFailure # {COMMENT}
# RuntimeError: something went wrong
def test_one(self):
pass
"""
result = remove_expected_failures(code, {("TestFoo", "test_one")})
self.assertNotIn("@unittest.expectedFailure", result)
self.assertNotIn("RuntimeError: something went wrong", result)
self.assertIn("def test_one(self):", result)
def test_no_removal_without_comment(self):
"""Decorators without our COMMENT marker are left untouched."""
code = """import unittest
class TestFoo(unittest.TestCase):
@unittest.expectedFailure
def test_one(self):
pass
"""
result = remove_expected_failures(code, {("TestFoo", "test_one")})
self.assertIn("@unittest.expectedFailure", result)
class TestStripReasonlessExpectedFailures(unittest.TestCase):
def test_strip_reason_formats(self):
"""Strips both inline-comment and comment-before formats when no reason."""
for label, code in [
(
"inline",
f"""import unittest
class TestFoo(unittest.TestCase):
@unittest.expectedFailure # {COMMENT}
def test_one(self):
pass
""",
),
(
"comment-before",
f"""import unittest
class TestFoo(unittest.TestCase):
# {COMMENT}
@unittest.expectedFailure
def test_one(self):
pass
""",
),
]:
with self.subTest(label):
result, stripped = strip_reasonless_expected_failures(code)
self.assertNotIn("@unittest.expectedFailure", result)
self.assertIn("def test_one(self):", result)
self.assertEqual(stripped, {("TestFoo", "test_one")})
def test_keep_with_reason(self):
code = f"""import unittest
class TestFoo(unittest.TestCase):
@unittest.expectedFailure # {COMMENT}; AssertionError: 1 != 2
def test_one(self):
pass
"""
result, stripped = strip_reasonless_expected_failures(code)
self.assertIn("@unittest.expectedFailure", result)
self.assertEqual(stripped, set())
def test_strip_with_comment_after(self):
"""Old-format reason comment on the next line is also removed."""
code = f"""import unittest
class TestFoo(unittest.TestCase):
@unittest.expectedFailure # {COMMENT}
# RuntimeError: something went wrong
def test_one(self):
pass
"""
result, stripped = strip_reasonless_expected_failures(code)
self.assertNotIn("RuntimeError", result)
self.assertIn("def test_one(self):", result)
self.assertEqual(stripped, {("TestFoo", "test_one")})
def test_strip_super_call_override(self):
"""Super-call overrides are removed entirely (both comment formats)."""
for label, code in [
(
"comment-before",
f"""import unittest
class _BaseTests:
def test_foo(self):
pass
class TestChild(_BaseTests, unittest.TestCase):
# {COMMENT}
@unittest.expectedFailure
def test_foo(self):
return super().test_foo()
""",
),
(
"inline",
f"""import unittest
class _BaseTests:
def test_foo(self):
pass
class TestChild(_BaseTests, unittest.TestCase):
@unittest.expectedFailure # {COMMENT}
def test_foo(self):
return super().test_foo()
""",
),
]:
with self.subTest(label):
result, stripped = strip_reasonless_expected_failures(code)
self.assertNotIn("return super().test_foo()", result)
self.assertNotIn("@unittest.expectedFailure", result)
self.assertEqual(stripped, {("TestChild", "test_foo")})
self.assertIn("class _BaseTests:", result)
def test_no_strip_without_comment(self):
"""Markers without our COMMENT are NOT stripped."""
code = """import unittest
class TestFoo(unittest.TestCase):
@unittest.expectedFailure
def test_one(self):
pass
"""
result, stripped = strip_reasonless_expected_failures(code)
self.assertIn("@unittest.expectedFailure", result)
self.assertEqual(stripped, set())
def test_mixed_with_and_without_reason(self):
code = f"""import unittest
class TestFoo(unittest.TestCase):
@unittest.expectedFailure # {COMMENT}
def test_no_reason(self):
pass
@unittest.expectedFailure # {COMMENT}; has a reason
def test_has_reason(self):
pass
"""
result, stripped = strip_reasonless_expected_failures(code)
self.assertEqual(stripped, {("TestFoo", "test_no_reason")})
self.assertIn("has a reason", result)
self.assertEqual(result.count("@unittest.expectedFailure"), 1)
class TestExpandStrippedToChildren(unittest.TestCase):
def test_parent_to_children(self):
"""Parent stripped → all/partial failing children returned."""
stripped = {("Base", "test_foo")}
all_children = {("ChildA", "test_foo"), ("ChildB", "test_foo")}
# All children fail
result = _expand_stripped_to_children(BASE_TWO_CHILDREN, stripped, all_children)
self.assertEqual(result, all_children)
# Only one child fails
partial = {("ChildA", "test_foo")}
result = _expand_stripped_to_children(BASE_TWO_CHILDREN, stripped, partial)
self.assertEqual(result, partial)
def test_direct_match(self):
code = """import unittest
class TestFoo(unittest.TestCase):
def test_one(self):
pass
"""
s = {("TestFoo", "test_one")}
self.assertEqual(_expand_stripped_to_children(code, s, s), s)
def test_child_with_own_override_excluded(self):
stripped = {("Base", "test_foo")}
all_failing = {("ChildA", "test_foo"), ("ChildB", "test_foo")}
result = _expand_stripped_to_children(
BASE_TWO_CHILDREN_ONE_OVERRIDE, stripped, all_failing
)
# ChildA inherits → included; ChildB has own method → excluded
self.assertEqual(result, {("ChildA", "test_foo")})
class TestApplyTestChanges(unittest.TestCase):
def test_apply_failing_tests(self):
code = """import unittest
class TestFoo(unittest.TestCase):
def test_one(self):
pass
"""
result = apply_test_changes(code, {("TestFoo", "test_one")}, set())
self.assertIn("@unittest.expectedFailure", result)
self.assertIn(COMMENT, result)
def test_apply_removes_unexpected_success(self):
code = f"""import unittest
class TestFoo(unittest.TestCase):
# {COMMENT}
@unittest.expectedFailure
def test_one(self):
pass
"""
result = apply_test_changes(code, set(), {("TestFoo", "test_one")})
self.assertNotIn("@unittest.expectedFailure", result)
self.assertIn("def test_one(self):", result)
def test_apply_both_changes(self):
code = f"""import unittest
class TestFoo(unittest.TestCase):
def test_one(self):
pass
# {COMMENT}
@unittest.expectedFailure
def test_two(self):
pass
"""
result = apply_test_changes(
code, {("TestFoo", "test_one")}, {("TestFoo", "test_two")}
)
self.assertEqual(result.count("@unittest.expectedFailure"), 1)
def test_apply_with_error_message(self):
code = """import unittest
class TestFoo(unittest.TestCase):
def test_one(self):
pass
"""
result = apply_test_changes(
code,
{("TestFoo", "test_one")},
set(),
{("TestFoo", "test_one"): "AssertionError: 1 != 2"},
)
self.assertIn("AssertionError: 1 != 2", result)
self.assertIn(COMMENT, result)
class TestConsolidateToParent(unittest.TestCase):
def test_all_children_fail_marks_parent_with_message(self):
"""All subclasses fail → marks parent; error message is transferred."""
failing = {("ChildA", "test_foo"), ("ChildB", "test_foo")}
error_messages = {("ChildA", "test_foo"): "RuntimeError: boom"}
result = apply_test_changes(BASE_TWO_CHILDREN, failing, set(), error_messages)
self.assertEqual(result.count("@unittest.expectedFailure"), 1)
self.assertNotIn("return super()", result)
self.assertIn("RuntimeError: boom", result)
def test_partial_children_fail_marks_children(self):
result = apply_test_changes(BASE_TWO_CHILDREN, {("ChildA", "test_foo")}, set())
self.assertIn("return super().test_foo()", result)
self.assertEqual(result.count("@unittest.expectedFailure"), 1)
def test_child_with_own_override_not_consolidated(self):
failing = {("ChildA", "test_foo"), ("ChildB", "test_foo")}
result = apply_test_changes(BASE_TWO_CHILDREN_ONE_OVERRIDE, failing, set())
self.assertEqual(result.count("@unittest.expectedFailure"), 2)
def test_strip_then_consolidate_restores_parent_marker(self):
"""End-to-end: strip parent marker → child failures → re-mark on parent."""
code = f"""import unittest
class _BaseTests:
@unittest.expectedFailure # {COMMENT}
def test_foo(self):
pass
class ChildA(_BaseTests, unittest.TestCase):
pass
class ChildB(_BaseTests, unittest.TestCase):
pass
"""
stripped_code, stripped_tests = strip_reasonless_expected_failures(code)
self.assertEqual(stripped_tests, {("_BaseTests", "test_foo")})
all_failing = {("ChildA", "test_foo"), ("ChildB", "test_foo")}
error_messages = {("ChildA", "test_foo"): "RuntimeError: boom"}
to_remark = _expand_stripped_to_children(
stripped_code, stripped_tests, all_failing
)
self.assertEqual(to_remark, all_failing)
result = apply_test_changes(stripped_code, to_remark, set(), error_messages)
self.assertIn("RuntimeError: boom", result)
self.assertEqual(result.count("@unittest.expectedFailure"), 1)
self.assertNotIn("return super()", result)
class TestSmartAutoMarkFiltering(unittest.TestCase):
"""Tests for smart auto-mark filtering (new tests vs regressions)."""
@staticmethod
def _filter(all_failing, original, current):
new = current - original
to_mark = {t for t in all_failing if t in new}
return to_mark, all_failing - to_mark
def test_new_vs_regression(self):
"""New failures are marked; existing (regression) failures are not."""
original = {("TestFoo", "test_old1"), ("TestFoo", "test_old2")}
current = original | {("TestFoo", "test_new1"), ("TestFoo", "test_new2")}
all_failing = {("TestFoo", "test_old1"), ("TestFoo", "test_new1")}
to_mark, regressions = self._filter(all_failing, original, current)
self.assertEqual(to_mark, {("TestFoo", "test_new1")})
self.assertEqual(regressions, {("TestFoo", "test_old1")})
# Edge: all new → all marked
to_mark, regressions = self._filter(all_failing, set(), current)
self.assertEqual(to_mark, all_failing)
self.assertEqual(regressions, set())
# Edge: all old → nothing marked
to_mark, regressions = self._filter(all_failing, current, current)
self.assertEqual(to_mark, set())
self.assertEqual(regressions, all_failing)
def test_filters_across_classes(self):
original = {("TestA", "test_a"), ("TestB", "test_b")}
current = original | {("TestA", "test_new_a"), ("TestC", "test_c")}
all_failing = {
("TestA", "test_a"), # regression
("TestA", "test_new_a"), # new
("TestC", "test_c"), # new (new class)
}
to_mark, regressions = self._filter(all_failing, original, current)
self.assertEqual(to_mark, {("TestA", "test_new_a"), ("TestC", "test_c")})
self.assertEqual(regressions, {("TestA", "test_a")})
class TestIsSuperCallOnly(unittest.TestCase):
@staticmethod
def _parse_method(code):
tree = ast.parse(code)
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
return node
return None
def test_sync(self):
cases = [
("return super().test_one()", True),
("return super().test_two()", False), # mismatched name
("pass", False), # regular body
("x = 1\n return super().test_one()", False), # multiple stmts
]
for body, expected in cases:
with self.subTest(body=body):
code = f"""
class Foo:
def test_one(self):
{body}
"""
self.assertEqual(
_is_super_call_only(self._parse_method(code)), expected
)
def test_async(self):
cases = [
("return await super().test_one()", True),
("return await super().test_two()", False),
("return super().test_one()", True), # sync call in async method
]
for body, expected in cases:
with self.subTest(body=body):
code = f"""
class Foo:
async def test_one(self):
{body}
"""
self.assertEqual(
_is_super_call_only(self._parse_method(code)), expected
)
class TestAutoMarkFileWithCrashedRun(unittest.TestCase):
"""auto_mark_file should process partial results when test runner crashes."""
CRASHED_STDOUT = """\
Run 1 test sequentially in a single process
0:00:00 [1/1] test_example
test_foo (test.test_example.TestA.test_foo) ... FAIL
test_bar (test.test_example.TestA.test_bar) ... ok
======================================================================
FAIL: test_foo (test.test_example.TestA.test_foo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test.py", line 10, in test_foo
self.assertEqual(1, 2)
AssertionError: 1 != 2
"""
def test_auto_mark_file_crashed_run(self):
"""auto_mark_file processes results even when tests_result is empty (crash)."""
test_code = f"""import unittest
class TestA(unittest.TestCase):
def test_foo(self):
pass
def test_bar(self):
pass
"""
with tempfile.TemporaryDirectory() as tmpdir:
test_file = pathlib.Path(tmpdir) / "test_example.py"
test_file.write_text(test_code)
mock_result = TestResult()
mock_result.tests_result = ""
mock_result.tests = [
Test(
name="test_foo",
path="test.test_example.TestA.test_foo",
result="fail",
error_message="AssertionError: 1 != 2",
),
]
with mock.patch(
"update_lib.cmd_auto_mark.run_test", return_value=mock_result
):
added, removed, regressions = auto_mark_file(
test_file, mark_failure=True, verbose=False
)
self.assertEqual(added, 1)
contents = test_file.read_text()
self.assertIn("expectedFailure", contents)
def test_auto_mark_file_no_results_at_all_raises(self):
"""auto_mark_file raises TestRunError when there are zero parsed results."""
test_code = """import unittest
class TestA(unittest.TestCase):
def test_foo(self):
pass
"""
with tempfile.TemporaryDirectory() as tmpdir:
test_file = pathlib.Path(tmpdir) / "test_example.py"
test_file.write_text(test_code)
mock_result = TestResult()
mock_result.tests_result = ""
mock_result.tests = []
mock_result.stdout = "some crash output"
with mock.patch(
"update_lib.cmd_auto_mark.run_test", return_value=mock_result
):
with self.assertRaises(TestRunError):
auto_mark_file(test_file, verbose=False)
class TestAutoMarkDirectoryWithCrashedRun(unittest.TestCase):
"""auto_mark_directory should process partial results when test runner crashes."""
def test_auto_mark_directory_crashed_run(self):
"""auto_mark_directory processes results even when tests_result is empty."""
test_code = f"""import unittest
class TestA(unittest.TestCase):
def test_foo(self):
pass
"""
with tempfile.TemporaryDirectory() as tmpdir:
test_dir = pathlib.Path(tmpdir) / "test_example"
test_dir.mkdir()
test_file = test_dir / "test_sub.py"
test_file.write_text(test_code)
mock_result = TestResult()
mock_result.tests_result = ""
mock_result.tests = [
Test(
name="test_foo",
path="test.test_example.test_sub.TestA.test_foo",
result="fail",
error_message="AssertionError: oops",
),
]
with (
mock.patch(
"update_lib.cmd_auto_mark.run_test", return_value=mock_result
),
mock.patch(
"update_lib.cmd_auto_mark.get_test_module_name",
side_effect=lambda p: (
"test_example" if p == test_dir else "test_example.test_sub"
),
),
):
added, removed, regressions = auto_mark_directory(
test_dir, mark_failure=True, verbose=False
)
self.assertEqual(added, 1)
contents = test_file.read_text()
self.assertIn("expectedFailure", contents)
def test_auto_mark_directory_no_results_raises(self):
"""auto_mark_directory raises TestRunError when zero results."""
with tempfile.TemporaryDirectory() as tmpdir:
test_dir = pathlib.Path(tmpdir) / "test_example"
test_dir.mkdir()
test_file = test_dir / "test_sub.py"
test_file.write_text("import unittest\n")
mock_result = TestResult()
mock_result.tests_result = ""
mock_result.tests = []
mock_result.stdout = "crash"
with (
mock.patch(
"update_lib.cmd_auto_mark.run_test", return_value=mock_result
),
mock.patch(
"update_lib.cmd_auto_mark.get_test_module_name",
return_value="test_example",
),
):
with self.assertRaises(TestRunError):
auto_mark_directory(test_dir, verbose=False)
class TestAutoMarkFileRestoresOnCrash(unittest.TestCase):
"""Stripped markers must be restored when the test runner crashes."""
def test_stripped_markers_restored_when_crash(self):
"""Markers stripped before run must be restored for unobserved tests on crash."""
test_code = f"""\
import unittest
class TestA(unittest.TestCase):
@unittest.expectedFailure # {COMMENT}
def test_foo(self):
pass
@unittest.expectedFailure # {COMMENT}
def test_bar(self):
pass
@unittest.expectedFailure # {COMMENT}
def test_baz(self):
pass
"""
with tempfile.TemporaryDirectory() as tmpdir:
test_file = pathlib.Path(tmpdir) / "test_example.py"
test_file.write_text(test_code)
# Simulate a crashed run that only observed test_foo (failed)
# test_bar and test_baz never ran due to crash
mock_result = TestResult()
mock_result.tests_result = "" # no Tests result line (crash)
mock_result.tests = [
Test(
name="test_foo",
path="test.test_example.TestA.test_foo",
result="fail",
error_message="AssertionError: 1 != 2",
),
]
with mock.patch(
"update_lib.cmd_auto_mark.run_test", return_value=mock_result
):
auto_mark_file(test_file, verbose=False)
contents = test_file.read_text()
# test_bar and test_baz were not observed — their markers must be restored
self.assertIn("def test_bar", contents)
self.assertIn("def test_baz", contents)
# Count expectedFailure markers: all 3 should be present
self.assertEqual(contents.count("expectedFailure"), 3, contents)
def test_stripped_markers_removed_when_complete_run(self):
"""Markers are properly removed when the run completes normally."""
test_code = f"""\
import unittest
class TestA(unittest.TestCase):
@unittest.expectedFailure # {COMMENT}
def test_foo(self):
pass
@unittest.expectedFailure # {COMMENT}
def test_bar(self):
pass
"""
with tempfile.TemporaryDirectory() as tmpdir:
test_file = pathlib.Path(tmpdir) / "test_example.py"