@jesdi/skills 0.0.81 → 0.0.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/package.json +2 -1
  2. package/skills/crap-gate/launcher.sh +104 -0
  3. package/skills/crap-gate/run.sh +15 -75
  4. package/skills/crap-gate/test_launcher.py +39 -0
  5. package/skills/implement-spec/launcher.sh +104 -0
  6. package/skills/implement-spec/run.sh +10 -89
  7. package/skills/implement-spec/tests/test_launcher.py +138 -0
  8. package/skills/test-weigh-in/SKILL.md +16 -0
  9. package/skills/test-weigh-in/dashboard.html +112 -0
  10. package/skills/test-weigh-in/launcher.sh +104 -0
  11. package/skills/test-weigh-in/rules.toml +134 -0
  12. package/skills/test-weigh-in/run.sh +21 -0
  13. package/skills/test-weigh-in/tests/brittle_repo.py +79 -0
  14. package/skills/test-weigh-in/tests/conftest.py +35 -0
  15. package/skills/test-weigh-in/tests/fixture_repo.py +99 -0
  16. package/skills/test-weigh-in/tests/kill_repo.py +87 -0
  17. package/skills/test-weigh-in/tests/maint_repo.py +139 -0
  18. package/skills/test-weigh-in/tests/map_fixture.py +56 -0
  19. package/skills/test-weigh-in/tests/pt_repo.py +46 -0
  20. package/skills/test-weigh-in/tests/red_repo.py +44 -0
  21. package/skills/test-weigh-in/tests/rule_repo.py +208 -0
  22. package/skills/test-weigh-in/tests/rules_fixture.py +65 -0
  23. package/skills/test-weigh-in/tests/smell_repo.py +138 -0
  24. package/skills/test-weigh-in/tests/test_brittleness.py +75 -0
  25. package/skills/test-weigh-in/tests/test_brittleness_history.py +168 -0
  26. package/skills/test-weigh-in/tests/test_coverage_run.py +201 -0
  27. package/skills/test-weigh-in/tests/test_coverage_value.py +76 -0
  28. package/skills/test-weigh-in/tests/test_dashboard_map.py +20 -0
  29. package/skills/test-weigh-in/tests/test_interpreters.py +115 -0
  30. package/skills/test-weigh-in/tests/test_kill_matrix.py +126 -0
  31. package/skills/test-weigh-in/tests/test_maintainability_smells.py +113 -0
  32. package/skills/test-weigh-in/tests/test_mutation_recovery.py +67 -0
  33. package/skills/test-weigh-in/tests/test_mutation_sampling.py +53 -0
  34. package/skills/test-weigh-in/tests/test_mutation_score.py +140 -0
  35. package/skills/test-weigh-in/tests/test_mutation_stale.py +30 -0
  36. package/skills/test-weigh-in/tests/test_mutmut_contract.py +43 -0
  37. package/skills/test-weigh-in/tests/test_ruff_pt_smells.py +45 -0
  38. package/skills/test-weigh-in/tests/test_runs.py +156 -0
  39. package/skills/test-weigh-in/tests/test_score.py +26 -0
  40. package/skills/test-weigh-in/tests/test_scoring.py +154 -0
  41. package/skills/test-weigh-in/tests/test_smell_rules.py +96 -0
  42. package/skills/test-weigh-in/tests/test_smells.py +71 -0
  43. package/skills/test-weigh-in/tests/test_walking_skeleton.py +91 -0
  44. package/skills/test-weigh-in/tests/testdata/default_repo/demo/__init__.py +0 -0
  45. package/skills/test-weigh-in/tests/testdata/default_repo/demo/board.py +2 -0
  46. package/skills/test-weigh-in/tests/testdata/default_repo/demo/config.py +2 -0
  47. package/skills/test-weigh-in/tests/testdata/default_repo/pyproject.toml +8 -0
  48. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_board.py +19 -0
  49. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_config.py +19 -0
  50. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_parser.py +19 -0
  51. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_render.py +19 -0
  52. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_report.py +17 -0
  53. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_session.py +19 -0
  54. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_store.py +17 -0
  55. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_sync.py +17 -0
  56. package/skills/test-weigh-in/tests/testdata/default_repo/uv.lock +1 -0
  57. package/skills/test-weigh-in/weigh.py +133 -0
  58. package/skills/test-weigh-in/weigh_coverage.py +154 -0
  59. package/skills/test-weigh-in/weigh_dashboard.py +72 -0
  60. package/skills/test-weigh-in/weigh_env.py +112 -0
  61. package/skills/test-weigh-in/weigh_git.py +119 -0
  62. package/skills/test-weigh-in/weigh_inventory.py +49 -0
  63. package/skills/test-weigh-in/weigh_mutation.py +190 -0
  64. package/skills/test-weigh-in/weigh_pytest_plugin.py +70 -0
  65. package/skills/test-weigh-in/weigh_ruff.py +22 -0
  66. package/skills/test-weigh-in/weigh_rules.py +65 -0
  67. package/skills/test-weigh-in/weigh_runs.py +134 -0
  68. package/skills/test-weigh-in/weigh_score.py +80 -0
  69. package/skills/test-weigh-in/weigh_smells.py +355 -0
  70. package/skills/test-weigh-in/weigh_snapshot.py +49 -0
  71. package/skills-manifest.json +11 -5
@@ -0,0 +1,138 @@
1
+ """Fixture suites for the smell tests (ticket tw/s5-smells/09), built on the default repo (40 tests, no smells).
2
+
3
+ smelly_suite adds tests/test_smells.py and tests/conftest.py. Expected smells by test (all other tests have none):
4
+ No assertion: test_board_renders, test_fail_hollow (fails), test_error_hollow (errors in setup), test_skipped_hollow (skipped)
5
+ Interaction-only: test_notify
6
+ Mock-heavy: test_b_heavy (3 @patch + MagicMock())
7
+ Private access: test_b_private (imports _requeue_locked from dispatcher.queue_ops)
8
+ No smell, each on a boundary: test_board (helper assert_board_equal from conftest), test_invalid (pytest.raises),
9
+ test_warns (pytest.warns), test_nested_helper (assert inside a nested def), test_a_patched (3 @patch),
10
+ test_a_dunder (obj.__dict__), test_conftest_private (a _name from conftest), test_mixed_mock (mock assert plus a plain assert).
11
+ mock_heavy_suite adds 25 mock-heavy tests that pass.
12
+ """
13
+ from fixture_repo import build_repo, git
14
+
15
+ SMELLS = '''import pytest
16
+ from unittest.mock import MagicMock, patch
17
+
18
+ from demo import board
19
+ from tests.conftest import _conftest_private, assert_board_equal
20
+
21
+
22
+ def test_board_renders():
23
+ board.render(1)
24
+
25
+
26
+ def test_fail_hollow():
27
+ raise RuntimeError("boom")
28
+
29
+
30
+ @pytest.fixture
31
+ def broken():
32
+ raise RuntimeError("setup")
33
+
34
+
35
+ def test_error_hollow(broken):
36
+ board.render(1)
37
+
38
+
39
+ @pytest.mark.skip
40
+ def test_skipped_hollow():
41
+ board.render(1)
42
+
43
+
44
+ def test_board():
45
+ assert_board_equal(board.render(1), "1")
46
+
47
+
48
+ def test_invalid():
49
+ with pytest.raises(ValueError):
50
+ int("x")
51
+
52
+
53
+ def test_warns():
54
+ import warnings
55
+ with pytest.warns(UserWarning):
56
+ warnings.warn("w", UserWarning)
57
+
58
+
59
+ def test_nested_helper():
60
+ def check(value):
61
+ assert value == "1"
62
+ check(board.render(1))
63
+
64
+
65
+ @patch("os.getcwd")
66
+ @patch("os.getpid")
67
+ @patch("os.getppid")
68
+ def test_a_patched(p1, p2, p3):
69
+ assert board.render(1) == "1"
70
+
71
+
72
+ @patch("os.getcwd")
73
+ @patch("os.getpid")
74
+ @patch("os.getppid")
75
+ def test_b_heavy(p1, p2, p3):
76
+ spare = MagicMock()
77
+ assert spare is not None
78
+
79
+
80
+ def test_notify():
81
+ sender = MagicMock()
82
+ sender.send("hi")
83
+ sender.send.assert_called_once_with("hi")
84
+
85
+
86
+ def test_mixed_mock():
87
+ sender = MagicMock()
88
+ sender.send("hi")
89
+ sender.send.assert_called_once_with("hi")
90
+ assert board.render(1) == "1"
91
+
92
+
93
+ def test_a_dunder():
94
+ class Obj:
95
+ pass
96
+ assert Obj().__dict__ == {}
97
+
98
+
99
+ def test_b_private():
100
+ from dispatcher.queue_ops import _requeue_locked
101
+ assert _requeue_locked() == 1
102
+
103
+
104
+ def test_conftest_private():
105
+ assert _conftest_private() == 1
106
+ '''
107
+ CONFTEST = '''def assert_board_equal(a, b):
108
+ assert a == b
109
+
110
+
111
+ def _conftest_private():
112
+ return 1
113
+ '''
114
+ MOCK_HEAVY = "from unittest.mock import patch\n\n\n" + "\n\n".join(
115
+ f'@patch("os.getcwd")\n@patch("os.getpid")\n@patch("os.getppid")\n@patch("os.getuid")\n'
116
+ f"def test_heavy_{i:02d}(a, b, c, d):\n assert a is not None\n" for i in range(25))
117
+
118
+
119
+ def _commit(repo):
120
+ git(repo, "add", "-A")
121
+ git(repo, "commit", "-q", "-m", "suite")
122
+ return repo
123
+
124
+
125
+ def smelly_suite(path):
126
+ repo = build_repo(path)
127
+ (repo / "dispatcher").mkdir()
128
+ (repo / "dispatcher" / "__init__.py").write_text("")
129
+ (repo / "dispatcher" / "queue_ops.py").write_text("def _requeue_locked():\n return 1\n")
130
+ (repo / "tests" / "conftest.py").write_text(CONFTEST)
131
+ (repo / "tests" / "test_smells.py").write_text(SMELLS)
132
+ return _commit(repo)
133
+
134
+
135
+ def mock_heavy_suite(path):
136
+ repo = build_repo(path)
137
+ (repo / "tests" / "test_heavy.py").write_text(MOCK_HEAVY)
138
+ return _commit(repo)
@@ -0,0 +1,75 @@
1
+ """Ticket tw/s6-brittleness/12: brittle test files from git history, and the deterministic default tier.
2
+ Interface: see brittle_repo.py."""
3
+ from brittle_repo import CLAIMS, TEST, board_repo, claims_repo, commit, history, without_git
4
+ from fixture_repo import build_repo, load, snapshots, weigh
5
+
6
+ KEY = "github.com/jesdi/demo"
7
+
8
+
9
+ def measure(repo, home, cache, key=KEY):
10
+ result = weigh(repo, home, "--no-open", cache=cache)
11
+ assert result.returncode == 0, result.stdout + result.stderr
12
+ return load(snapshots(home, key)[-1])
13
+
14
+
15
+ def test_a_test_file_changed_in_9_of_the_10_commits_that_changed_its_source_is_brittle(tmp_path, home, cache):
16
+ repo = history(claims_repo(tmp_path / "demo"), both=8, claims_only=1)
17
+ data = measure(repo, home, cache)
18
+ assert data["test_files"][TEST] == {"sources": [CLAIMS], "brittle": True}
19
+ assert data["metrics"]["brittle_test_files"]["value"] == 100
20
+ assert data["pillars"]["refactoring"]["partial"] is False
21
+
22
+
23
+ def test_a_test_file_changed_in_5_of_the_10_commits_is_not_brittle(tmp_path, home, cache):
24
+ repo = history(claims_repo(tmp_path / "demo"), both=4, claims_only=5)
25
+ data = measure(repo, home, cache)
26
+ assert data["test_files"][TEST] == {"sources": [CLAIMS], "brittle": False}
27
+ assert data["metrics"]["brittle_test_files"]["value"] == 0
28
+
29
+
30
+ def test_a_helper_with_40_of_300_covered_lines_is_not_a_mapped_source(tmp_path, home, cache):
31
+ data = measure(board_repo(tmp_path / "demo"), home, cache)
32
+ assert data["test_files"]["tests/test_board.py"]["sources"] == ["demo/board.py"]
33
+
34
+
35
+ def test_a_commit_that_changed_140_files_is_not_counted(tmp_path, home, cache):
36
+ repo = history(claims_repo(tmp_path / "demo"), both=0, claims_only=1) # suite (both) + 1 claims-only: 1 of 2
37
+ commit(repo, "reformat", [CLAIMS, TEST], [f"docs/f{i}.txt" for i in range(140)]) # counted, it would make 2 of 3
38
+ data = measure(repo, home, cache)
39
+ assert data["test_files"][TEST]["brittle"] is False
40
+
41
+
42
+ def test_only_the_last_200_of_500_source_changing_commits_are_counted(tmp_path, home, cache):
43
+ # the suite commit and 299 more change both files, the last 200 change claims.py alone: 300 of 500 would be brittle
44
+ repo = history(claims_repo(tmp_path / "demo"), both=299, claims_only=200)
45
+ data = measure(repo, home, cache)
46
+ assert data["test_files"][TEST]["brittle"] is False
47
+
48
+
49
+ def test_a_target_that_is_not_a_git_repository_leaves_brittleness_unmeasured(tmp_path, home, cache):
50
+ repo = without_git(history(claims_repo(tmp_path / "demo"), both=8, claims_only=1))
51
+ data = measure(repo, home, cache, key="local/demo")
52
+ assert not data["commit"]
53
+ assert data["test_files"][TEST]["brittle"] is None
54
+ assert "brittle_test_files" not in data["metrics"]
55
+ assert data["pillars"]["refactoring"]["partial"] is True
56
+
57
+
58
+ def test_two_runs_of_the_default_repo_are_equal_apart_from_durations(tmp_path, home, cache):
59
+ repo = build_repo(tmp_path / "demo")
60
+
61
+ def run():
62
+ data = measure(repo, home, cache)
63
+ assert "brittle_test_files" in data["metrics"]
64
+ for test in data["tests"].values():
65
+ del test["duration"]
66
+ del data["inventory"]["runtime_seconds"]
67
+ for metric in ("total_runtime", "p95_duration", "slowest_decile_share", "tests_over_10s"):
68
+ del data["metrics"][metric]
69
+ del data["pillars"]["feedback"]["score"]
70
+ return data
71
+
72
+ first = run()
73
+ second = run()
74
+ assert first == second
75
+ assert [list(f["sources"]) for f in first["test_files"].values()] == [sorted(f["sources"]) for f in first["test_files"].values()]
@@ -0,0 +1,168 @@
1
+ """Ticket tw/s6-brittleness/12: the history brittleness reads (window boundary, renames, merges), a red suite, and file discovery.
2
+ Interface: see brittle_repo.py."""
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+
11
+ from brittle_repo import CLAIMS, TEST, claims_repo, commit, history
12
+ from fixture_repo import git, load, snapshots, weigh
13
+
14
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
15
+ from weigh_inventory import python_files # noqa: E402
16
+
17
+ KEY = "github.com/jesdi/demo"
18
+
19
+
20
+ def measure(repo, home, cache):
21
+ result = weigh(repo, home, "--no-open", cache=cache)
22
+ assert result.returncode == 0, result.stdout + result.stderr
23
+ return load(snapshots(home, KEY)[-1])
24
+
25
+
26
+ def test_the_window_holds_exactly_the_last_200_source_changing_commits(tmp_path, home, cache):
27
+ # oldest to newest: the suite (both), 298 claims-only, a co-change at 201st newest, a claims-only at 200th newest,
28
+ # then 199 holding 100 co-changes: 100 of 200 is not brittle, while 100 of 199 or 101 of 201 would be
29
+ repo = history(claims_repo(tmp_path / "demo"), both=0, claims_only=298)
30
+ commit(repo, "201st", [CLAIMS, TEST])
31
+ commit(repo, "200th", [CLAIMS])
32
+ for i in range(199):
33
+ commit(repo, f"recent {i}", [CLAIMS, TEST] if i % 2 == 0 else [CLAIMS])
34
+ data = measure(repo, home, cache)
35
+ assert data["test_files"][TEST]["brittle"] is False
36
+
37
+
38
+ def test_a_renamed_source_keeps_the_history_before_its_rename(tmp_path, home, cache):
39
+ # the suite, the rename to claims_old.py (which edits the test's import), 8 co-changes as claims_old.py, the rename
40
+ # back, then 4 changing claims.py alone: 11 of 15 is brittle; reading claims.py's path alone, 3 of 7 is not
41
+ repo = claims_repo(tmp_path / "demo")
42
+ old = "demo/claims_old.py"
43
+ rename(repo, CLAIMS, old, "import claims,", "import claims_old as claims,")
44
+ for i in range(8):
45
+ commit(repo, f"both {i}", [old, TEST])
46
+ rename(repo, old, CLAIMS, "import claims_old as claims,", "import claims,")
47
+ history(repo, both=0, claims_only=4)
48
+ data = measure(repo, home, cache)
49
+ assert data["test_files"][TEST] == {"sources": [CLAIMS], "brittle": True}
50
+
51
+
52
+ def rename(repo, src, dst, old_import, new_import):
53
+ git(repo, "mv", src, dst)
54
+ (repo / TEST).write_text((repo / TEST).read_text().replace(old_import, new_import))
55
+ commit(repo, f"rename to {dst}", [TEST])
56
+
57
+
58
+ def test_a_side_branch_change_to_a_name_main_renamed_counts_under_the_new_name(tmp_path, home, cache, monkeypatch):
59
+ # the suite and a rename to claims_old.py; then main renames it back while a side branch makes 8 co-changes to
60
+ # claims_old.py, all dated after main's rename back, and the merge (both files differ from each parent) brings them
61
+ # in; then 4 claims.py-only commits: 12 of 16 is brittle, while leaving the side commits under claims_old.py is 4 of 8
62
+ clock = iter(range(1_000_000))
63
+ monkeypatch.setattr(subprocess, "run", dated(subprocess.run, clock))
64
+ repo = claims_repo(tmp_path / "demo")
65
+ old = "demo/claims_old.py"
66
+ rename(repo, CLAIMS, old, "import claims,", "import claims_old as claims,")
67
+ git(repo, "branch", "side")
68
+ git(repo, "mv", old, CLAIMS) # unlike rename(), the test's last line stays, so the merge has no conflict
69
+ (repo / TEST).write_text((repo / TEST).read_text().replace("import claims_old as claims,", "import claims,"))
70
+ git(repo, "commit", "-q", "-am", "rename back")
71
+ git(repo, "checkout", "-q", "side")
72
+ for i in range(8):
73
+ commit(repo, f"side {i}", [old, TEST])
74
+ git(repo, "checkout", "-q", "-")
75
+ git(repo, "merge", "-q", "--no-ff", "-m", "merge side", "side")
76
+ history(repo, both=0, claims_only=4)
77
+ monkeypatch.undo()
78
+ data = measure(repo, home, cache)
79
+ assert data["test_files"][TEST] == {"sources": [CLAIMS], "brittle": True}
80
+
81
+
82
+ def test_a_new_file_reusing_a_renamed_away_name_leaves_the_history_with_the_renamed_file(tmp_path, home, cache):
83
+ # the suite, 8 co-changes, the rename to claims_new.py (which edits the test), a new claims.py, then 4 changing
84
+ # claims_new.py alone: 10 of 14 is brittle, while handing the history before the rename to the new claims.py is 1 of 5
85
+ repo = history(claims_repo(tmp_path / "demo"), both=8, claims_only=0)
86
+ new = "demo/claims_new.py"
87
+ rename(repo, CLAIMS, new, "import claims,", "import claims_new as claims,")
88
+ (repo / CLAIMS).write_text("VALUE = 1\n")
89
+ git(repo, "add", CLAIMS)
90
+ git(repo, "commit", "-q", "-m", "a new claims.py")
91
+ for i in range(4):
92
+ commit(repo, f"new {i}", [new])
93
+ data = measure(repo, home, cache)
94
+ assert data["test_files"][TEST] == {"sources": [new], "brittle": True}
95
+
96
+
97
+ def test_the_window_holds_the_newest_commits_by_date_across_merged_branches(tmp_path, home, cache, monkeypatch):
98
+ # a side branch makes 200 co-changes, then main makes 200 claims.py-only changes dated after them, and the merge:
99
+ # by date the window is the merge and 199 of main's, 0 co-changes; the side branch's history first is 199 of 200
100
+ clock = iter(range(1_000_000))
101
+ monkeypatch.setattr(subprocess, "run", dated(subprocess.run, clock))
102
+ repo = claims_repo(tmp_path / "demo")
103
+ git(repo, "checkout", "-q", "-b", "side")
104
+ for i in range(200):
105
+ commit(repo, f"side {i}", [CLAIMS, TEST])
106
+ git(repo, "checkout", "-q", "-")
107
+ for i in range(200): # at the top of claims.py, where the side branch's appended lines don't conflict
108
+ (repo / CLAIMS).write_text(f"# main {i}\n" + (repo / CLAIMS).read_text())
109
+ git(repo, "commit", "-q", "-am", f"main {i}")
110
+ git(repo, "merge", "-q", "--no-ff", "-m", "merge side", "side")
111
+ monkeypatch.undo()
112
+ data = measure(repo, home, cache)
113
+ assert data["test_files"][TEST]["brittle"] is False
114
+
115
+
116
+ def dated(run, clock):
117
+ """subprocess.run that dates each git commit or merge a minute after the last, so log order is commit order."""
118
+ def run_dated(args, **kw):
119
+ if "commit" in args or "merge" in args:
120
+ stamp = f"{int(time.time()) - 86_400 + 60 * next(clock)} +0000"
121
+ kw["env"] = {**(kw.get("env") or os.environ), "GIT_AUTHOR_DATE": stamp, "GIT_COMMITTER_DATE": stamp}
122
+ return run(args, **kw)
123
+ return run_dated
124
+
125
+
126
+ def test_a_merge_counts_the_changes_its_resolution_made(tmp_path, home, cache):
127
+ # the suite (both) and 1 claims-only make 1 of 2; a merge whose resolution changes both files makes it 2 of 3
128
+ repo = history(claims_repo(tmp_path / "demo"), both=0, claims_only=1)
129
+ git(repo, "checkout", "-q", "-b", "side")
130
+ commit(repo, "side", extra=["docs/side.txt"])
131
+ git(repo, "checkout", "-q", "-")
132
+ commit(repo, "main", extra=["docs/main.txt"])
133
+ git(repo, "merge", "-q", "--no-ff", "--no-commit", "side")
134
+ commit(repo, "merge", [CLAIMS, TEST])
135
+ data = measure(repo, home, cache)
136
+ assert data["test_files"][TEST]["brittle"] is True
137
+
138
+
139
+ def test_a_red_suite_leaves_refactoring_partial_with_brittleness_measured(tmp_path, home, cache):
140
+ repo = claims_repo(tmp_path / "demo")
141
+ (repo / "tests" / "test_fails.py").write_text("def test_fails():\n assert False\n")
142
+ git(repo, "add", "-A")
143
+ git(repo, "commit", "-q", "-m", "a failing test")
144
+ history(repo, both=8, claims_only=1)
145
+ data = measure(repo, home, cache)
146
+ assert data["test_files"][TEST]["brittle"] is True
147
+ assert "brittle_test_files" in data["metrics"]
148
+ assert data["pillars"]["refactoring"]["partial"] is True
149
+
150
+
151
+ def test_a_repository_whose_index_git_cannot_read_raises_and_a_plain_folder_is_walked(tmp_path):
152
+ repo = claims_repo(tmp_path / "demo")
153
+ (repo / "untracked.py").write_text("")
154
+ (repo / ".git" / "index").write_text("garbage")
155
+ with pytest.raises(subprocess.CalledProcessError):
156
+ python_files(repo)
157
+ (tmp_path / "plain" / "pkg").mkdir(parents=True)
158
+ (tmp_path / "plain" / "pkg" / "a.py").write_text("")
159
+ assert python_files(tmp_path / "plain") == ["pkg/a.py"]
160
+
161
+
162
+ def test_a_git_file_pointing_at_a_missing_gitdir_raises(tmp_path):
163
+ repo = tmp_path / "broken"
164
+ (repo / "pkg").mkdir(parents=True)
165
+ (repo / "pkg" / "a.py").write_text("")
166
+ (repo / ".git").write_text(f"gitdir: {tmp_path / 'missing'}\n")
167
+ with pytest.raises(subprocess.CalledProcessError):
168
+ python_files(repo)
@@ -0,0 +1,201 @@
1
+ """Ticket tw/s4-coverage/07: the coverage run, flakiness, red suites, unique coverage and the overlay race.
2
+
3
+ Snapshot interface the tests pin (the spec leaves the JSON keys open), on top of fixture_repo.py:
4
+ tests[node].coverage {repo-relative path: sorted covered lines}: the union of the test's passing cases,
5
+ {} for a failed or skipped test
6
+ tests[node].flaky true when the outcome differs between the plain and the coverage run
7
+ tests[node].unique_coverage number of lines the test covers that no other passing test covers
8
+ overlaps [{"tests": [node, node], "jaccard": float}] for passing pairs with jaccard >= 0.9
9
+ metrics.branch_coverage / metrics.no_unique_coverage {value, score}; value in percent
10
+ Stdout: "<n> flaky test(s)" and "<n> tests are failing" warnings.
11
+ """
12
+ import time
13
+ from concurrent.futures import ThreadPoolExecutor
14
+
15
+ import pytest
16
+
17
+ import fixture_repo
18
+ from fixture_repo import FAKECLOCK, build_repo, git, load, snapshots, weigh
19
+ from red_repo import FAILING, SKIPPED, red_suite, skipped_suite
20
+
21
+ KEY = "github.com/jesdi/demo"
22
+
23
+
24
+ def ok(result):
25
+ assert result.returncode == 0, result.stdout + result.stderr
26
+
27
+
28
+ def commit(repo, files):
29
+ for rel, text in files.items():
30
+ (repo / rel).parent.mkdir(parents=True, exist_ok=True)
31
+ (repo / rel).write_text(text)
32
+ git(repo, "add", "-A")
33
+ git(repo, "commit", "-q", "-m", "extra")
34
+ return repo
35
+
36
+
37
+ def snap(home):
38
+ (path,) = snapshots(home, KEY)
39
+ return load(path)
40
+
41
+
42
+ PARSE = "".join(f"def f{k}():\n return {k}\n" for k in range(14)) # f<k> body is line 2k+2
43
+ PARSE_TEST = '''import pytest
44
+ from demo import parse
45
+
46
+
47
+ @pytest.mark.parametrize("n", range(14))
48
+ def test_parse(n):
49
+ getattr(parse, f"f{n}")()
50
+ assert n != 13
51
+ '''
52
+
53
+
54
+ def test_a_parametrized_test_is_one_test_with_the_union_of_its_passing_cases(tmp_path, home, cache):
55
+ repo = build_repo(tmp_path / "demo")
56
+ site = next((repo / ".venv" / "lib").glob("python*/site-packages"))
57
+ (site / "fakeclock.py").write_text(FAKECLOCK.replace("1.125", "0.1"))
58
+ commit(repo, {"demo/parse.py": PARSE, "tests/test_parse.py": PARSE_TEST})
59
+ result = weigh(repo, home, "--pytest-args", "tests/test_parse.py", cache=cache)
60
+ ok(result)
61
+ data = snap(home)
62
+ assert (data["inventory"]["tests"], data["inventory"]["cases"]) == (1, 14)
63
+ test = data["tests"]["tests/test_parse.py::test_parse"]
64
+ assert (test["outcome"], test["cases"]) == ("failed", 14)
65
+ assert test["duration"] == pytest.approx(1.4)
66
+ assert test["coverage"]["demo/parse.py"] == [2 * k + 2 for k in range(13)]
67
+
68
+
69
+ RETRY = 'import sys\n\n\ndef test_retry():\n assert "coverage" not in sys.modules\n'
70
+ # covered by test_solo alone, so its unique coverage keeps no_unique_coverage below 100%
71
+ SOLO = {"demo/solo.py": "def solo():\n return 1\n",
72
+ "tests/test_solo.py": "from demo.solo import solo\n\n\ndef test_solo():\n assert solo() == 1\n"}
73
+
74
+
75
+ def test_a_test_that_differs_between_the_runs_is_flaky(tmp_path, home, cache):
76
+ repo = commit(build_repo(tmp_path / "demo"), {"tests/test_retry.py": RETRY, **SOLO})
77
+ result = weigh(repo, home, "--pytest-args", "tests/test_retry.py tests/test_board.py tests/test_solo.py", cache=cache)
78
+ ok(result)
79
+ tests = snap(home)["tests"]
80
+ assert tests["tests/test_retry.py::test_retry"]["flaky"] is True
81
+ assert [n for n, t in tests.items() if t.get("flaky")] == ["tests/test_retry.py::test_retry"]
82
+ assert "1 flaky test" in result.stdout
83
+ # failing under coverage, test_retry gives no value: it is out of the count, yet in the base of all tests
84
+ others = [t for n, t in tests.items() if n != "tests/test_retry.py::test_retry"]
85
+ assert snap(home)["metrics"]["no_unique_coverage"]["value"] == pytest.approx(
86
+ 100 * sum(not t["unique_coverage"] for t in others) / len(tests))
87
+
88
+
89
+ def test_a_repo_inside_a_folder_named_tests_keeps_its_source_coverage(tmp_path, home, cache):
90
+ repo = commit(build_repo(tmp_path / "tests" / "demo"), SOLO)
91
+ ok(weigh(repo, home, "--pytest-args", "tests/test_solo.py", cache=cache))
92
+ assert snap(home)["tests"]["tests/test_solo.py::test_solo"]["coverage"]["demo/solo.py"] == [2]
93
+
94
+
95
+ def test_a_red_suite_is_measured_without_the_failing_tests_value(tmp_path, home, cache):
96
+ repo = red_suite(tmp_path / "demo")
97
+ result = weigh(repo, home, cache=cache)
98
+ ok(result)
99
+ data = snap(home)
100
+ inv = data["inventory"]
101
+ assert inv["tests"] == 40 and inv["runtime_seconds"] == pytest.approx(45)
102
+ assert inv["test_lines"] == sum(len(p.read_text().splitlines()) for p in (repo / "tests").glob("test_*.py"))
103
+ failed = {n for n, t in data["tests"].items() if t["outcome"] == "failed"}
104
+ assert failed == set(FAILING)
105
+ assert all(data["tests"][n]["coverage"] == {} for n in failed)
106
+ assert not any(set(pair["tests"]) & failed for pair in data["overlaps"])
107
+ assert data["metrics"]["branch_coverage"]["value"] == pytest.approx(50)
108
+ # failing tests give no value: not in the count, yet in the base, a percentage of all 40 tests (req 17)
109
+ passed = [t for t in data["tests"].values() if t["outcome"] == "passed"]
110
+ assert all(data["tests"][n]["unique_coverage"] == 0 for n in failed)
111
+ assert data["metrics"]["no_unique_coverage"]["value"] == pytest.approx(
112
+ 100 * sum(not t["unique_coverage"] for t in passed) / 40)
113
+ assert data["pillars"]["regression"]["partial"] and data["pillars"]["economy"]["partial"]
114
+ assert "3 tests are failing" in result.stdout
115
+
116
+
117
+ def test_skipped_tests_cost_without_value(tmp_path, home, cache):
118
+ repo = skipped_suite(tmp_path / "demo")
119
+ result = weigh(repo, home, cache=cache)
120
+ ok(result)
121
+ data = snap(home)
122
+ assert data["inventory"]["tests"] == 40
123
+ assert data["inventory"]["test_lines"] == sum(len(p.read_text().splitlines()) for p in (repo / "tests").glob("test_*.py"))
124
+ for node in SKIPPED:
125
+ assert data["tests"][node]["outcome"] == "skipped"
126
+ assert data["tests"][node]["coverage"] == {}
127
+ assert not any(set(pair["tests"]) & set(SKIPPED) for pair in data["overlaps"])
128
+
129
+
130
+ BOARD = ["def render(n):", " return str(n)", *[f"# line {n}" for n in range(3, 9)], "def part1():",
131
+ *[f" _ = {n}" for n in range(10, 21)], "def part2():", *[f" _ = {n}" for n in range(22, 26)],
132
+ "def part3():", " _ = 27"]
133
+ BOARD_TESTS = '''from demo import board
134
+
135
+
136
+ def _make(name, *parts):
137
+ def run():
138
+ for part in parts:
139
+ getattr(board, part)()
140
+ return run
141
+
142
+
143
+ test_board_empty = _make("test_board_empty", "part1")
144
+ test_board_none = _make("test_board_none", "part1", "{other}")
145
+ '''
146
+ EMPTY, NONE = "tests/test_board_cases.py::test_board_empty", "tests/test_board_cases.py::test_board_none"
147
+
148
+
149
+ def board_run(tmp_path, home, cache, other):
150
+ assert BOARD.index("def part1():") == 8 and BOARD.index("def part2():") == 20
151
+ repo = commit(build_repo(tmp_path / "demo"), {"demo/board.py": "\n".join(BOARD) + "\n",
152
+ "tests/test_board_cases.py": BOARD_TESTS.replace("{other}", other)})
153
+ ok(weigh(repo, home, "--pytest-args", "tests/test_board_cases.py", cache=cache))
154
+ return snap(home)
155
+
156
+
157
+ def test_a_test_covered_by_another_has_no_unique_coverage_and_a_far_pair_is_no_overlap(tmp_path, home, cache):
158
+ data = board_run(tmp_path, home, cache, "part2") # lines 10-20 against 10-25: Jaccard 11/15
159
+ assert data["tests"][EMPTY]["coverage"]["demo/board.py"] == list(range(10, 21))
160
+ assert data["tests"][NONE]["coverage"]["demo/board.py"] == [*range(10, 21), *range(22, 26)]
161
+ assert data["tests"][EMPTY]["unique_coverage"] == 0
162
+ assert data["tests"][NONE]["unique_coverage"] > 0
163
+ assert data["metrics"]["no_unique_coverage"]["value"] == pytest.approx(50)
164
+ assert data["overlaps"] == []
165
+
166
+
167
+ def test_a_pair_at_jaccard_09_or_more_is_an_overlap(tmp_path, home, cache):
168
+ data = board_run(tmp_path, home, cache, "part3") # lines 10-20 against 10-20 and 27: Jaccard 11/12
169
+ (pair,) = data["overlaps"]
170
+ assert sorted(pair["tests"]) == sorted([EMPTY, NONE])
171
+ assert pair["jaccard"] == pytest.approx(11 / 12)
172
+ assert data["tests"][EMPTY]["unique_coverage"] == 0
173
+
174
+
175
+ def test_two_first_runs_share_one_complete_overlay(tmp_path, home, cache, monkeypatch):
176
+ fresh = tmp_path / "fresh-cache"
177
+ repos = [build_repo(tmp_path / "work" / name, origin=f"git@github.com:jesdi/{name}.git") for name in ("a", "b")]
178
+ homes = [home / name for name in ("a", "b")]
179
+ for h in homes:
180
+ h.mkdir()
181
+ real = fixture_repo.uv()
182
+ slow = tmp_path / "slow-uv" # the overlay install takes 3s, so the second run starts while the first is mid-build
183
+ slow.write_text(f'#!/bin/sh\ncase "$1" in pip) sleep 3;; esac\nexec {real} "$@"\n')
184
+ slow.chmod(0o755)
185
+ monkeypatch.setattr(fixture_repo, "uv", lambda: str(slow))
186
+
187
+ def staggered(i):
188
+ time.sleep(i)
189
+ return weigh(repos[i], homes[i], cache=fresh)
190
+
191
+ with ThreadPoolExecutor(2) as pool:
192
+ results = list(pool.map(staggered, (0, 1)))
193
+ for result in results:
194
+ ok(result)
195
+ for name, h in zip("ab", homes):
196
+ (path,) = snapshots(h, f"github.com/jesdi/{name}")
197
+ tests = load(path)["tests"]
198
+ assert len(tests) == 40 and all(t["coverage"] for t in tests.values())
199
+ (overlay,) = fresh.iterdir()
200
+ assert overlay.name.startswith("overlay-")
201
+ assert (overlay / "weigh_pytest_plugin.py").is_file() and (overlay / "coverage").is_dir()
@@ -0,0 +1,76 @@
1
+ """The coverage run's value data: branches count in uniqueness and overlap, an expected failure keeps its coverage,
2
+ and a coverage report that fails stops the run instead of reading as empty coverage."""
3
+ import subprocess
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+
9
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
10
+
11
+ from fixture_repo import build_repo, git, load, snapshots, weigh
12
+ from weigh_env import SetupError
13
+ from weigh_runs import _report
14
+
15
+ KEY = "github.com/jesdi/demo"
16
+ FLAG = "def flag(x):\n if x:\n pass\n return 2\n"
17
+
18
+
19
+ def run(tmp_path, home, cache, files, args):
20
+ repo = build_repo(tmp_path / "demo")
21
+ for rel, text in files.items():
22
+ (repo / rel).write_text(text)
23
+ git(repo, "add", "-A")
24
+ git(repo, "commit", "-q", "-m", "extra")
25
+ result = weigh(repo, home, "--pytest-args", args, cache=cache)
26
+ assert result.returncode == 0, result.stdout + result.stderr
27
+ (path,) = snapshots(home, KEY)
28
+ return load(path)
29
+
30
+
31
+ def test_a_test_that_alone_takes_a_branch_has_unique_coverage_on_the_same_lines(tmp_path, home, cache):
32
+ tests = ("from demo.flag import flag\n\n\ndef test_both():\n flag(True)\n flag(False)\n\n\n"
33
+ "def test_true():\n flag(True)\n")
34
+ data = run(tmp_path, home, cache, {"demo/flag.py": FLAG, "tests/test_flag.py": tests}, "tests/test_flag.py")
35
+ both, true = data["tests"]["tests/test_flag.py::test_both"], data["tests"]["tests/test_flag.py::test_true"]
36
+ assert both["coverage"] == true["coverage"] == {"demo/flag.py": [2, 3, 4]}
37
+ assert both["branches"] == {"demo/flag.py": [[2, 3], [2, 4]]} and true["branches"] == {"demo/flag.py": [[2, 3]]}
38
+ assert (both["unique_coverage"], true["unique_coverage"]) == (1, 0)
39
+ assert data["overlaps"] == [] # 4 of 5 lines and branches shared: Jaccard 0.8
40
+
41
+
42
+ def test_a_branch_of_a_multi_line_condition_counts_as_unique(tmp_path, home, cache):
43
+ # the tracer records the true branch from line 3, the condition's last line; the report from line 2, its first
44
+ source = "def both(a, b):\n if (a\n and b):\n return 1\n return 2\n"
45
+ tests = ("from demo.both import both\n\n\ndef test_both_true():\n both(1, 1)\n\n\n"
46
+ "def test_first_false():\n both(0, 1)\n")
47
+ data = run(tmp_path, home, cache, {"demo/both.py": source, "tests/test_both.py": tests}, "tests/test_both.py")
48
+ true = data["tests"]["tests/test_both.py::test_both_true"]
49
+ assert [2, 4] in true["branches"]["demo/both.py"]
50
+ assert true["unique_coverage"] > 0
51
+
52
+
53
+ @pytest.mark.parametrize("arg", ["a, b", "$HOME"])
54
+ def test_a_test_id_with_a_comma_or_a_dollar_name_keeps_its_coverage(tmp_path, home, cache, arg):
55
+ # coverage splits its config lists at commas and expands $NAME there: the context regex must survive both
56
+ tests = ("import pytest\nfrom demo.flag import flag\n\n\n"
57
+ f"@pytest.mark.parametrize('arg', [{arg!r}])\ndef test_odd(arg):\n flag(True)\n")
58
+ data = run(tmp_path, home, cache, {"demo/flag.py": FLAG, "tests/test_odd.py": tests}, "tests/test_odd.py")
59
+ assert data["tests"]["tests/test_odd.py::test_odd"]["coverage"] == {"demo/flag.py": [2, 3, 4]}
60
+
61
+
62
+ def test_an_expected_failure_keeps_its_coverage(tmp_path, home, cache):
63
+ tests = ("import pytest\nfrom demo.flag import flag\n\n\n@pytest.mark.xfail\ndef test_xfail():\n"
64
+ " flag(False)\n assert False\n")
65
+ data = run(tmp_path, home, cache, {"demo/flag.py": FLAG, "tests/test_xfail.py": tests}, "tests/test_xfail.py")
66
+ test = data["tests"]["tests/test_xfail.py::test_xfail"]
67
+ assert test["outcome"] == "passed" and test["coverage"] == {"demo/flag.py": [2, 4]}
68
+ assert test["unique_coverage"] > 0 and data["metrics"]["no_unique_coverage"]["value"] == 0
69
+
70
+
71
+ def test_a_failing_coverage_report_is_an_error_with_its_output(tmp_path):
72
+ def coverage(*args):
73
+ return subprocess.CompletedProcess(args, 1, "", "Couldn't parse demo/x.py")
74
+
75
+ with pytest.raises(SetupError, match="coverage json exited 1:\nCouldn't parse demo/x.py"):
76
+ _report(coverage, tmp_path / "rc", tmp_path / "data", tmp_path / "out.json", "(?!)")