assert-one-assert-per-test 20261111143626__py3-none-any.whl
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.
- assert_one_assert_per_test/__init__.py +0 -0
- assert_one_assert_per_test/__main__.py +3 -0
- assert_one_assert_per_test/cli.py +274 -0
- assert_one_assert_per_test/finding.py +25 -0
- assert_one_assert_per_test/py.typed +0 -0
- assert_one_assert_per_test/rust.py +139 -0
- assert_one_assert_per_test/scanner.py +17 -0
- assert_one_assert_per_test-20261111143626.dist-info/METADATA +199 -0
- assert_one_assert_per_test-20261111143626.dist-info/RECORD +13 -0
- assert_one_assert_per_test-20261111143626.dist-info/WHEEL +5 -0
- assert_one_assert_per_test-20261111143626.dist-info/entry_points.txt +2 -0
- assert_one_assert_per_test-20261111143626.dist-info/licenses/LICENSE.txt +190 -0
- assert_one_assert_per_test-20261111143626.dist-info/top_level.txt +1 -0
|
File without changes
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import fnmatch
|
|
5
|
+
import glob
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
|
|
11
|
+
from .finding import Finding, Unparsable
|
|
12
|
+
from .scanner import SCANNERS, Scanner, scanner_for
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
|
|
17
|
+
EXIT_SUCCESS = 0
|
|
18
|
+
EXIT_FINDINGS = 1
|
|
19
|
+
EXIT_ERROR = 2
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class ScanResult:
|
|
24
|
+
findings: list[Finding]
|
|
25
|
+
files_scanned: int
|
|
26
|
+
had_error: bool
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def create_parser() -> argparse.ArgumentParser:
|
|
30
|
+
parser = argparse.ArgumentParser(
|
|
31
|
+
prog="assert-one-assert-per-test",
|
|
32
|
+
description="Assert that each test function contains exactly one assertion.",
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
parser.add_argument(
|
|
36
|
+
"files",
|
|
37
|
+
nargs="+",
|
|
38
|
+
metavar="FILE",
|
|
39
|
+
help=(
|
|
40
|
+
"One or more file paths, directory paths, or glob patterns to scan. "
|
|
41
|
+
"Directories are scanned recursively for source files of a supported "
|
|
42
|
+
f"language ({', '.join(sorted(SCANNERS))})."
|
|
43
|
+
),
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
parser.add_argument(
|
|
47
|
+
"--exclude",
|
|
48
|
+
metavar="PATTERNS",
|
|
49
|
+
help="Comma-separated glob patterns to exclude files.",
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
output_group = parser.add_mutually_exclusive_group()
|
|
53
|
+
output_group.add_argument(
|
|
54
|
+
"--quiet",
|
|
55
|
+
action="store_true",
|
|
56
|
+
help="Suppress all output. Exit code indicates success (0) or findings (1).",
|
|
57
|
+
)
|
|
58
|
+
output_group.add_argument(
|
|
59
|
+
"--count",
|
|
60
|
+
action="store_true",
|
|
61
|
+
help="Output only the count of findings.",
|
|
62
|
+
)
|
|
63
|
+
output_group.add_argument(
|
|
64
|
+
"--verbose",
|
|
65
|
+
action="store_true",
|
|
66
|
+
help="Show detailed processing information.",
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
behavior_group = parser.add_mutually_exclusive_group()
|
|
70
|
+
behavior_group.add_argument(
|
|
71
|
+
"--fail-fast",
|
|
72
|
+
action="store_true",
|
|
73
|
+
help="Exit immediately after finding the first issue.",
|
|
74
|
+
)
|
|
75
|
+
behavior_group.add_argument(
|
|
76
|
+
"--warn-only",
|
|
77
|
+
action="store_true",
|
|
78
|
+
help="Always exit with code 0, even if findings exist.",
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
return parser
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def parse_patterns(patterns_str: str | None) -> list[str]:
|
|
85
|
+
if not patterns_str:
|
|
86
|
+
return []
|
|
87
|
+
return [p.strip() for p in patterns_str.split(",") if p.strip()]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _is_glob_pattern(path: str) -> bool:
|
|
91
|
+
return any(c in path for c in ("*", "?", "["))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _expand_glob(pattern: str) -> tuple[list[str], bool]:
|
|
95
|
+
matched = glob.glob(pattern, recursive=True, include_hidden=True)
|
|
96
|
+
files = []
|
|
97
|
+
for path in matched:
|
|
98
|
+
if os.path.isfile(path):
|
|
99
|
+
files.append(path)
|
|
100
|
+
elif os.path.isdir(path):
|
|
101
|
+
files.extend(_expand_directory(path))
|
|
102
|
+
return (files, bool(matched))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _expand_directory(directory: str) -> list[str]:
|
|
106
|
+
files = []
|
|
107
|
+
for root, dirs, filenames in os.walk(directory):
|
|
108
|
+
dirs[:] = [d for d in dirs if not d.startswith(".")]
|
|
109
|
+
for filename in filenames:
|
|
110
|
+
if scanner_for(filename) is not None:
|
|
111
|
+
files.append(os.path.join(root, filename))
|
|
112
|
+
return files
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _iter_files(paths: Sequence[str]) -> tuple[list[str], list[str]]:
|
|
116
|
+
files: list[str] = []
|
|
117
|
+
missing: list[str] = []
|
|
118
|
+
|
|
119
|
+
for path in paths:
|
|
120
|
+
if _is_glob_pattern(path):
|
|
121
|
+
matched_files, found = _expand_glob(path)
|
|
122
|
+
if found:
|
|
123
|
+
files.extend(matched_files)
|
|
124
|
+
else:
|
|
125
|
+
missing.append(path)
|
|
126
|
+
elif os.path.isfile(path):
|
|
127
|
+
files.append(path)
|
|
128
|
+
elif os.path.isdir(path):
|
|
129
|
+
files.extend(_expand_directory(path))
|
|
130
|
+
else:
|
|
131
|
+
missing.append(path)
|
|
132
|
+
|
|
133
|
+
seen: set[str] = set()
|
|
134
|
+
unique_files: list[str] = []
|
|
135
|
+
for f in files:
|
|
136
|
+
normalized = os.path.normpath(f)
|
|
137
|
+
if normalized not in seen:
|
|
138
|
+
seen.add(normalized)
|
|
139
|
+
unique_files.append(f)
|
|
140
|
+
|
|
141
|
+
return (unique_files, missing)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _should_skip_file(path: str, exclude_patterns: list[str]) -> bool:
|
|
145
|
+
return any(
|
|
146
|
+
fnmatch.fnmatch(path, pattern)
|
|
147
|
+
or fnmatch.fnmatch(os.path.basename(path), pattern)
|
|
148
|
+
for pattern in exclude_patterns
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _scan_one(path: str, scanner: Scanner) -> list[Finding] | None:
|
|
153
|
+
try:
|
|
154
|
+
with open(path, "rb") as f:
|
|
155
|
+
content = f.read()
|
|
156
|
+
except OSError as e:
|
|
157
|
+
print(f"Error reading {path}: {e}", file=sys.stderr)
|
|
158
|
+
return None
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
return scanner(path, content)
|
|
162
|
+
except Unparsable as e:
|
|
163
|
+
print(f"Syntax error in {path}: {e}", file=sys.stderr)
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def process_files(
|
|
168
|
+
files: list[str],
|
|
169
|
+
exclude_patterns: list[str],
|
|
170
|
+
verbose: bool = False,
|
|
171
|
+
fail_fast: bool = False,
|
|
172
|
+
) -> ScanResult:
|
|
173
|
+
findings: list[Finding] = []
|
|
174
|
+
files_scanned = 0
|
|
175
|
+
had_error = False
|
|
176
|
+
|
|
177
|
+
for path in sorted(files):
|
|
178
|
+
scanner = scanner_for(path)
|
|
179
|
+
if scanner is None:
|
|
180
|
+
if verbose:
|
|
181
|
+
print(f"Skipping (unsupported language): {path}")
|
|
182
|
+
continue
|
|
183
|
+
|
|
184
|
+
if _should_skip_file(path, exclude_patterns):
|
|
185
|
+
if verbose:
|
|
186
|
+
print(f"Skipping (excluded): {path}")
|
|
187
|
+
continue
|
|
188
|
+
|
|
189
|
+
if verbose:
|
|
190
|
+
print(f"Scanning: {path}")
|
|
191
|
+
|
|
192
|
+
file_findings = _scan_one(path, scanner)
|
|
193
|
+
if file_findings is None:
|
|
194
|
+
had_error = True
|
|
195
|
+
continue
|
|
196
|
+
|
|
197
|
+
files_scanned += 1
|
|
198
|
+
findings.extend(file_findings)
|
|
199
|
+
|
|
200
|
+
if verbose:
|
|
201
|
+
for finding in file_findings:
|
|
202
|
+
print(f" Found: {finding}")
|
|
203
|
+
|
|
204
|
+
if findings and fail_fast:
|
|
205
|
+
break
|
|
206
|
+
|
|
207
|
+
return ScanResult(
|
|
208
|
+
findings=findings,
|
|
209
|
+
files_scanned=files_scanned,
|
|
210
|
+
had_error=had_error,
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def output_findings(
|
|
215
|
+
findings: list[Finding],
|
|
216
|
+
count_mode: bool = False,
|
|
217
|
+
) -> None:
|
|
218
|
+
if count_mode:
|
|
219
|
+
print(len(findings))
|
|
220
|
+
else:
|
|
221
|
+
for finding in findings:
|
|
222
|
+
print(finding)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def determine_exit_code(result: ScanResult, warn_only: bool = False) -> int:
|
|
226
|
+
if warn_only:
|
|
227
|
+
return EXIT_SUCCESS
|
|
228
|
+
if result.findings:
|
|
229
|
+
return EXIT_FINDINGS
|
|
230
|
+
if result.had_error:
|
|
231
|
+
return EXIT_ERROR
|
|
232
|
+
return EXIT_SUCCESS
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def main(argv: Sequence[str] | None = None) -> None:
|
|
236
|
+
parser = create_parser()
|
|
237
|
+
args = parser.parse_args(argv)
|
|
238
|
+
|
|
239
|
+
exclude_patterns = parse_patterns(args.exclude)
|
|
240
|
+
|
|
241
|
+
files, missing = _iter_files(args.files)
|
|
242
|
+
|
|
243
|
+
for path in missing:
|
|
244
|
+
print(f"Error: Path not found: {path}", file=sys.stderr)
|
|
245
|
+
|
|
246
|
+
if not files and missing:
|
|
247
|
+
sys.exit(EXIT_ERROR)
|
|
248
|
+
|
|
249
|
+
if args.verbose:
|
|
250
|
+
print(f"Scanning {len(files)} file(s) for tests...")
|
|
251
|
+
if exclude_patterns:
|
|
252
|
+
print(f"Excluding patterns: {', '.join(exclude_patterns)}")
|
|
253
|
+
print()
|
|
254
|
+
|
|
255
|
+
result = process_files(
|
|
256
|
+
files=files,
|
|
257
|
+
exclude_patterns=exclude_patterns,
|
|
258
|
+
verbose=args.verbose,
|
|
259
|
+
fail_fast=args.fail_fast,
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
if missing:
|
|
263
|
+
result.had_error = True
|
|
264
|
+
|
|
265
|
+
if args.verbose:
|
|
266
|
+
print()
|
|
267
|
+
print(f"Files scanned: {result.files_scanned}")
|
|
268
|
+
print(f"Findings: {len(result.findings)}")
|
|
269
|
+
if result.had_error:
|
|
270
|
+
print("Errors occurred during scanning.")
|
|
271
|
+
elif not args.quiet:
|
|
272
|
+
output_findings(result.findings, args.count)
|
|
273
|
+
|
|
274
|
+
sys.exit(determine_exit_code(result, args.warn_only))
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class Finding:
|
|
8
|
+
path: str
|
|
9
|
+
line_number: int
|
|
10
|
+
function_name: str
|
|
11
|
+
assert_count: int
|
|
12
|
+
conjunction: bool = False
|
|
13
|
+
|
|
14
|
+
def __str__(self) -> str:
|
|
15
|
+
suffix = ":conjunction" if self.conjunction else ""
|
|
16
|
+
return (
|
|
17
|
+
f"{self.path}:{self.line_number}:{self.function_name}"
|
|
18
|
+
f":{self.assert_count}{suffix}"
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Unparsable(Exception):
|
|
23
|
+
def __init__(self, line_number: int) -> None:
|
|
24
|
+
super().__init__(f"line {line_number}")
|
|
25
|
+
self.line_number = line_number
|
|
File without changes
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
import tree_sitter_rust
|
|
6
|
+
from tree_sitter import Language, Parser
|
|
7
|
+
|
|
8
|
+
from .finding import Finding, Unparsable
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from collections.abc import Iterator
|
|
12
|
+
|
|
13
|
+
from tree_sitter import Node
|
|
14
|
+
|
|
15
|
+
RUST = Language(tree_sitter_rust.language())
|
|
16
|
+
|
|
17
|
+
TEST_ATTRIBUTES = frozenset({"test", "rstest", "test_case"})
|
|
18
|
+
PANIC_ATTRIBUTE = "should_panic"
|
|
19
|
+
ASSERTION_FAMILIES = ("assert", "debug_assert")
|
|
20
|
+
COMMENTS = frozenset({"line_comment", "block_comment"})
|
|
21
|
+
NESTED_ITEMS = frozenset(
|
|
22
|
+
{"function_item", "impl_item", "mod_item", "trait_item"}
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def text(node: Node) -> str:
|
|
27
|
+
return (node.text or b"").decode("utf-8", "replace")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def last_segment(path: Node) -> str:
|
|
31
|
+
name = path.child_by_field_name("name")
|
|
32
|
+
return text(path if name is None else name)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def attribute_names(function: Node) -> list[str]:
|
|
36
|
+
names: list[str] = []
|
|
37
|
+
sibling = function.prev_named_sibling
|
|
38
|
+
while sibling is not None and (
|
|
39
|
+
sibling.type == "attribute_item" or sibling.type in COMMENTS
|
|
40
|
+
):
|
|
41
|
+
if sibling.type == "attribute_item":
|
|
42
|
+
attribute = sibling.named_children[0]
|
|
43
|
+
names.append(last_segment(attribute.named_children[0]))
|
|
44
|
+
sibling = sibling.prev_named_sibling
|
|
45
|
+
return names
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def is_test_function(function: Node) -> bool:
|
|
49
|
+
return any(name in TEST_ATTRIBUTES for name in attribute_names(function))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def is_assertion_macro(name: str) -> bool:
|
|
53
|
+
return any(
|
|
54
|
+
name == family or name.startswith(f"{family}_")
|
|
55
|
+
for family in ASSERTION_FAMILIES
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def macro_name(macro: Node) -> str:
|
|
60
|
+
path = macro.child_by_field_name("macro")
|
|
61
|
+
return "" if path is None else last_segment(path)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def assertion_macros(node: Node) -> Iterator[Node]:
|
|
65
|
+
for child in node.named_children:
|
|
66
|
+
if child.type in NESTED_ITEMS:
|
|
67
|
+
continue
|
|
68
|
+
if child.type == "macro_invocation" and is_assertion_macro(
|
|
69
|
+
macro_name(child)
|
|
70
|
+
):
|
|
71
|
+
yield child
|
|
72
|
+
yield from assertion_macros(child)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def is_operand(token: Node | None) -> bool:
|
|
76
|
+
return token is not None and (token.is_named or token.type == "?")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def claim_operators(macro: Node) -> list[str]:
|
|
80
|
+
operators: list[str] = []
|
|
81
|
+
previous: Node | None = None
|
|
82
|
+
for token in macro.named_children[-1].children[1:-1]:
|
|
83
|
+
if token.type == ",":
|
|
84
|
+
break
|
|
85
|
+
if token.type in ("&&", "||") and is_operand(previous):
|
|
86
|
+
operators.append(token.type)
|
|
87
|
+
previous = token
|
|
88
|
+
return operators
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def conjunct_count(macro: Node) -> int:
|
|
92
|
+
if macro_name(macro) not in ASSERTION_FAMILIES:
|
|
93
|
+
return 0
|
|
94
|
+
operators = claim_operators(macro)
|
|
95
|
+
if "||" in operators or "&&" not in operators:
|
|
96
|
+
return 0
|
|
97
|
+
return operators.count("&&") + 1
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_functions(node: Node) -> Iterator[Node]:
|
|
101
|
+
for child in node.named_children:
|
|
102
|
+
if child.type == "function_item" and is_test_function(child):
|
|
103
|
+
yield child
|
|
104
|
+
yield from test_functions(child)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def first_fault(node: Node) -> Node:
|
|
108
|
+
if node.is_error or node.is_missing:
|
|
109
|
+
return node
|
|
110
|
+
return first_fault(next(child for child in node.children if child.has_error))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def check_function(path: str, function: Node) -> list[Finding]:
|
|
114
|
+
name = text(function.child_by_field_name("name") or function)
|
|
115
|
+
body = function.child_by_field_name("body")
|
|
116
|
+
macros = [] if body is None else list(assertion_macros(body))
|
|
117
|
+
panics = attribute_names(function).count(PANIC_ATTRIBUTE)
|
|
118
|
+
count = len(macros) + panics
|
|
119
|
+
findings = []
|
|
120
|
+
if count != 1:
|
|
121
|
+
findings.append(Finding(path, function.start_point.row + 1, name, count))
|
|
122
|
+
for macro in macros:
|
|
123
|
+
conjuncts = conjunct_count(macro)
|
|
124
|
+
if conjuncts:
|
|
125
|
+
findings.append(
|
|
126
|
+
Finding(path, macro.start_point.row + 1, name, conjuncts, True)
|
|
127
|
+
)
|
|
128
|
+
return findings
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def scan(path: str, source: bytes) -> list[Finding]:
|
|
132
|
+
root = Parser(RUST).parse(source).root_node
|
|
133
|
+
if root.has_error:
|
|
134
|
+
raise Unparsable(first_fault(root).start_point.row + 1)
|
|
135
|
+
return [
|
|
136
|
+
finding
|
|
137
|
+
for function in test_functions(root)
|
|
138
|
+
for finding in check_function(path, function)
|
|
139
|
+
]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
|
|
6
|
+
from . import rust
|
|
7
|
+
from .finding import Finding
|
|
8
|
+
|
|
9
|
+
Scanner = Callable[[str, bytes], list[Finding]]
|
|
10
|
+
|
|
11
|
+
SCANNERS: dict[str, Scanner] = {
|
|
12
|
+
".rs": rust.scan,
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def scanner_for(path: str) -> Scanner | None:
|
|
17
|
+
return SCANNERS.get(os.path.splitext(path)[1])
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: assert-one-assert-per-test
|
|
3
|
+
Version: 20261111143626
|
|
4
|
+
Summary: CLI tool to assert that each test function, in any supported language, contains exactly one assertion
|
|
5
|
+
Author-email: 10U Labs <dev@10ulabs.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/10U-Labs/assert-one-assert-per-test
|
|
8
|
+
Project-URL: Repository, https://github.com/10U-Labs/assert-one-assert-per-test
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Rust
|
|
19
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
20
|
+
Classifier: Topic :: Software Development :: Testing
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE.txt
|
|
24
|
+
Requires-Dist: tree-sitter>=0.25
|
|
25
|
+
Requires-Dist: tree-sitter-rust>=0.24
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# assert-one-assert-per-test
|
|
29
|
+
|
|
30
|
+
Assert that each test function contains exactly one assertion, in any language
|
|
31
|
+
the tool can read. Rust is the first.
|
|
32
|
+
|
|
33
|
+
It is the language-independent sibling of
|
|
34
|
+
[assert-one-assert-per-pytest](https://github.com/10U-Labs/assert-one-assert-per-pytest),
|
|
35
|
+
and reports the same findings in the same format.
|
|
36
|
+
|
|
37
|
+
## Why One Assert Per Test?
|
|
38
|
+
|
|
39
|
+
The "one assert per test" pattern encourages writing focused, atomic tests that
|
|
40
|
+
verify a single behavior. Benefits include:
|
|
41
|
+
|
|
42
|
+
- **Clear failure messages**: When a test fails, you know exactly what behavior broke
|
|
43
|
+
- **Better test names**: Tests naturally describe specific behaviors
|
|
44
|
+
- **Easier maintenance**: Changes to one behavior don't affect unrelated assertions
|
|
45
|
+
- **Faster debugging**: No need to hunt through multiple assertions
|
|
46
|
+
|
|
47
|
+
## Installation
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install assert-one-assert-per-test
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Usage
|
|
54
|
+
|
|
55
|
+
### Command Line
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
# Scan a crate's sources and integration tests
|
|
59
|
+
assert-one-assert-per-test src tests
|
|
60
|
+
|
|
61
|
+
# Scan specific files
|
|
62
|
+
assert-one-assert-per-test src/lib.rs tests/cli.rs
|
|
63
|
+
|
|
64
|
+
# Use glob patterns
|
|
65
|
+
assert-one-assert-per-test "crates/**/*.rs"
|
|
66
|
+
|
|
67
|
+
# Exclude patterns
|
|
68
|
+
assert-one-assert-per-test . --exclude "*/target/*"
|
|
69
|
+
|
|
70
|
+
# Verbose output
|
|
71
|
+
assert-one-assert-per-test src --verbose
|
|
72
|
+
|
|
73
|
+
# Fail fast (exit on first finding)
|
|
74
|
+
assert-one-assert-per-test src --fail-fast
|
|
75
|
+
|
|
76
|
+
# Warn only (always exit 0)
|
|
77
|
+
assert-one-assert-per-test src --warn-only
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
A directory is read recursively for files in a supported language, skipping
|
|
81
|
+
hidden directories. A file in a language the tool cannot read is passed over.
|
|
82
|
+
|
|
83
|
+
### GitHub Actions
|
|
84
|
+
|
|
85
|
+
```yaml
|
|
86
|
+
- uses: 10U-Labs/assert-one-assert-per-test@v1
|
|
87
|
+
with:
|
|
88
|
+
files: "src tests"
|
|
89
|
+
exclude: "*/target/*"
|
|
90
|
+
verbose: "true"
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### As a Python Module
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
python -m assert_one_assert_per_test src tests
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Supported Languages
|
|
100
|
+
|
|
101
|
+
| Language | Suffixes | Parser |
|
|
102
|
+
| -------- | -------- | ------------------------------------------------------------------- |
|
|
103
|
+
| Rust | `.rs` | [tree-sitter-rust](https://github.com/tree-sitter/tree-sitter-rust) |
|
|
104
|
+
|
|
105
|
+
Each language is read by its own grammar rather than by matching text, so an
|
|
106
|
+
`assert!` inside a string or a comment is never counted.
|
|
107
|
+
|
|
108
|
+
## Output Format
|
|
109
|
+
|
|
110
|
+
Default output shows one finding per line:
|
|
111
|
+
|
|
112
|
+
```text
|
|
113
|
+
src/lib.rs:10:adds:0
|
|
114
|
+
src/lib.rs:15:adds_twice:2
|
|
115
|
+
src/lib.rs:22:adds_both:2:conjunction
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Format: `file_path:line_number:function_name:assert_count`
|
|
119
|
+
|
|
120
|
+
The line number is the line the function's `fn` keyword is on, after any
|
|
121
|
+
attributes. A conjunction finding adds a fifth field, `conjunction`. Its line
|
|
122
|
+
number is the assertion rather than the enclosing function, and its count is the
|
|
123
|
+
number of conjuncts the expression joins.
|
|
124
|
+
|
|
125
|
+
## Exit Codes
|
|
126
|
+
|
|
127
|
+
- `0`: No findings (or `--warn-only` specified)
|
|
128
|
+
- `1`: Findings detected
|
|
129
|
+
- `2`: Error (missing files, unreadable files, syntax errors)
|
|
130
|
+
|
|
131
|
+
## Rust
|
|
132
|
+
|
|
133
|
+
### What Counts as a Test?
|
|
134
|
+
|
|
135
|
+
A function carrying an attribute whose last path segment is `test`, `rstest` or
|
|
136
|
+
`test_case`. That covers `#[test]`, `#[tokio::test]`, `#[async_std::test]`,
|
|
137
|
+
`#[sqlx::test]`, `#[rstest]` and `#[test_case(...)]`, wherever the function is,
|
|
138
|
+
including inside `#[cfg(test)] mod tests`. `#[cfg(test)]` on its own does not
|
|
139
|
+
make a function a test.
|
|
140
|
+
|
|
141
|
+
### What Counts as an Assertion?
|
|
142
|
+
|
|
143
|
+
- A macro whose last path segment is `assert` or `debug_assert`, or starts with
|
|
144
|
+
`assert_` or `debug_assert_`: `assert!`, `assert_eq!`, `assert_ne!`,
|
|
145
|
+
`debug_assert!`, `debug_assert_eq!`, `debug_assert_ne!`,
|
|
146
|
+
`pretty_assertions::assert_eq!`, `assert_matches!`, and the `assert_*_snapshot!`
|
|
147
|
+
macros from `insta`.
|
|
148
|
+
- A `#[should_panic]` attribute on the test, which asserts that the body panics.
|
|
149
|
+
|
|
150
|
+
An assertion inside a closure or a loop in the test body is counted once, where
|
|
151
|
+
it is written. An assertion inside an item nested in the test, a `fn`, `impl`,
|
|
152
|
+
`trait` or `mod`, is not counted, since nothing says the test runs it. Neither
|
|
153
|
+
is an assertion in a helper function the test calls.
|
|
154
|
+
|
|
155
|
+
### Conjunctions
|
|
156
|
+
|
|
157
|
+
An `assert!` or `debug_assert!` whose condition is a top-level `&&` carries one
|
|
158
|
+
claim per conjunct, so a red run names the whole expression rather than the
|
|
159
|
+
claim that broke. The tool reports it the way it reports a second assertion.
|
|
160
|
+
|
|
161
|
+
```rust
|
|
162
|
+
#[test]
|
|
163
|
+
fn parses() {
|
|
164
|
+
assert!(config.name == "app" && config.port == 8080);
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Only a top-level `&&` is refused. These are all allowed:
|
|
169
|
+
|
|
170
|
+
- `assert!(a || b)`, one claim about two alternatives.
|
|
171
|
+
- `assert!(a || b && c)`, where `&&` binds tighter and the claim being made is
|
|
172
|
+
the disjunction.
|
|
173
|
+
- `assert!(!(a && b))`, which is `!a || !b`, and so a disjunction.
|
|
174
|
+
- `assert!(items.iter().all(|i| i.a && i.b))`, where the `&&` is evaluated per
|
|
175
|
+
item inside a closure rather than joining two claims about the test.
|
|
176
|
+
- `assert!(a, "{}", b && c)` and `assert!(a, "b && c")`, where the `&&` is in
|
|
177
|
+
the message.
|
|
178
|
+
- `assert_eq!(a && b, true)`, which claims one equality.
|
|
179
|
+
|
|
180
|
+
### Syntax Errors
|
|
181
|
+
|
|
182
|
+
A file tree-sitter cannot parse completely is reported as a syntax error naming
|
|
183
|
+
the first line it could not place, and the run exits 2, because a test the
|
|
184
|
+
grammar misread could be counted wrongly.
|
|
185
|
+
|
|
186
|
+
## Options
|
|
187
|
+
|
|
188
|
+
| Option | Description |
|
|
189
|
+
| -------------------- | ------------------------------------------ |
|
|
190
|
+
| `--exclude PATTERNS` | Glob patterns to exclude (comma-separated) |
|
|
191
|
+
| `--quiet` | Suppress all output (exit code only) |
|
|
192
|
+
| `--count` | Print only the number of findings |
|
|
193
|
+
| `--verbose` | Show detailed processing information |
|
|
194
|
+
| `--fail-fast` | Exit after the first file with a finding |
|
|
195
|
+
| `--warn-only` | Always exit 0, even with findings |
|
|
196
|
+
|
|
197
|
+
## License
|
|
198
|
+
|
|
199
|
+
Apache 2.0 - See [LICENSE.txt](LICENSE.txt)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
assert_one_assert_per_test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
assert_one_assert_per_test/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
|
|
3
|
+
assert_one_assert_per_test/cli.py,sha256=miHp8ewyhYnFgBZ3f7UJdVfwWuGrQwcr76pI-C3tBuA,7247
|
|
4
|
+
assert_one_assert_per_test/finding.py,sha256=zPGKasj-CVO_SlwB5uBy_YTAFb44cQgbKd0DnrY6PFs,618
|
|
5
|
+
assert_one_assert_per_test/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
assert_one_assert_per_test/rust.py,sha256=CapXMPFFb8y8lvbRms7sfdoxR-bqk5xlhQmyEIQI7nw,4201
|
|
7
|
+
assert_one_assert_per_test/scanner.py,sha256=I75K9LZ8QVlTDhsXR75kxRCIChBVfcmuYYGAAtMC3KE,338
|
|
8
|
+
assert_one_assert_per_test-20261111143626.dist-info/licenses/LICENSE.txt,sha256=7C7FkuzwSQFE_PL6st5x2YyMN1aiyjZ9ti1s5X45no8,10761
|
|
9
|
+
assert_one_assert_per_test-20261111143626.dist-info/METADATA,sha256=5flJWVGwg9RBEfXHOT-R1OsXhV7mdwzY67Qzzw7sIWY,6948
|
|
10
|
+
assert_one_assert_per_test-20261111143626.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
assert_one_assert_per_test-20261111143626.dist-info/entry_points.txt,sha256=ZUAuHBa1iixBShGaMH_3FR6j6Uc8poNxwza6JqF8hAw,83
|
|
12
|
+
assert_one_assert_per_test-20261111143626.dist-info/top_level.txt,sha256=iZPv_Xq5dKrKjkTrQJuphmcdvfascXyKqMCCet-bCNU,27
|
|
13
|
+
assert_one_assert_per_test-20261111143626.dist-info/RECORD,,
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2024 10U Labs LLC
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
assert_one_assert_per_test
|