Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Testing

cargo test --workspace          # everything
cargo test -p kargo-core        # one crate
cargo test -p kargo-resolver nearest   # one test by name substring

CI runs the workspace suite on Linux, macOS, and Windows. A test that assumes a path separator or a home directory layout will fail on one of them.

Where tests go

One question decides it: does the test need to reach something that is not pub?

  • Yes — it goes inline, in an #[cfg(test)] mod tests at the bottom of the file that defines the item. A test for a private helper has nowhere else to live.
  • No — it goes in crates/<crate>/tests/, which cargo compiles as a separate crate that links yours the way a real consumer does.

That is the whole rule. Reach for "unit versus integration" and you will argue about the label; ask whether the test needs to see inside the module and you have an answer in five seconds.

LocationFor
crates/<crate>/src/** inlineTests that touch non-pub items
crates/<crate>/tests/Everything else: public API, fixture-driven cases, CLI behavior
tests/fixtures/Sample manifests and mock repository data, shared across crates
tests/projects/Whole sample projects, built and run by the end-to-end tier

Two things worth knowing about that table:

The repo root has no test tier. The root Cargo.toml is a virtual workspace — [workspace] with no [package] — so cargo compiles nothing from a root tests/*.rs. tests/fixtures/ and tests/projects/ are data directories read by crate tests, not test targets. A cross-crate test belongs in the tests/ directory of the crate that owns the entry point; CLI-level behavior goes in crates/kargo-cli/tests/, which drives the built binary through assert_cmd.

Visibility is a real constraint here, not a formality. A crate's top-level modules are mostly pub mod, but the submodules under them usually are not — ops_build/package.rs and plugins/ksp/standalone.rs sit behind a plain mod, so nothing in them is reachable from tests/ at any visibility, and kargo-cli is wholly unreachable because it is a binary. Check how a file's module chain is declared before concluding a test could move out of it.

scripts/check-inline-tests.sh enforces the rule, against scripts/inline-test-baseline — one line per file with an inline test mod, naming the non-pub item that keeps it there. Adding an inline test mod means adding a line; widening that item to pub fails the check until the file either names another private item or moves its tests to tests/. The conventions workflow runs it on every pull request, so the placement rule is checked rather than asserted.

Do not convert existing tests as a drive-by. A PR that moves tests and changes behavior is one nobody can review — move them in a PR that does nothing else.

Fixtures

tests/fixtures/
├── simple-jvm.toml
├── with-flavors.toml
├── with-catalog.toml
├── kmp-compose.toml
├── invalid-missing-name.toml
└── test.kargo.env

Each fixture is small and covers one scenario, with a name that says which. A fixture exercising five features at once tells you nothing when it fails.

What to cover

AreaCases
Manifest parsingValid and invalid Kargo.toml, every section
Interpolation${env:…} from .kargo.env and the environment, unresolved references
ResolutionTransitive graphs, conflicts, scope propagation, exclusions, BOM imports
Maven protocolPOM parsing, parent inheritance, metadata parsing, URL layout
Version parsingSemver edge cases, SNAPSHOT handling
CLICommand output, ideally as snapshots
LockfileRound-trip stability, byte-identical regeneration

A bug fix should come with a test that fails before it and passes after. That is the only way to know the fix addresses the reported problem rather than a neighbor.

Naming

No test_ prefix. Name the behavior and the condition it holds under:

#[test]
fn parse_manifest_with_flavors() { … }

#[test]
fn resolve_conflict_nearest_wins() { … }

#[test]
fn manifest_rejects_invalid_semver() { … }

A test name should tell you what broke without opening the file, and test_ is five characters that never do. The #[test] attribute directly above says it is a test; inside #[cfg(test)] mod tests the module path says it twice; and in crates/<crate>/tests/ cargo prints the target name as a header above that file's results. Prefixing only buries the part of the name that varies.

The rule is deliberately the same in both locations. Naming that depended on where a test lived would turn every move between the two into a rename, and tests move — the placement rule above sends them one way the first time something stops being pub.

rustc and cargo drop the prefix in their own suites, so this also keeps the tree reading like idiomatic Rust rather than like a port from another language.

Assertions

Always with a message:

assert_eq!(
    resolved.version, "1.9.21",
    "nearest-wins should pick the depth-1 version"
);

assert!(
    result.is_err(),
    "a manifest without package.name must be rejected"
);

For error cases, assert on the message too — an error that fires for the wrong reason still passes is_err():

let err = Manifest::parse_toml(input).unwrap_err();
assert!(
    err.to_string().contains("package.name"),
    "error should name the offending key, got: {err}"
);

.unwrap() in test code is fine. The no-panic rule is about library code.

Network

Resolution and download tests must not hit the network. Use fixtures and a mock repository layout under tests/fixtures/. A test suite that needs Maven Central fails on an airplane and flakes in CI.

kargo audit is the exception: it queries OSV live, so its tests cover request construction and response parsing rather than end-to-end behavior.

End-to-end runs

The end-to-end tier is the exception to the network rule, and the only one: kargo build on a real project is what users actually do, and it cannot be mocked into a meaningful test. Whether a processor's output lands where the compiler can use it, whether the jar carries an entry point, whether resolution reproduces its own lockfile — each of those is a fact about a real toolchain running over real sources.

It lives in crates/kargo-cli/tests/, driving the built binary through assert_cmd like every other CLI test. There is no separate workspace member for it and no root-level tier: the root Cargo.toml is a virtual workspace, so a root tests/*.rs compiles into nothing. The targets share one harness in crates/kargo-cli/tests/support/:

TargetCoversSamples
e2e_sample_projectsArtifacts, the build cache, --release, clean, run, test, lockfile regenerationjvm-sample, ksp-sample, plus every sample's lockfile
e2e_annotation_processingKAPT and KSP: generated sources, stubs, processor options, processor errors, stale outputkapt-sample, mixed-ap-sample
e2e_reporting_commandscheck, tree and its modes, fetch --verify, and the informational commandsjvm-sample
e2e_androidThe Android SDK on the classpath, .aar dependencies, compile-sdk in the fingerprintkargo new --template android
e2e_templatesThe service templates: resolution, compile, their own tests, and the service starting on the port it is givenkargo new --template ktor, --template spring

Each needs Maven Central, a Kotlin toolchain, and a JDK, so each is opt-in and cargo test skips them with a note:

KARGO_E2E=1 cargo test -p kargo-cli --test e2e_sample_projects
KARGO_E2E=1 cargo test -p kargo-cli --test e2e_annotation_processing
KARGO_E2E=1 cargo test -p kargo-cli --test e2e_reporting_commands
KARGO_E2E=1 cargo test -p kargo-cli --test e2e_android
KARGO_E2E=1 cargo test -p kargo-cli --test e2e_templates

e2e_android also needs an installed Android platform, two for the compile-sdk test, and skips without one.

Each test copies its sample into a temporary directory — including the sample's .kargo/ dependency cache, so a developer who has run the samples once pays no download, and the sample itself is never modified. Run the annotation-processing target after any change to crates/kargo-compiler/src/plugins/ or to the annotation-processing phase of kargo-ops, and the sample-projects target after any change to the build pipeline, the build cache, or resolution output.

In CI

The End-to-end job in .github/workflows/ci.yml runs every target on every pull request and every push to main. It is deliberately one ubuntu leg, not the three-OS matrix the rest of the suite uses: it downloads a compiler, spawns JVMs, and talks to Maven Central, so the matrix would triple the slowest and most environment-dependent part of CI for little extra signal.

Three things make that leg predictable, and each is load-bearing:

  • actions/setup-java pins a JDK 21. The samples declare java-target = "21" and JDK discovery reads JAVA_HOME first, so without the pin the leg inherits whatever the runner image ships.
  • A kargo fetch warm-up populates each sample's .kargo/, and actions/cache keeps that plus ~/.kargo across runs, keyed on the sample manifests and lockfiles. The tests read those caches through the copy they make, so a warm run downloads nothing.
  • Tests run with --test-threads=1. Each one spawns a Kotlin compile, and several JVMs at once on a four-core runner buy wall-clock with memory pressure.

A sample project is a test input, so changing one changes what CI asserts. If a change to tests/projects/ is intended, commit the regenerated Kargo.lock with it — every_sample_regenerates_its_committed_lockfile fails otherwise, by design.

Platform-specific code

#[cfg(unix)]
#[test]
fn executable_bit_is_set() { … }

#[cfg(windows)]
#[test]
fn path_normalization_on_windows() { … }

Prefer writing the test for every platform and normalizing paths in the code under test. A #[cfg(unix)] test is one CI matrix leg's worth of coverage.

Coverage

Coverage gates at 85% line coverage across the workspace, with Codecov's patch status held at 90% for the lines a change touches. Reproduce the project measurement locally with the same two steps the Coverage job uses:

cargo llvm-cov --workspace \
  --ignore-filename-regex '(^|/)tests/' \
  --lcov --output-path lcov.raw.info

scripts/filter-inline-test-coverage.sh \
  --input lcov.raw.info --summary --fail-under-lines 85

The Coverage job is a required status check, so falling below 85% blocks the merge. Test targets under tests/ are excluded — they are test code, not code under test — and the exclusion is duplicated in codecov.yml, so change both together.

The two thresholds differ on purpose. 85% is roughly where the workspace sits, so the project gate holds the line rather than chasing it; 90% on the patch ratchets new code up without blocking a change on a gap it did not create. kargo-ops is still the largest gap; the Codecov dashboard has the current per-crate figures, and a pull request that adds tests to a thin module is always welcome.

About a third of what is left is not reachable from an ordinary test: vendor downloads, the watch loop, interactive prompts, code that replaces the running binary, and the two annotation-processing passes that would need their own sample projects. Covering every line a test can reach would land around 94%, which is the practical ceiling rather than 100%.

Codecov reports the same threshold on each pull request: one comment, updated in place on every push, plus inline annotations on uncovered lines in Files Changed. The patch status covers the lines the change touched, which is the number worth reading on a review — a change that adds uncovered lines is the case the gate exists to catch.

Treat the percentage as a floor, not a goal. Hitting a number by testing what is easy to test is how a suite becomes expensive to maintain and bad at finding bugs; a module with no coverage at all is still the strongest signal on the report.

Next