Skip to content

Latest commit

 

History

History
675 lines (499 loc) · 41.3 KB

SLEUTH.adoc

File metadata and controls

675 lines (499 loc) · 41.3 KB

Sleuth: A Dependency-Aware Test Framework for the JVM

Sleuth is a lightweight Java test framework — and a Maven Surefire provider — built around first-class dependencies between test suites and between tests. It is designed for test suites whose correctness is genuinely ordered (integration tests, end-to-end flows, staged pipelines) while still permitting aggressive parallelism wherever the graph allows it. Sleuth understands its own annotations natively and can transparently execute unmodified TestNG test classes.

1. Why Sleuth Exists

Most JVM test frameworks are built on an assumption that tests are independent. JUnit deliberately randomizes order to keep authors honest; JUnit 5’s parallel executor has no notion of "this test must not start until that other test succeeded." TestNG does express dependsOnMethods and dependsOnGroups, but its configuration surface — XML suite files, two separate thread-pool dimensions, per-group filtering — grew organically over many years.

Sleuth is an opinionated take on the same idea, with the following non-negotiables:

  • Dependencies are first-class at both tiers. A suite can depend on another suite; a test can depend on another test. When a prerequisite fails, its downstream nodes are skipped and the original failure (the "culprit") is propagated with them.

  • Configuration lives in code. There is no testng.xml analogue. Group membership, priority, ordering, and hard-versus-soft constraints are all expressed as annotation attributes on Java classes and methods.

  • Parallelism is bounded by a single threadCount. One pool, one knob. Fair semaphores gate two tiers (suite and test), so the framework will use every thread it can justify given the dependency graph — and never more.

  • Migration is cheap. Existing TestNG test classes run under Sleuth without modification through a pluggable annotation translator layer.

  • Maven integration is a single JAR. Dropping surefire-sleuth-provider into the Surefire plugin’s <dependencies> block is all that is needed; no Mojos, no separate plugin, no extra phases.

The package name and its contents reflect that focus: a test runner that investigates the graph of relationships between tests, arranges them correctly, and reports who caused what.

2. Module Layout

The sleuth package is a Maven POM aggregator with two published artifacts:

Artifact Module Module name Purpose

sleuth-runner

runner/

org.smallmind.sleuth.runner

The framework proper: annotations, dependency resolution, thread pool, event system. No Maven dependencies; usable programmatically from any JVM host.

surefire-sleuth-provider

maven/surefire/

org.smallmind.sleuth.maven.surefire

A Surefire provider that adapts sleuth-runner to the standard Maven mvn test lifecycle, translating Sleuth events into Surefire RunListener calls.

The sleuth-runner module name is the one to use in requires. Surefire loads surefire-sleuth-provider through its own class realms, so org.smallmind.sleuth.maven.surefire only identifies the jar; it is not intended for a consumer’s requires.

sleuth-runner ships an explicit module descriptor. It exports its three packages, re-exports org.smallmind.nutsnbolts (requires transitive), and requires TestNG as the automatic module org.testng, which it does not re-export. Tests normally run on the classpath, where the descriptor is ignored. If you drive sleuth-runner on a module path, open each test package to it, because it constructs test classes and invokes their annotated methods reflectively:

opens com.example.app.tests to org.smallmind.sleuth.runner;

See Module Path And Classpath for the repository-wide rules.

Depend on sleuth-runner if you are embedding Sleuth in another tool, driving it from a main method, or writing your own reporter. Depend on surefire-sleuth-provider (and only that) when you want mvn test to execute Sleuth-annotated classes.

3. Quick Start

3.1. Maven Surefire (the common case)

Add the provider to the Surefire plugin’s <dependencies> block. Surefire will discover it through META-INF/services and delegate all test execution to Sleuth.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <dependencies>
    <dependency>
      <groupId>org.smallmind</groupId>
      <artifactId>surefire-sleuth-provider</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>
  <configuration>
    <properties>
      <property>
        <name>groups</name>
        <value>smoke,regression</value>
      </property>
      <property>
        <name>threadCount</name>
        <value>4</value>
      </property>
    </properties>
  </configuration>
</plugin>

Write a suite:

package com.example;

import org.smallmind.sleuth.runner.annotation.AfterSuite;
import org.smallmind.sleuth.runner.annotation.BeforeSuite;
import org.smallmind.sleuth.runner.annotation.BeforeTest;
import org.smallmind.sleuth.runner.annotation.Suite;
import org.smallmind.sleuth.runner.annotation.Test;
import org.smallmind.sleuth.runner.TestContext;

@Suite(groups = {"smoke"})
public class AccountServiceTest {

  @BeforeSuite
  public void openDb () {
    TestContext.put("db", Database.connect());
  }

  @AfterSuite
  public void closeDb () {
    TestContext.get("db", Database.class).close();
  }

  @BeforeTest
  public void beginTx () {
    TestContext.put("tx", TestContext.get("db", Database.class).begin());
  }

  @Test(priority = 0)
  public void createAccount () {
    Account a = TestContext.get("tx", Transaction.class).create("alice");
    assert a.id() != null;
  }

  @Test(priority = 1, dependsOn = "createAccount")
  public void readAccount () {
    // only runs if createAccount passed
  }
}

Run it:

mvn test
mvn -Dgroups=smoke test
mvn -Dgroups=all test

The -Dgroups=all sentinel disables group filtering entirely and runs every annotated suite.

3.2. Programmatic embedding

If you are not using Maven, instantiate SleuthRunner directly:

SleuthRunner runner = new SleuthRunner();
runner.addListener(event -> System.out.println(event));
runner.execute(
    new String[] {"smoke"},   // groups
    4,                        // threadCount
    true,                     // stopOnError
    true,                     // stopOnFailure
    AccountServiceTest.class,
    OrderServiceTest.class);

4. Annotations

Sleuth’s own annotations live in org.smallmind.sleuth.runner.annotation. All are retained at runtime.

4.1. @Suite (class-level)

Attribute Type Default Purpose

groups

String[]

(required)

Group names this suite belongs to. Group filter selects suites by intersection. An empty array means the suite belongs to no named group and is excluded when any filter is active.

priority

int

0

Cross-suite ordering tier. Lower tiers are fully drained before higher tiers begin.

executeAfter

String[]

{}

Fully-qualified class names of suites that must complete (any outcome) before this one starts. Soft ordering; no culprit propagation.

dependsOn

String[]

{}

Fully-qualified class names of suites that must succeed before this one starts. Hard dependency; culprit is inherited and the suite is skipped if any prerequisite failed.

enabled

boolean

true

When false, the suite is unconditionally excluded.

Note
Groups are declared on the suite, not on individual tests. This is deliberate: the unit of opt-in is the class.

4.2. @Test (method-level)

Attribute Type Default Purpose

priority

int

0

Intra-suite ordering tier. Lower tiers run first.

executeAfter

String[]

{}

Method names in the same suite that must complete before this test starts. Soft ordering.

dependsOn

String[]

{}

Method names in the same suite that must succeed before this test starts. Hard dependency.

expectedExceptions

Class<?>[]

{}

Exception types the test method is expected to throw. If the method throws one of the listed types, the test is reported as SUCCESS. If the list is non-empty and the method throws nothing, or throws a type not on the list, the outcome is determined by enforcement rules (see below).

enabled

boolean

true

When false, the test is unconditionally excluded.

A @Test method must take no arguments. Return values are ignored.

When expectedExceptions is empty (the default), an AssertionError escaping the method produces a FAILURE event; any other exception produces an ERROR event. The two are reported distinctly because one represents a broken expectation and the other represents broken code (or broken environment) — they deserve different triage.

When expectedExceptions is non-empty, entries that are not subtypes of Exception are silently ignored. For entries that are subtypes of Exception: if the thrown exception is an instance of a listed type, the test is reported as SUCCESS. If at least one Exception-subtype entry was present but none matched, the test is reported as FAILURE. If the list contains no Exception-subtype entries at all (e.g., only Error types), it is treated as absent and normal exception handling applies.

4.3. Lifecycle annotations

Four lifecycle annotations. @AfterSuite and @AfterTest carry a single alwaysRun attribute (default false); the two before-annotations have none. Multiple methods in a class (including inherited ones) may carry any of them; they run in class-hierarchy order, superclass methods first.

Annotation When it fires If it throws

@BeforeSuite

Once, before the first @Test in the suite.

A culprit is recorded; every subsequent @Test is skipped, as is every @AfterSuite method not marked alwaysRun = true.

@AfterSuite

Once, after the last @Test in the suite. Test failures do not suppress it. Skipped when @BeforeSuite failed unless alwaysRun = true; always skipped when the suite inherited a culprit from a failed dependsOn prerequisite.

Produces an ERROR event and becomes the suite culprit only if none existed; does not cascade.

@BeforeTest

Once per @Test method, immediately before it.

A culprit is recorded for the upcoming test, causing it to be skipped.

@AfterTest

Once per @Test method whose body ran, whether it passed or failed. Skipped when @BeforeTest failed or the test was skipped, unless alwaysRun = true.

Produces an ERROR event; becomes the culprit only if the test itself did not already fail.

4.4. What about testng.xml?

There isn’t one, by design. Anything you would put in a TestNG XML file — group composition, suite inclusion, ordering — is expressed on the classes themselves, and the filter surface is just the groups parameter. See TestNG Interoperability for running TestNG test classes unmodified.

5. The Dependency Model

5.1. Two kinds of ordering constraints

Sleuth separates two concerns that TestNG conflates:

Constraint Semantics

executeAfter

"Don’t start me until the named node has finished." Outcome of the named node is irrelevant; this node still runs no matter what.

dependsOn

"Don’t start me unless the named node succeeded." If any named prerequisite failed, this node is skipped and inherits the prerequisite’s culprit.

The distinction matters. Consider an integration test where reconcile() must run after insert() (because it reads the same rows) but should still run even if insert() produced a failure (because reconciliation is the thing you want to know about). That is executeAfter, not dependsOn. Conversely, readAccount has no reason to run if createAccount never produced an account — that is dependsOn.

5.2. Priority

Priority is a scheduling tier, not a sort key. All nodes sharing priority p may run concurrently; no node with priority p+1 may start until every node with priority p has completed. Priorities compose cleanly with explicit dependsOn / executeAfter — a priority-1 node implicitly executes after every priority-0 node, whether or not it names any of them.

5.3. Culprit propagation

When a test or suite fails, a Culprit is created. It walks the throwable chain looking for the first stack frame whose class name matches the node that threw (the test class or suite class), and records that frame plus the underlying throwable. The culprit rides along with the dependency node, and when the DependencyQueue later unblocks a dependent node, it copies the culprit over before dispatching. The skipped node emits a SkippedSleuthEvent whose message names the original culprit — so "test X was skipped because test Y failed at line 42 with AssertionError" is visible all the way down the chain.

5.4. Group filtering

At the start of every run the SleuthRunner partitions suites by group membership. A suite is included iff its groups array intersects the requested filter. Special cases:

  • groups == null (no filter was supplied): all suites run.

  • groups == new String[0] (empty filter): all suites run. The Surefire provider uses this to represent -Dgroups=all.

  • Non-empty filter: at least one suite group must match at least one filter entry.

Filtered-out suites never enter the dependency graph, which means a suite filtered out by group cannot cause dependents to be skipped through dependsOn. If you have "don’t run me unless X ran too" semantics, you need to include X’s group in the filter; you can’t rely on skip-propagation to do it for you.

5.5. Cycle and missing-dependency detection

DependencyAnalysis.calculate() performs an iterative DFS topological sort with two invariants: every node is reachable, and the graph is acyclic. A cycle (A depends on B depends on A) throws TestDependencyException before any test executes. A dangling reference (A depends on B but B was never discovered, either because it has no @Test or because its class was filtered out) likewise throws TestDependencyException. Both failures prevent the run from starting rather than being discovered half-way through.

6. Lifecycle, Step by Step

A complete run looks like this:

  1. SleuthRunner.execute(…​) creates a SleuthThreadPool(threadCount) and an AnnotationProcessor with the native translator followed by the TestNG translator.

  2. For each candidate class, the processor returns an AnnotationDictionary (or null if the class is not a recognized suite). Enabled, in-group suites become Dependency nodes in a DependencyAnalysis<Suite, Class<?>>.

  3. calculate() produces a topologically sorted DependencyQueue<Suite, Class<?>>.

  4. A CountDownLatch is initialized to the queue size. The main thread drains the queue in a loop: each ready suite is dispatched to the pool as a SuiteRunner, blocking on the SUITE-tier semaphore when all threads are busy.

  5. Each SuiteRunner:

    1. Reflectively instantiates the test class (requires a public no-arg constructor, otherwise TestProcessingException).

    2. Invokes @BeforeSuite methods via AnnotationMethodology.invoke(…​). A throwing setup records a culprit.

    3. Builds a per-suite DependencyAnalysis<Test, Method> from the suite’s @Test methods.

    4. Drains the per-suite DependencyQueue, dispatching each ready test as a TestRunner on the TEST-tier semaphore.

    5. Awaits a per-suite CountDownLatch.

    6. Invokes @AfterSuite methods. Test failures do not suppress them; a @BeforeSuite failure skips those not marked alwaysRun, and a culprit inherited from a dependsOn prerequisite skips all of them.

    7. Stores the final culprit on its dependency node and calls complete(), which releases its semaphore permit, marks the suite done in the queue (waking threads blocked in poll()), and decrements the global suite latch.

  6. Each TestRunner:

    1. Invokes @BeforeTest methods. Any failure becomes the initial culprit for the test body.

    2. Fires StartSleuthEvent. If a culprit exists (from setup or from a failed dependsOn prerequisite), fires SkippedSleuthEvent and proceeds to teardown.

    3. Otherwise invokes the @Test method. If it returns normally and the expectedExceptions list contains at least one Exception subtype, a FailureSleuthEvent is fired for the missing throw; otherwise SuccessSleuthEvent. If it throws, the exception is checked against expectedExceptions: a matching Exception-subtype entry → SuccessSleuthEvent; a non-matching Exception-subtype entry or an AssertionError → FailureSleuthEvent; any other exception → ErrorSleuthEvent.

    4. Invokes @AfterTest methods if the test body ran, whether it passed or failed; if the body was skipped, only hooks marked alwaysRun are invoked. A hook failure becomes the culprit only when the test did not already fail.

    5. Calls complete().

  7. When the global latch reaches zero, execute() returns. If the run was cancelled mid-flight a CancelledSleuthEvent is fired in lieu of awaiting the latch.

6.1. Setup-failure cascading, concretely

If @BeforeSuite throws, every @Test in that suite emits a SkippedSleuthEvent, as does every @AfterSuite not marked alwaysRun = true (after firing their own StartSleuthEvent); alwaysRun after-suite hooks still run so they can release whatever setup acquired before it failed, and an exception they throw is reported as an ERROR without replacing the original culprit. If @BeforeTest throws, only the corresponding @Test and its non-alwaysRun @AfterTest hooks are skipped — the rest of the suite is untouched. This is the intended symmetry: a suite-level fixture is a suite-level responsibility, a test-level fixture is a test-level one.

A culprit inherited from a failed dependsOn suite is different: nothing in the dependent suite was ever set up, so every @BeforeSuite, @Test, and @AfterSuite there is skipped, alwaysRun included.

7. The Event Model

Sleuth is built around a typed event hierarchy and a single listener interface:

package org.smallmind.sleuth.runner.event;

public interface SleuthEventListener extends java.util.EventListener {
  void handle (SleuthEvent event);
}

Events are dispatched synchronously on the thread that fires them. Listeners must be thread-safe.

7.1. Event hierarchy

SleuthEvent                          (className, methodName; abstract)
├── CancelledSleuthEvent             (CANCELLED)
└── TimedSleuthEvent                 (+ elapsed: long; abstract)
    ├── SuccessSleuthEvent           (SUCCESS)
    ├── ThrowableSleuthEvent         (+ throwable: Throwable; abstract)
    │   ├── FailureSleuthEvent       (FAILURE — AssertionError)
    │   ├── ErrorSleuthEvent         (ERROR — any other exception)
    │   └── FatalSleuthEvent         (FATAL — runner-level abort)
    └── MessageSleuthEvent           (+ message: String; abstract)
        └── SkippedSleuthEvent       (SKIPPED — culprit-driven)

Additionally StartSleuthEvent (type START) extends SleuthEvent directly because nothing has been timed yet when it fires.

7.2. Discriminator enum

Each concrete event exposes getType() returning a SleuthEventType. Listeners that want to switch over type instead of instanceof should do so on this enum. The Surefire integration takes this approach; UnknownSwitchCaseException is thrown if a new enum constant is ever added without updating the switch, which means the compiler, not runtime, catches the drift.

7.3. Writing a custom listener

SleuthRunner runner = new SleuthRunner();

runner.addListener(event -> {
  switch (event.getType()) {
    case START:    System.out.println(">> " + event.getClassName() + "." + event.getMethodName()); break;
    case SUCCESS:  System.out.println("ok"); break;
    case FAILURE:
    case ERROR: {
      ThrowableSleuthEvent t = (ThrowableSleuthEvent) event;
      t.getThrowable().printStackTrace();
      break;
    }
    case SKIPPED:  System.out.println("skipped: " + ((SkippedSleuthEvent) event).getMessage()); break;
    default: break;
  }
});

Every SleuthEvent also overrides toString() to produce an ANSI-colored one-line summary via AnsiColor, which is why System.out.println(event) works out of the box from the quick-start example.

8. Sharing State: TestContext

Because all @Test methods in a suite are invoked on the same instance of the test class, and because several of those methods may run concurrently, mutable instance fields are a hazard. Sleuth provides TestContext as the canonical alternative:

public final class TestContext {
  public static <T> T     get (String key, Class<T> type);
  public static Object    get (String key);
  public static void      put (String key, Object value);
  public static Object    putIfAbsent (String key, Object value);
}

The backing store is an InheritableThreadLocal<HashMap<String, Object>>. This has two consequences:

  1. Values set on the suite thread (by @BeforeSuite) are automatically visible to the child threads spawned for individual tests, because InheritableThreadLocal copies to child threads at creation.

  2. Values set inside a @Test or @BeforeTest are scoped to that test’s thread only, and will not bleed into sibling tests running on other threads.

The typical pattern is: expensive, read-only resources (database connections, HTTP clients, parsed configuration) are put into the context in @BeforeSuite; per-test state (a fresh transaction, a fresh captured event buffer) is put in @BeforeTest.

9. Concurrency Model

A single SleuthThreadPool is shared across the entire run. It holds two fair Semaphore instances — one per TestTier — each seeded with threadCount permits.

Tier Governs

SUITE

Number of simultaneously executing SuiteRunner instances — i.e. how many suites are open at once.

TEST

Number of simultaneously executing TestRunner instances, globally across all open suites.

The second point matters: the TEST semaphore is not per-suite. If threadCount = 4 and two suites are open, up to 4 @Test methods can run in parallel between them, not 4 per suite. This is the intentional policy — threadCount is a budget for the machine as a whole, not per suite.

SleuthThreadPool does not reuse threads. Every TestController runs on a freshly spawned Thread. This is cheap enough in practice and avoids subtle interactions with thread-locals in user code. When a controller finishes it calls complete(), which releases its permit so a blocked dispatcher can proceed.

9.1. Cancellation

SleuthRunner.cancel() flips an AtomicBoolean. Already-running controllers finish their current lifecycle method; the dispatcher stops handing out new work and calls complete() directly on any controller it would have launched, which keeps the latches monotonic. A CancelledSleuthEvent is fired once the dispatcher loop observes the flag.

Cancellation is also triggered automatically by stopOnError=true (any ERROR event) and stopOnFailure=true (any FAILURE event). The Surefire provider sets both to true by default; setting testFailureIgnore=true in the plugin configuration flips both to false, producing "run everything, report everything" semantics.

10. TestNG Interoperability

Sleuth bundles a second AnnotationTranslator that recognizes TestNG’s annotation set and produces equivalent Sleuth dictionaries. Classes annotated with TestNG run unmodified as Sleuth suites, subject to the following mapping:

TestNG Sleuth Notes

Class-level @Test

@Suite (via SuiteLiteral)

Maps groups, priority, dependsOnMethods. No executeAfter equivalent.

@BeforeClass

@BeforeSuite

@AfterClass

@AfterSuite

Maps alwaysRun.

@BeforeMethod

@BeforeTest

@AfterMethod

@AfterTest

Maps alwaysRun.

Method-level @Test

@Test

Maps priority, dependsOnMethods, enabled, expectedExceptions.

The native translator runs first, so if a class carries both dialects (unusual, but legal) the Sleuth annotations win. TestNG’s @BeforeTest and @AfterTest (which operate on TestNG’s XML <test> tag, not on individual methods) are intentionally not mapped — there is no equivalent concept in Sleuth.

This translator layer is pluggable. To add, for example, a JUnit 4 translator, implement AnnotationTranslator and register it with the AnnotationProcessor. The existing SleuthRunner hard-codes new AnnotationProcessor(new NativeAnnotationTranslator(), new TestNGAnnotationTranslator()); embedders who need a different chain can build their own execution path reusing the rest of the framework.

11. The Maven Surefire Provider

The surefire-sleuth-provider JAR contains a single SurefireProvider service implementation plus supporting classes that plug Sleuth into the Maven Surefire reporting pipeline.

11.1. Discovery

Surefire uses the standard Java service loader. The JAR ships with:

META-INF/services/org.apache.maven.surefire.api.provider.SurefireProvider

containing one line:

org.smallmind.sleuth.maven.surefire.SleuthProvider

When Surefire starts, it discovers this provider and delegates discovery and execution to it. No <configuration> switch is needed to select it — Surefire picks whichever provider is on its plugin classpath.

11.2. Configuration properties

All configuration is read from either JVM system properties or the provider’s <properties> block:

Property Source Default Effect

groups

-Dgroups=… or provider property

(none)

Comma-separated group names to include. The sentinel value all anywhere in the list disables group filtering entirely. System property wins if both are set.

threadCount / threadcount

provider property

0 → unbounded (Integer.MAX_VALUE)

Semaphore permits per tier.

testFailureIgnore

provider property

false

When true, sets both stopOnError and stopOnFailure to false, so the run continues through failures and errors.

11.3. What it does at runtime

  1. getSuites() calls providerParameters.getScanResult().applyFilter(null, …​) — i.e. delegates classpath scanning to Surefire’s normal mechanism. Sleuth does not scan the classpath itself.

  2. invoke(Object forkTestSet):

    1. Replaces System.out and System.err with ForwardingPrintStream instances so that stdout/stderr produced by a test is correlated with that test’s TestIdentifier and written as a TestOutputReportEntry on the Surefire listener — meaning the Surefire XML report attributes console output to the right test even under parallel execution.

    2. Reads groups, threadCount, and testFailureIgnore.

    3. Registers a SurefireSleuthEventListener that maps Sleuth events onto Surefire RunListener callbacks.

    4. Calls testSetStarting on the reporter, runs sleuthRunner.execute(…​), then calls testSetCompleted.

    5. If a FatalSleuthEvent was captured, throws TestSetFailedException so Maven marks the build failed.

    6. Closes the ReporterFactory and returns the aggregated RunResult.

11.4. Event-to-Surefire mapping

Sleuth event type Surefire callback Carries

START

testStarting

—

SUCCESS

testSucceeded

elapsed ms

FAILURE

testFailed

SleuthStackTraceWriter, elapsed ms

ERROR

testError

SleuthStackTraceWriter, elapsed ms

SKIPPED

testSkipped

skip message (names the culprit)

CANCELLED

testSetCompleted

—

FATAL

testExecutionSkippedByUser; throwable is captured for later rethrow

—

SleuthStackTraceWriter is the bridge between a Sleuth Culprit and Surefire’s StackTraceWriter contract. Its smartTrimmedStackTrace() delegates to Culprit.toString(), producing short lines like:

com.example.AccountServiceTest.createAccount:42 AssertionError expected: <true> but was: <false>

12. Architecture Reference

This section describes the internals, for readers who want to extend or embed Sleuth.

12.1. SleuthRunner

org.smallmind.sleuth.runner.SleuthRunner is the only public entry point. It owns:

  • A LinkedList<SleuthEventListener> — registered listeners, fired synchronously in registration order.

  • An AtomicBoolean cancelled — flipped by cancel().

Its two execute overloads differ only in whether they accept varargs or an Iterable. Both go through the same pipeline described under [_lifecycle_step_by_step].

12.2. AnnotationProcessor and the translator chain

AnnotationProcessor holds an ordered array of AnnotationTranslator implementations and a HashMap<Class<?>, AnnotationDictionary> cache. process(Class<?>) is synchronized because the cache is shared across every SuiteRunner. For each class it walks translators in order and returns the first dictionary whose isImplemented() method returns true (i.e. it actually found Sleuth-or-equivalent annotations). A class that matches no translator is silently skipped.

12.3. AnnotationDictionary and AnnotationMethodology

An AnnotationDictionary holds the Suite (class-level) plus up to five AnnotationMethodology<A> instances — one per lifecycle annotation kind, plus one for @Test. An AnnotationMethodology is an ordered, deduplicated collection of (Method, A) pairs. Deduplication is by MethodKey (method name + parameter types), so when MethodCensus walks the class hierarchy superclass-first, an overriding subclass method naturally replaces the superclass entry.

AnnotationMethodology.invoke(SleuthRunner, Culprit, Class<?>, Object) is the single entry point that fires a batch of lifecycle methods. It emits a StartSleuthEvent before each method, a SuccessSleuthEvent or ErrorSleuthEvent after, and SkippedSleuthEvent for every method encountered once a culprit exists. The five-argument overload takes a Predicate<A> naming the annotations whose methods run anyway (the runners pass AfterSuite::alwaysRun and AfterTest::alwaysRun); a method that throws while a culprit already exists is reported as an ERROR but does not replace that culprit. The method returns the (possibly updated) culprit so the caller can chain calls.

12.4. Dependency, DependencyAnalysis, DependencyQueue

The dependency engine is fully generic: Dependency<A, T> parameterizes over the annotation type (Suite or Test) and the payload type (Class<?> or Method). The engine has no knowledge of Sleuth-specific semantics; it operates only on name, priority, executeAfter, dependsOn, expectedExceptions, and children.

DependencyAnalysis.calculate() does two things:

  1. Priority wiring. If there are multiple distinct priority values, every node in each lower tier becomes a parent of every node in the next tier, and the array of lower-tier names is stored on the higher-tier node as priorityOn. This is how "all priority-0 before any priority-1" is enforced without the user typing executeAfter everywhere.

  2. Topological sort. Iterative DFS with cycle detection. The result is a LinkedList<Dependency> in execution order.

DependencyQueue.poll() is a synchronized, blocking dequeue. It scans the list for any node whose dependsOn, executeAfter, and priorityOn arrays are entirely contained in the completedSet. For dependsOn specifically, if the prerequisite was completed but failed, the prerequisite’s culprit is copied into the candidate before it is returned. If no node is ready and the list is non-empty, the calling thread wait()`s. `complete(Dependency) adds the node to the completedSet and `notifyAll()`s.

12.5. SleuthThreadPool and TestTier

SleuthThreadPool holds two java.util.concurrent.Semaphore instances, one per TestTier (SUITE, TEST), each initialized with threadCount fair permits. execute(TestTier, TestController):

  1. Blocks on acquire() of the tier’s semaphore.

  2. If the runner is no longer running (cancel() was called), calls controller.complete() directly — which releases the permit and decrements the owning latch — without starting a thread.

  3. Otherwise spawns a new Thread(controller) and starts it.

There is no thread reuse. If this matters for an embedder, implementing a custom TestController host is straightforward: the interface is just Runnable plus complete().

12.6. Culprit

Culprit records the origin of a failure by walking the throwable chain (via getCause()) and searching each throwable’s stack trace for the first frame whose class name matches the node that threw. The pair (matching throwable, matching frame) is what survives, so that a wrapped-and-rethrown failure still reports the original line in the original test class. Culprit.toString() is the compact one-liner seen in skip messages and Surefire trimmed stack traces.

12.7. TestIdentifier

Every time a SuiteRunner or TestRunner is about to dispatch a method, TestIdentifier.updateIdentifier(className, methodName) is called on the spawning thread. TestIdentifier maintains a static HashMap<TestKey, Long> — keyed on a (className, methodName) composite in which methodName is null for suite-level entries — assigning a stable long to each pair it ever sees, plus an AtomicLong counter and an InheritableThreadLocal<Long> holding the current thread’s id (default 1, inherited by child test threads). Allocation uses double-checked locking on the map. The Surefire provider reads this id when constructing every SimpleReportEntry and TestOutputReportEntry, ensuring that each Surefire event is attributable to the exact test that produced it — even stdout/stderr lines written from deep inside a service under test.

13. Worked Examples

13.1. Integration test with a seeded fixture

@Suite(groups = {"integration"})
public class OrderLifecycleTest {

  @BeforeSuite public void openDb () { TestContext.put("db", Database.connect()); }
  @AfterSuite  public void closeDb () { TestContext.get("db", Database.class).close(); }

  @Test(priority = 0)
  public void placeOrder () {
    Order o = TestContext.get("db", Database.class).orders().place("SKU-1", 3);
    TestContext.put("orderId", o.id());
    assert o.status() == PENDING;
  }

  @Test(priority = 1, dependsOn = "placeOrder")
  public void shipOrder () {
    String id = TestContext.get("orderId", String.class);
    TestContext.get("db", Database.class).orders().ship(id);
  }

  @Test(priority = 2, dependsOn = "shipOrder")
  public void deliverOrder () { ... }

  @Test(priority = 2, executeAfter = "shipOrder")
  public void auditTrailRecordedShipment () {
    // runs concurrently with deliverOrder, but not before shipOrder is done;
    // still runs even if shipOrder failed — that's the point of executeAfter
  }
}

A failure in placeOrder cascades: shipOrder, deliverOrder, and auditTrailRecordedShipment are all skipped with placeOrder’s culprit. A failure in `shipOrder skips deliverOrder (hard dep) but lets auditTrailRecordedShipment run anyway.

13.2. Cross-suite dependency

@Suite(groups = {"e2e"})
public class UserSetupSuite {
  @Test public void createTenant () { ... }
  @Test(dependsOn = "createTenant") public void createAdminUser () { ... }
}

@Suite(groups = {"e2e"}, dependsOn = "com.example.UserSetupSuite")
public class BillingSuite {
  @Test public void configureBillingPlan () { ... }
}

BillingSuite is held back until UserSetupSuite has fully run and completed without a culprit. If either test in UserSetupSuite fails, every test in BillingSuite is skipped.

13.3. Custom listener (histogram of outcomes)

public class HistogramListener implements SleuthEventListener {
  private final EnumMap<SleuthEventType, AtomicInteger> counts = new EnumMap<>(SleuthEventType.class);

  @Override public void handle (SleuthEvent event) {
    counts.computeIfAbsent(event.getType(), k -> new AtomicInteger()).incrementAndGet();
  }

  public void print () {
    counts.forEach((k, v) -> System.out.println(k + " = " + v.get()));
  }
}

13.4. Running a TestNG class unmodified

import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;

@Test(groups = {"smoke"})
public class LegacyTestNgTest {
  @BeforeClass public void setup () { ... }
  @Test(priority = 1) public void a () { ... }
  @Test(priority = 2, dependsOnMethods = "a") public void b () { ... }
}

TestNGAnnotationTranslator produces a dictionary equivalent to the Sleuth-native version above, so this class runs exactly as it would have under TestNG (modulo Sleuth’s concurrency model and event taxonomy).

14. Exception Reference

Exception Thrown when

TestDependencyException

The dependency graph contains a cycle, or a dependsOn / executeAfter name does not match any discovered node. Thrown from DependencyAnalysis.calculate(), before any test executes.

TestProcessingException

A suite class cannot be instantiated — usually because it lacks a public no-arg constructor — or the constructor itself threw.

15. Package File Map

The runner module lives under sleuth/runner/src/main/java/org/smallmind/sleuth/.

File (relative to sleuth/runner/src/main/java/org/smallmind/sleuth/) Role

runner/SleuthRunner.java

Public entry point; listener registry, cancellation, and suite dispatch.

runner/SuiteRunner.java

Executes one suite’s full lifecycle.

runner/TestRunner.java

Executes one test method’s full lifecycle.

runner/TestController.java

Interface: Runnable plus complete().

runner/SleuthThreadPool.java

Two-tier semaphore-based concurrency gate.

runner/TestTier.java

Enum: SUITE, TEST.

runner/Dependency.java

Graph node.

runner/DependencyAnalysis.java

Builds the graph and topologically sorts it.

runner/DependencyQueue.java

Blocking ready-queue with culprit propagation.

runner/Culprit.java

Failure-origin record.

runner/TestContext.java

Inheritable thread-local fixture store.

runner/TestIdentifier.java

Stable per-test id for output correlation.

runner/TestDependencyException.java

Cycle or missing-dependency error.

runner/TestProcessingException.java

Suite instantiation failure.

runner/annotation/Suite.java, Test.java, BeforeSuite.java, AfterSuite.java, BeforeTest.java, AfterTest.java

Sleuth’s annotation set.

runner/annotation/*Literal.java

Programmatic annotation instances, one per annotation (used by translators).

runner/annotation/AnnotationTranslator.java

Strategy interface.

runner/annotation/NativeAnnotationTranslator.java

Recognizes Sleuth’s own annotations.

runner/annotation/TestNGAnnotationTranslator.java

Recognizes TestNG annotations.

runner/annotation/AnnotationProcessor.java

Caches the translator-chain output.

runner/annotation/AnnotationDictionary.java

Per-class scan result.

runner/annotation/AnnotationMethodology.java

Ordered, deduplicated (Method, annotation) pairs with invoke(…​).

runner/annotation/MethodCensus.java

Iterates the class hierarchy.

runner/event/SleuthEvent.java

Abstract event root.

runner/event/SleuthEventListener.java

Observer interface.

runner/event/SleuthEventType.java

Discriminator enum.

runner/event/TimedSleuthEvent.java, ThrowableSleuthEvent.java, MessageSleuthEvent.java

Abstract mixins adding elapsed, throwable, message.

runner/event/StartSleuthEvent.java, SuccessSleuthEvent.java, FailureSleuthEvent.java, ErrorSleuthEvent.java, SkippedSleuthEvent.java, FatalSleuthEvent.java, CancelledSleuthEvent.java

Concrete events.

The maven/surefire module lives under sleuth/maven/surefire/src/main/.

File Role

java/org/smallmind/sleuth/maven/surefire/SleuthProvider.java

The AbstractProvider implementation; the Surefire entry point.

java/org/smallmind/sleuth/maven/surefire/SurefireSleuthEventListener.java

Translates Sleuth events into Surefire RunListener callbacks.

java/org/smallmind/sleuth/maven/surefire/SleuthStackTraceWriter.java

Bridge between Culprit and Surefire’s StackTraceWriter.

java/org/smallmind/sleuth/maven/surefire/SleuthOutputReceiver.java

Wraps output entries with RunMode + TestIdentifier.

java/org/smallmind/sleuth/maven/surefire/ForwardingPrintStream.java

Replaces System.out / System.err so per-test output is correctly attributed.

java/org/smallmind/sleuth/maven/surefire/SleuthReportEntry.java

OutputReportEntry wrapper.

resources/meta/META-INF/services/org.apache.maven.surefire.api.provider.SurefireProvider

Service-loader descriptor registering SleuthProvider.

16. License

Sleuth is dual-licensed under the GNU Affero General Public License v3 and the Apache License 2.0, at the user’s discretion. See the license header on any source file for the full text.