@jesdi/skills 0.0.80 → 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 (76) 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-prune/SKILL.md +4 -2
  9. package/skills/test-prune/prune_strengthen.py +24 -12
  10. package/skills/test-prune/tests/test_prune_guards.py +1 -1
  11. package/skills/test-prune/tests/test_prune_inputs.py +10 -5
  12. package/skills/test-prune/tests/test_prune_strengthen.py +34 -12
  13. package/skills/test-weigh-in/SKILL.md +16 -0
  14. package/skills/test-weigh-in/dashboard.html +112 -0
  15. package/skills/test-weigh-in/launcher.sh +104 -0
  16. package/skills/test-weigh-in/rules.toml +134 -0
  17. package/skills/test-weigh-in/run.sh +21 -0
  18. package/skills/test-weigh-in/tests/brittle_repo.py +79 -0
  19. package/skills/test-weigh-in/tests/conftest.py +35 -0
  20. package/skills/test-weigh-in/tests/fixture_repo.py +99 -0
  21. package/skills/test-weigh-in/tests/kill_repo.py +87 -0
  22. package/skills/test-weigh-in/tests/maint_repo.py +139 -0
  23. package/skills/test-weigh-in/tests/map_fixture.py +56 -0
  24. package/skills/test-weigh-in/tests/pt_repo.py +46 -0
  25. package/skills/test-weigh-in/tests/red_repo.py +44 -0
  26. package/skills/test-weigh-in/tests/rule_repo.py +208 -0
  27. package/skills/test-weigh-in/tests/rules_fixture.py +65 -0
  28. package/skills/test-weigh-in/tests/smell_repo.py +138 -0
  29. package/skills/test-weigh-in/tests/test_brittleness.py +75 -0
  30. package/skills/test-weigh-in/tests/test_brittleness_history.py +168 -0
  31. package/skills/test-weigh-in/tests/test_coverage_run.py +201 -0
  32. package/skills/test-weigh-in/tests/test_coverage_value.py +76 -0
  33. package/skills/test-weigh-in/tests/test_dashboard_map.py +20 -0
  34. package/skills/test-weigh-in/tests/test_interpreters.py +115 -0
  35. package/skills/test-weigh-in/tests/test_kill_matrix.py +126 -0
  36. package/skills/test-weigh-in/tests/test_maintainability_smells.py +113 -0
  37. package/skills/test-weigh-in/tests/test_mutation_recovery.py +67 -0
  38. package/skills/test-weigh-in/tests/test_mutation_sampling.py +53 -0
  39. package/skills/test-weigh-in/tests/test_mutation_score.py +140 -0
  40. package/skills/test-weigh-in/tests/test_mutation_stale.py +30 -0
  41. package/skills/test-weigh-in/tests/test_mutmut_contract.py +43 -0
  42. package/skills/test-weigh-in/tests/test_ruff_pt_smells.py +45 -0
  43. package/skills/test-weigh-in/tests/test_runs.py +156 -0
  44. package/skills/test-weigh-in/tests/test_score.py +26 -0
  45. package/skills/test-weigh-in/tests/test_scoring.py +154 -0
  46. package/skills/test-weigh-in/tests/test_smell_rules.py +96 -0
  47. package/skills/test-weigh-in/tests/test_smells.py +71 -0
  48. package/skills/test-weigh-in/tests/test_walking_skeleton.py +91 -0
  49. package/skills/test-weigh-in/tests/testdata/default_repo/demo/__init__.py +0 -0
  50. package/skills/test-weigh-in/tests/testdata/default_repo/demo/board.py +2 -0
  51. package/skills/test-weigh-in/tests/testdata/default_repo/demo/config.py +2 -0
  52. package/skills/test-weigh-in/tests/testdata/default_repo/pyproject.toml +8 -0
  53. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_board.py +19 -0
  54. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_config.py +19 -0
  55. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_parser.py +19 -0
  56. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_render.py +19 -0
  57. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_report.py +17 -0
  58. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_session.py +19 -0
  59. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_store.py +17 -0
  60. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_sync.py +17 -0
  61. package/skills/test-weigh-in/tests/testdata/default_repo/uv.lock +1 -0
  62. package/skills/test-weigh-in/weigh.py +133 -0
  63. package/skills/test-weigh-in/weigh_coverage.py +154 -0
  64. package/skills/test-weigh-in/weigh_dashboard.py +72 -0
  65. package/skills/test-weigh-in/weigh_env.py +112 -0
  66. package/skills/test-weigh-in/weigh_git.py +119 -0
  67. package/skills/test-weigh-in/weigh_inventory.py +49 -0
  68. package/skills/test-weigh-in/weigh_mutation.py +190 -0
  69. package/skills/test-weigh-in/weigh_pytest_plugin.py +70 -0
  70. package/skills/test-weigh-in/weigh_ruff.py +22 -0
  71. package/skills/test-weigh-in/weigh_rules.py +65 -0
  72. package/skills/test-weigh-in/weigh_runs.py +134 -0
  73. package/skills/test-weigh-in/weigh_score.py +80 -0
  74. package/skills/test-weigh-in/weigh_smells.py +355 -0
  75. package/skills/test-weigh-in/weigh_snapshot.py +49 -0
  76. package/skills-manifest.json +13 -7
@@ -0,0 +1,208 @@
1
+ """Fixture suite for the boundaries of the smell rules, built on the default repo (40 tests, no smells).
2
+
3
+ rules_suite adds tests/conftest.py, demo/_queue.py, data/app.json, tests/test_rules.py and tests/test_maint_rules.py.
4
+ Expected smells by test of test_rules.py:
5
+ No assertion: TestA::test_board (TestB::test_board, same name, asserts),
6
+ TestOther::test_inherited (TestChild::test_inherited, from Base, asserts),
7
+ TestDiamond::test_diamond (Python takes it from DRight, which does not assert; DBase does)
8
+ Interaction-only: test_call_count, test_call_args (test_mixed and test_tuple_mixed also assert on a result;
9
+ test_empty_equal compares two empty lists, a plain check)
10
+ Mock-heavy: test_setattr_4 (4 monkeypatch.setattr; test_setattr_3 has 3)
11
+ Private access: test_module_private (demo._queue._requeue through a module alias),
12
+ test_local_private (the same through a function-local alias `module`)
13
+ No smell: test_check (check_equal from conftest), test_expect (expect_equal from conftest),
14
+ test_conftest_private (conftest._conftest_private through `from tests import conftest`),
15
+ test_local_conftest (the same through a function-local alias `module`, defined after test_local_private).
16
+ Expected smells by test of test_maint_rules.py:
17
+ Mystery guest: test_guest_name (open(path), path a literal), test_guest_path (Path from a literal, then read_text)
18
+ Eager test: test_eager_helpers (3 act-then-check_equal cycles)
19
+ No smell: test_swallow_checked (its handler calls check_equal), test_long (54 lines of asserts, a long test).
20
+ Every call takes 1.125 s (fakeclock), so every test is slow.
21
+ """
22
+ from fixture_repo import build_repo, git
23
+
24
+ CONFTEST = '''def check_equal(a, b):
25
+ assert a == b
26
+
27
+
28
+ def expect_equal(a, b):
29
+ assert a == b
30
+
31
+
32
+ def _conftest_private():
33
+ return 1
34
+ '''
35
+ RULES = '''import os
36
+ from unittest.mock import MagicMock, call
37
+
38
+ import demo._queue as queue
39
+ from demo import board
40
+ from tests import conftest
41
+ from tests.conftest import check_equal, expect_equal
42
+
43
+
44
+ def test_check():
45
+ check_equal(board.render(1), "1")
46
+
47
+
48
+ def test_expect():
49
+ expect_equal(board.render(1), "1")
50
+
51
+
52
+ def test_call_count():
53
+ sender = MagicMock()
54
+ sender.send("hi")
55
+ assert sender.send.call_count == 1
56
+
57
+
58
+ def test_call_args():
59
+ sender = MagicMock()
60
+ sender.send("hi")
61
+ assert sender.send.call_args == call("hi")
62
+
63
+
64
+ def test_setattr_3(monkeypatch):
65
+ monkeypatch.setattr(os, "getcwd", lambda: "/")
66
+ monkeypatch.setattr(os, "getpid", lambda: 1)
67
+ monkeypatch.setattr(os, "getppid", lambda: 1)
68
+ assert os.getpid() == 1
69
+
70
+
71
+ def test_setattr_4(monkeypatch):
72
+ monkeypatch.setattr(os, "getcwd", lambda: "/")
73
+ monkeypatch.setattr(os, "getpid", lambda: 1)
74
+ monkeypatch.setattr(os, "getppid", lambda: 1)
75
+ monkeypatch.setattr(os, "getuid", lambda: 1)
76
+ assert os.getpid() == 1
77
+
78
+
79
+ def test_conftest_private():
80
+ assert conftest._conftest_private() == 1
81
+
82
+
83
+ def test_module_private():
84
+ assert queue._requeue() == 1
85
+
86
+
87
+ def test_local_private():
88
+ import demo._queue as module
89
+ assert module._requeue() == 1
90
+
91
+
92
+ def test_local_conftest():
93
+ from tests import conftest as module
94
+ assert module._conftest_private() == 1
95
+
96
+
97
+ def test_mixed():
98
+ sender = MagicMock()
99
+ result = board.render(1)
100
+ sender.send(result)
101
+ assert result == "1" and sender.send.call_count == 1
102
+
103
+
104
+ def test_tuple_mixed():
105
+ sender = MagicMock()
106
+ result = board.render(1)
107
+ sender.send(result)
108
+ assert (result, sender.send.call_count) == ("1", 1)
109
+
110
+
111
+ def test_empty_equal():
112
+ sender = MagicMock()
113
+ sender.send(board.render(1))
114
+ assert [] == []
115
+
116
+
117
+ class TestA:
118
+ def test_board(self):
119
+ board.render(1)
120
+
121
+
122
+ class TestB:
123
+ def test_board(self):
124
+ assert board.render(1) == "1"
125
+
126
+
127
+ class Base:
128
+ def test_inherited(self):
129
+ assert board.render(1) == "1"
130
+
131
+
132
+ class TestOther:
133
+ def test_inherited(self):
134
+ board.render(1)
135
+
136
+
137
+ class TestChild(Base):
138
+ pass
139
+
140
+
141
+ class DBase:
142
+ def test_diamond(self):
143
+ assert board.render(1) == "1"
144
+
145
+
146
+ class DLeft(DBase):
147
+ pass
148
+
149
+
150
+ class DRight(DBase):
151
+ def test_diamond(self):
152
+ board.render(1)
153
+
154
+
155
+ class TestDiamond(DLeft, DRight):
156
+ pass
157
+ '''
158
+
159
+ MAINT = """from pathlib import Path
160
+
161
+ from demo import board
162
+ from tests.conftest import check_equal
163
+
164
+
165
+ def test_guest_name():
166
+ path = "data/app.json"
167
+ with open(path) as handle:
168
+ assert handle.read() == "{}"
169
+
170
+
171
+ def test_guest_path():
172
+ source = Path("data/app.json")
173
+ copied = source
174
+ assert copied.read_text() == "{}"
175
+
176
+
177
+ def test_eager_helpers():
178
+ first = board.render(1)
179
+ check_equal(first, "1")
180
+ second = board.render(2)
181
+ check_equal(second, "2")
182
+ third = board.render(3)
183
+ check_equal(third, "3")
184
+
185
+
186
+ def test_swallow_checked():
187
+ try:
188
+ board.render(1)
189
+ except Exception as error:
190
+ check_equal(str(error), "")
191
+
192
+
193
+ def test_long():
194
+ """ + "".join(f" assert board.render({i}) == '{i}'\n" for i in range(53))
195
+
196
+
197
+ def rules_suite(path):
198
+ repo = build_repo(path)
199
+ (repo / "tests" / "__init__.py").write_text("")
200
+ (repo / "tests" / "conftest.py").write_text(CONFTEST)
201
+ (repo / "demo" / "_queue.py").write_text("def _requeue():\n return 1\n")
202
+ (repo / "tests" / "test_rules.py").write_text(RULES)
203
+ (repo / "tests" / "test_maint_rules.py").write_text(MAINT)
204
+ (repo / "data").mkdir()
205
+ (repo / "data" / "app.json").write_text("{}")
206
+ git(repo, "add", "-A")
207
+ git(repo, "commit", "-q", "-m", "suite")
208
+ return repo
@@ -0,0 +1,65 @@
1
+ """Rules file the scoring tests hand to weigh.py through TEST_WEIGH_IN_RULES=<path>.
2
+
3
+ Interface the tests pin (the spec leaves the TOML keys and the snapshot JSON keys open):
4
+ rules.toml: version = 1; [pillars.<key>] name = "..."; [pillars.<key>.metrics.<id>] name, weight,
5
+ optional partial_weight, target, bad, optional log = true. Percentages are 0-100,
6
+ durations are seconds. Pillar keys: regression, refactoring, feedback,
7
+ maintainability, economy.
8
+ snapshot: rules {version, sha256}; metrics {<id>: {value, score}}; pillars {<key>: {score, partial}}.
9
+ Scores are unrounded floats; only the dashboard rounds and clamps.
10
+ """
11
+ import hashlib
12
+
13
+ # pillar key: (name, [(metric id, name, weight, partial weight, target, bad, log scale)])
14
+ STARTER = {
15
+ "regression": ("Protection against regressions", [
16
+ ("mutation_score", "Mutation score", .45, None, 80, 40, False),
17
+ ("branch_coverage", "Branch coverage", .25, .60, 90, 50, False),
18
+ ("hollow_tests", "Hollow tests", .20, .40, 0, 10, False),
19
+ ("pseudo_tested_functions", "Pseudo-tested functions", .10, None, 0, 15, False),
20
+ ]),
21
+ "refactoring": ("Resistance to refactoring", [
22
+ ("brittle_test_files", "Brittle test files", .40, None, 15, 60, False),
23
+ ("private_access", "Tests with private access", .25, None, 2, 30, False),
24
+ ("mock_heavy", "Mock-heavy tests", .20, None, 5, 30, False),
25
+ ("interaction_only", "Interaction-only tests", .15, None, 5, 30, False),
26
+ ]),
27
+ "feedback": ("Fast feedback", [
28
+ ("total_runtime", "Total runtime", .40, None, 60, 600, True),
29
+ ("p95_duration", "p95 test duration", .30, None, .1, 2, True),
30
+ ("slowest_decile_share", "Runtime share of slowest 10% of tests", .15, None, 40, 90, False),
31
+ ("tests_over_10s", "Tests over 10 s", .15, None, 0, 2, False),
32
+ ]),
33
+ "maintainability": ("Maintainability", [
34
+ ("smelly_tests", "Tests with a maintainability smell", .50, None, 5, 40, False),
35
+ ("long_tests", "Tests longer than 50 lines", .20, None, 2, 20, False),
36
+ ("test_source_ratio", "Test : source lines-of-code ratio", .30, None, 1.5, 4.0, False),
37
+ ]),
38
+ "economy": ("Economy", [
39
+ ("no_unique_coverage", "Tests with no unique coverage", .35, .60, 10, 50, False),
40
+ ("subsumed_in_kill_matrix", "Tests subsumed in the kill matrix", .40, None, 5, 35, False),
41
+ ("duplicate_clusters", "Tests in a duplicate-body cluster", .25, .40, 2, 20, False),
42
+ ]),
43
+ }
44
+
45
+
46
+ def write_rules(path, **overrides):
47
+ """Write the version 1 starter rules; overrides are `<metric id>={weight=..., target=..., bad=...}`."""
48
+ lines = ["version = 1", ""]
49
+ for key, (name, metrics) in STARTER.items():
50
+ lines += [f"[pillars.{key}]", f'name = "{name}"', ""]
51
+ for mid, mname, weight, partial, target, bad, log in metrics:
52
+ m = {**dict(weight=weight, target=target, bad=bad), **overrides.get(mid, {})}
53
+ lines += [f"[pillars.{key}.metrics.{mid}]", f'name = "{mname}"']
54
+ lines += [f"{k} = {v!r}" for k, v in m.items()]
55
+ if partial is not None:
56
+ lines.append(f"partial_weight = {partial!r}")
57
+ if log:
58
+ lines.append("log = true")
59
+ lines.append("")
60
+ path.write_text("\n".join(lines))
61
+ return path
62
+
63
+
64
+ def sha256(path):
65
+ return hashlib.sha256(path.read_bytes()).hexdigest()
@@ -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)