Skip to content

7. Tests & CRAP

codeknife tests does two jobs. It reads every test it can find and flags “test theater”: tests with no assertions, tests that only check that something exists, tests that mostly verify mock wiring, tests with loops and branches, and tests that sleep or read the clock. It also scores every non-test function with the CRAP formula, which combines cyclomatic complexity with line coverage from a coverage report. Use it to find tests that pass without proving much and complex code that no test exercises.

Everything here is static. codeknife tests never runs your tests. It reads source files and, if one exists, a coverage report you generated earlier. To check whether your tests actually catch bugs, use Mutation Testing.

The demo crate below has one complex function, grade, with ten if branches, and four weak tests. A Python test file sits next to it.

// src/lib.rs (excerpt)
pub fn grade(score: u32) -> &'static str {
if score >= 90 {
"A"
} else if score >= 80 {
"B"
// ... eight more branches ...
} else {
"J"
}
}
#[test]
fn smoke_grade() {
let _ = grade(95);
}
#[test]
fn parses_something() {
assert!(parse("7").is_ok());
}
#[test]
fn loops_over_cases() {
for s in [95, 85, 75] {
if s >= 90 {
assert_eq!(grade(s), "A");
} else if s >= 80 {
assert_eq!(grade(s), "B");
}
}
}
#[test]
fn error_text() {
std::thread::sleep(std::time::Duration::from_millis(1));
assert_eq!(parse("x").unwrap_err(), "invalid digit found in string".to_string(), "msg");
}
py/test_service.py
from unittest.mock import MagicMock
def test_notifies_user(mocker, monkeypatch):
mailer = MagicMock()
mocker.patch("service.load_user")
monkeypatch.setattr("service.CLOCK", 0)
mailer.send("hi")
mailer.send.assert_called_once()

With no coverage file in the repository, CRAP cannot be computed. CodeKnife runs in complexity-only mode and prints a note with the command that would produce a report for each language it found:

Terminal window
codeknife tests --no-cache --format agent
CODEKNIFE tests status=fail files=2 errors=0 warnings=5 infos=3 elapsed_ms=3
[1] WARNING CK_TEST_ZERO_ASSERT src/lib.rs:34-36 sym=smoke_grade impact=80 | test `smoke_grade` executes with zero assertions | fix: Assert concrete observable outputs or side effects through the public interface.
[2] WARNING CK_TEST_MOCK_THEATER py/test_service.py:5-9 sym=test_notifies_user impact=70 | test `test_notifies_user` sets up 3 mocks and asserts mock calls rather than observable behavior | fix: Test real behavior against in-memory fakes/fixtures instead of verifying mock call wiring.
[3] WARNING CK_TEST_WEAK_ASSERT src/lib.rs:39-41 sym=parses_something impact=65 | test `parses_something` has only weak existence/truthiness assertions (1 weak / 1 total) | fix: Replace `.is_ok()` / `.toBeDefined()` with assertions checking exact returned values or state changes.
[4] WARNING CK_TEST_FLAKE_SMELL src/lib.rs:56-56 sym=error_text impact=60 | wall-clock sleep inside unit test in test `error_text` | fix: Inject deterministic clocks/seeds/channels instead of sleeping or reading wall time.
[5] WARNING CK_TEST_BRANCHING src/lib.rs:44-52 sym=loops_over_cases impact=50 | test `loops_over_cases` contains 3 conditional/loop control-flow branch(es) | fix: Split into deterministic flat test cases or parameterized test tables so assertions never silently skip.
[6] INFO CK_TEST_IMPL_COUPLED py/test_service.py:5-9 sym=test_notifies_user impact=35 | test `test_notifies_user` asserts implementation details (call counts or brittle error strings) | fix: Assert error variants/codes and observable outputs so refactors do not break tests.
[7] INFO CK_TEST_IMPL_COUPLED src/lib.rs:55-58 sym=error_text impact=35 | test `error_text` asserts implementation details (call counts or brittle error strings) | fix: Assert error variants/codes and observable outputs so refactors do not break tests.
[8] INFO CK_TEST_UNCOVERED_COMPLEXITY src/lib.rs:1-23 sym=theater::grade impact=30 | `grade` has high cyclomatic complexity (CC=10) with no coverage report loaded | fix: Split conditional branches into smaller tested functions or supply `--coverage` for CRAP scoring.
NOTE no coverage file found (running complexity-only mode); generate one with: cargo llvm-cov --lcov --output-path lcov.info | pytest --cov --cov-report=xml:coverage.xml

The exit code is 1 because there are warnings.

Generate an LCOV file with cargo llvm-cov and run the same command. CodeKnife finds lcov.info at the repository root on its own:

Terminal window
cargo llvm-cov --lcov --output-path lcov.info
codeknife tests --no-cache --format agent
CODEKNIFE tests status=fail files=2 errors=1 warnings=5 infos=2 elapsed_ms=2
[1] ERROR CK_TEST_HIGH_CRAP src/lib.rs:1-23 sym=theater::grade impact=46 | `grade` CRAP score is 46.4 (CC=10, cov=29%, limit 15.0) | fix: Reduce complexity below 5 or add tests covering `grade` to bring CRAP below 15.0.
[2] WARNING CK_TEST_ZERO_ASSERT src/lib.rs:34-36 sym=smoke_grade impact=80 | test `smoke_grade` executes with zero assertions | fix: Assert concrete observable outputs or side effects through the public interface.
...
[8] INFO CK_TEST_IMPL_COUPLED src/lib.rs:55-58 sym=error_text impact=35 | test `error_text` asserts implementation details (call counts or brittle error strings) | fix: Assert error variants/codes and observable outputs so refactors do not break tests.
NOTE loaded coverage report (lcov, 1 files)

CK_TEST_UNCOVERED_COMPLEXITY is gone and CK_TEST_HIGH_CRAP replaces it. The report covered 6 of the 21 instrumented lines in grade, so coverage is 29% and CRAP is 10² × (1 − 0.286)³ + 10 = 46.4.

You can also pass a report explicitly. Here is a hand-written LCOV file that marks lines 1 to 12 as hit and the rest of grade as missed:

SF:src/lib.rs
DA:1,1
DA:2,1
...
DA:12,1
DA:13,0
...
DA:23,0
end_of_record
Terminal window
codeknife tests --no-cache --coverage ../covdemo/partial.info --format agent
...
[6] WARNING CK_TEST_HIGH_CRAP src/lib.rs:1-23 sym=theater::grade impact=18 | `grade` CRAP score is 17.9 (CC=10, cov=57%, limit 15.0) | fix: Reduce complexity below 5 or add tests covering `grade` to bring CRAP below 15.0.
NOTE loaded coverage report (lcov, 1 files)

A CRAP score of 17.9 is above the limit of 15 but below 30, so the finding is a warning instead of an error.

Flag Effect
--coverage <path> Load this coverage report instead of auto-discovering one. The path is used as given, so a relative path is relative to your current directory, not to --path. If the file cannot be read, the command fails with exit code 2.
--changed Only report findings for files in the git diff. See Diff-CRAP and changed scope.
--since <ref> Base ref for --changed. On its own it does not scope anything.
--strict Turns CK_TEST_ZERO_ASSERT and CK_TEST_WEAK_ASSERT into errors and caps max_crap at 10.0.
--path, --format, --no-cache, --max-items Global flags. See the CLI Reference.
Rule ID Default severity Triggers when Threshold or key --strict Fixer
CK_TEST_ZERO_ASSERT warning A test has zero recognized assertions and does not call a helper that asserts. none becomes error none
CK_TEST_WEAK_ASSERT warning Every assertion in the test is a weak existence or truthiness check. none becomes error none
CK_TEST_MOCK_THEATER warning The test makes 3 or more mock setup calls and its mock-call assertions are at least as many as its other assertions. fixed at 3 setups unchanged none
CK_TEST_BRANCHING warning The test body contains 3 or more if, for, while or try nodes. fixed at 3 unchanged none
CK_TEST_FLAKE_SMELL warning A call in the test sleeps, reads wall-clock time or uses unseeded randomness. One finding per line and smell. none unchanged none
CK_TEST_IMPL_COUPLED info An assertion checks call counts or an exact error string. none unchanged none
CK_TEST_HIGH_CRAP warning, or error when CRAP is 30 or more A coverage report is loaded and a function’s CRAP score is above max_crap. [thresholds] max_crap, default 15.0 limit capped at 10.0 none
CK_TEST_UNCOVERED_COMPLEXITY info No coverage report is loaded and a function’s cyclomatic complexity is 10 or more. fixed at 10 unchanged none

No rule in this blade has an automatic fixer. codeknife fix leaves these findings alone. See the Autofix Engine for the rules it does fix. The full list of rule IDs across all blades is in the Rule Catalogue.

Info findings never fail the run. Warnings and errors do (exit code 1), unless the baseline already records them.

CodeKnife audits a function only if it decides the function is a test. The rules differ per language.

Language What counts as a test
Rust A function with an attribute that is exactly #[test], ends with ::test] (for example #[tokio::test]), contains ::test(, or contains rstest. Attributes containing cfg( do not count. A #[should_panic] attribute counts as one assertion.
Python A function whose name starts with test_ and that is either in a test file or a method of a class whose name starts with Test.
Go A function in a _test.go file whose name starts with Test. Benchmark and Example functions are not audited.
TypeScript, JavaScript A call to it, test, it.only, test.only or it.concurrent whose second argument is an arrow function or a function expression. The test name is the first argument.

it.skip, test.skip and describe are not in that list, so skipped tests and suite wrappers are not audited at all. CodeKnife has no rule for skipped or ignored tests, and no rule for snapshot-only tests.

Test files are also excluded from CRAP scoring. These paths count as test files:

Language Test file paths
Rust starts with tests/ or benches/, contains /tests/ or /benches/, ends with _test.rs or /tests.rs
Python file name starts with test_ or ends with _test.py, or path starts with tests/ or contains /tests/
Go ends with _test.go
TypeScript, JavaScript contains __tests__/, .test. or .spec., starts with test/, tests/ or bench/, or contains /bench/ or /benches/

In Rust, functions inside a #[cfg(test)] module are also treated as test code and are skipped by CRAP, even when they are helpers without #[test].

CodeKnife walks the test body’s syntax tree. For each call, macro invocation or Python assert statement, it takes the first line of that node’s text and checks it against a per-language list. Each matching node counts as one assertion.

Language Counts as an assertion when the first line
Rust starts with assert!, assert_, debug_assert, panic!(, unreachable!(, matches!(, check!( or assert_matches!, or contains .assert(), .assert_, .success() or .failure()
TypeScript, JavaScript starts with assert(, or contains expect(, expect.assertions, t.is(, t.deepEqual(, t.throws(, t.true(, t.false(, fail(, expectTypeOf(, expectType<, assert., assertEquals(, assertStrictEquals(, assertThrows(, .assertEqual or assertType
Python starts with assert , or contains self.assert, self.fail, assertRaises, assertWarns, assertLogs, .assert_, pytest.raises, pytest.warns, pytest.deprecated_call, pytest.fail, warnings.catch_warnings or with raises(
Go contains t.Error, t.Fatal, t.Fail, assert. or require., or is a call to a helper whose name starts with assert, check, verify or expect (case-insensitive) and whose argument list starts with t, or t) or contains , t,

Some nodes count as assertions without a call:

  • Rust: a macro_rules! definition inside the test whose text contains assert or panic!.
  • TypeScript and JavaScript: a // @ts-expect-error comment, and a type alias whose text contains Expect<, AssertTrue< or AssertEqual<.

A test with zero assertions is not flagged if it calls a function that asserts. CodeKnife checks each call the test makes:

  • If the called function is itself a test with at least one assertion, the test passes.
  • If the called function is in the same file, CodeKnife searches its source text for assert!, assert , assert_eq!, assert_ne!, assert_matches!, debug_assert, expect(, assert., require., t.Fatal, t.Error, pytest.raises, pytest.warns or self.assert.
  • Helpers in other files are not inspected, so a test that only calls an asserting helper from another module is still reported as CK_TEST_ZERO_ASSERT.

An assertion is weak when its first line contains .is_ok(), .is_some(), .toBeDefined(), .toBeTruthy(), is not None, NotNil( or NoError(. CK_TEST_WEAK_ASSERT fires only when every assertion in the test is weak.

  • Mock setups are calls whose first line contains vi.mock(, jest.mock(, vi.spyOn(, jest.spyOn(, MagicMock(, @patch(, monkeypatch., mocker.patch or gomock..
  • Mock assertions are assertions containing toHaveBeenCalled or assert_called.
  • Implementation-coupled assertions contain toHaveBeenCalledTimes, assert_called_once, toThrow(" or .to_string(),.
  • Branches are syntax nodes of kind if_expression, if_statement, for_expression, for_statement, while_expression, while_statement or try_statement. In Go, an if with no else whose text contains t.Error, t.Fatal, t.Fail, b.Error, b.Fatal, assert. or require. is a guard, not a branch, so if err != nil { t.Fatal(err) } does not count.
  • Flake smells, checked in this order, one message per call:
Message Triggered by
wall-clock sleep inside unit test thread::sleep, setTimeout(, time.sleep(, time.Sleep(
uninjected wall-clock time dependency in test SystemTime::now, Date.now(, time.time(, time.Now(
unseeded randomness in test Math.random(, rand::random

All of these checks are substring matches on the first line of each call. They are not type-aware. Only the test body is inspected, so decorators are never seen: a Python test with three @patch(...) decorators and one assert_called_with produced no findings in a test run.

For every function or method that is not a test and is not in a test file, CodeKnife computes:

CRAP = CC² × (1 − coverage)³ + CC
  • CC is the function’s cyclomatic complexity, with a minimum of 1. See How Metrics Are Computed for how it is counted per language.
  • coverage is the fraction of the function’s covered lines, between 0 and 1. CodeKnife takes every line in the report between the function’s first and last line, and divides the number with a hit count above zero by the number of lines in the report for that range. Lines the report does not mention are ignored.

A fully covered function scores exactly its complexity. An uncovered function scores CC² + CC, so CC 5 gives 30.

When a report is loaded but has no entry for the function’s file, or no lines inside the function, the function’s coverage is taken as 0%. Code the coverage tool never saw is scored as completely untested.

When the score is above max_crap, CodeKnife reports CK_TEST_HIGH_CRAP. The severity is error when the score is 30 or more and warning otherwise. The impact score is the CRAP score, capped at 95. The fix hint suggests a complexity target of half the current complexity, but never less than 3.

Without a coverage report, CRAP is not computed. Instead every function with cyclomatic complexity of 10 or more gets an info finding, CK_TEST_UNCOVERED_COMPLEXITY. The run also prints a note. The note names a coverage command for each language present in the repository:

Language Suggested command
Rust cargo llvm-cov --lcov --output-path lcov.info
TypeScript, JavaScript npx vitest run --coverage
Python pytest --cov --cov-report=xml:coverage.xml
Go go test -coverprofile=coverage.out ./...

codeknife tests uses --coverage when you pass it. Otherwise it tries each path in [coverage] paths (relative to the repository root), then a fixed list of standard locations, and loads the first file that exists. Supported formats are LCOV, llvm-cov JSON, Go coverprofile, Istanbul JSON and Cobertura XML. The discovery order, format detection and path matching are on the Coverage Reports page.

Key Default Effect
[thresholds] max_crap 15.0 CRAP limit for CK_TEST_HIGH_CRAP. --strict or strictness = "strict" lowers it to 10.0 if it is higher. Raising it in a diff is reported by the Loosening Guard.
[coverage] paths [] Coverage files to try before the standard locations.
[blades] tests true When false, codeknife check drops this blade’s findings and notes. codeknife tests still runs and reports them. CRAP values are still computed and written to the metrics files.
strictness "default" "strict" has the same effect as --strict.

Mutation settings live under [mutate]. See Mutation Testing. The full config file is described in codeknife.toml.

With --changed, codeknife tests reports test-theater findings only for tests in changed files, and CRAP findings only for functions in changed files. The scope is the whole file, not the changed lines. CRAP is still computed for every function in the repository, because other features read it.

Terminal window
# the working tree changes one line inside grade()
codeknife tests --no-cache --changed --format agent
CODEKNIFE tests status=fail files=2 errors=1 warnings=4 infos=1 elapsed_ms=8
[1] ERROR CK_TEST_HIGH_CRAP src/lib.rs:1-23 sym=theater::grade impact=46 | `grade` CRAP score is 46.4 (CC=10, cov=29%, limit 15.0) | fix: Reduce complexity below 5 or add tests covering `grade` to bring CRAP below 15.0.
...
NOTE loaded coverage report (lcov, 1 files)

The Python test file was not changed, so its findings are gone. With a clean working tree, --changed reports nothing:

CODEKNIFE tests status=pass files=2 errors=0 warnings=0 infos=0 elapsed_ms=4
NOTE loaded coverage report (lcov, 1 files)

--since <ref> sets the base for the diff. Without --changed it has no effect here: codeknife tests --since HEAD~1 reports the same findings as a plain run.

Diff-CRAP is the highest CRAP score among functions that the diff actually touches. It is computed by codeknife check --changed (and plan with --changed), not by codeknife tests. A function counts when it is in a changed file and its line range overlaps an added or modified line range. If git reports no line ranges for a changed file, every function in that file counts. Functions without a CRAP score (no coverage report) are skipped.

Diff-CRAP appears in the PR risk brief. A value of 30 or more makes the brief’s risk high. In this run, only parse was edited. grade still has its finding because it is in the same file, but Diff-CRAP is parse’s score of 1.0:

Terminal window
codeknife check --no-cache --changed --format agent
CODEKNIFE check status=fail files=2 errors=1 warnings=4 infos=3 elapsed_ms=10
PR_BRIEF risk=high changed_files=1 dirs=1 max_diff_crap=1.0 new_suppressions=0 new_deps=0
...

The risk is high here because the run has an error finding. The other inputs to the brief are described on The Check Gate.

The per-function CRAP, complexity and coverage values are written to the metrics files in .codeknife/ (unless you pass --no-cache). Work Orders use them to rank findings, and the Garden Map reads them too. See The .codeknife Directory for the files.

Exit code When
0 No warnings or errors (info findings allowed).
1 At least one warning or error finding that the baseline does not suppress.
2 The command failed, for example --coverage points at a missing file: codeknife error: reading coverage report ../covdemo/missing.info: No such file or directory (os error 2). A coverage file that is not valid JSON but starts with { also fails here.
  • codeknife check runs this blade as part of the gate, with --coverage on check as the override. See The Check Gate.
  • The codeknife_check MCP tool runs the same static suite, including this blade. It has no coverage parameter. See MCP Tools.
  • There is no dedicated MCP tool for tests.