Skip to content

RabbitMQ and other message queues: keeping test context across async hops

By Melih Sakarya · Published · 5 min read

Bu yazının Türkçesi →

Tests in a CoverOps run, each with the services and endpoints it reached

Short answer

Every asynchronous hop is a place where a functional test loses track of the code it caused. Here is how CoverOps carries the test context through RabbitMQ without code on the JVM, how to carry it through a raw consumer or a transport the agent does not know, and which async work stays outside per-test coverage.

Short answer: a message queue breaks per-test coverage unless the message carries the test's identity. CoverOps puts it in the message headers. On the JVM with tracing on, every RabbitMQ basicPublish, RabbitTemplate included, writes the test context, and Spring AMQP listeners run in the message's context, so the consumer's code is filed under the test that sent the message. A raw basicConsume consumer, a transport the agent does not know and work handed to another thread need a few lines. Timers and background jobs that never adopt a message's context stay outside per-test coverage; their lines still count for the run.

Every async hop is a place to lose the test

A functional test sends a request and checks the answer. Much of what the system then does happens out of sight: a consumer updates a read model, a worker sends the email, a job reindexes search. None of that runs on a thread that saw the test's request. If the work is not told which test caused it, its coverage is real but has no owner. It appears in the service's total, under no test, and test selection cannot connect a change in that consumer to the test that exercises it.

The fix is the one distributed tracing uses: write the context into the message on the way in to the queue, and adopt it around the handler on the way out.

RabbitMQ on the JVM: automatic

Start the services with COVERAGEOPS_TRACE=true. The Java agent then carries the context without code:

  • Publishing: every basicPublish, RabbitTemplate included, writes the message headers: the X-CoverageOps-Trace chain header and the test's X-CoverageOps-Test, -Test-Id and -Run. Headers are replaced, never added, so a message published twice does not carry two sets.
  • Consuming with Spring AMQP: listeners run in the message's context. The code they run is filed under the test that published the message, and the consumer appears as the next hop of the publisher's chain.
  • Inside a request: a thread that is already handling a request keeps it; a message read in the middle of an HTTP call belongs to that call.

Tests in a CoverOps run, each with the services and endpoints it reached

A raw consumer: one call around the handler

A consumer passed straight to basicConsume is not followed on its own. Adopt the message's headers around its handling:

import io.coverageops.agent.api.Trace;

channel.basicConsume("orders", false, (tag, delivery) -> {
  Trace.adoptMessage(delivery.getProperties().getHeaders(), "consume orders");
  try {
    handle(delivery.getBody());
    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
  } finally {
    Trace.endMessage();
  }
}, tag -> { });

AMQP header values arrive as LongString, not String; adoptMessage reads them as they are, matches names without regard to case, and does nothing when the message has no headers.

Any other transport: the same two calls

The agent writes the context by itself only on the clients it knows. For anything else, such as another broker, a job table or an in-house event bus, the public API is the same on both ends. Trace.outboundHeaders() returns every header to put on an outbound call or message, and is empty when there is nothing to carry. Trace.adoptMessage takes them back on the other side:

// sending: store the context with the job, wherever your transport keeps metadata
job.metadata().putAll(Trace.outboundHeaders());

// the worker
Trace.adoptMessage(job.metadata(), "job reindex");
try {
  reindex(job);
} finally {
  Trace.endMessage();
}

job.metadata() stands for whatever your transport calls its headers or attributes. The rule is that the values travel with the message, unchanged.

Other runtimes

  • Ruby: Bunny publishes carry the context automatically. A consumer adopts it with CoverageOps.with_context(message.headers, label: "orders.created") { handle(message) }.
  • Node.js, Go, Python, .NET and PHP: message hops are carried by hand: put the agent's outbound headers on the message when you publish it. A JVM or Ruby consumer on the other side adopts them as described above.

A hop that does not carry the headers still has its coverage in the run, just not under the test, and the chain breaks there.

Work that stays outside per-test coverage

  • Timers and schedulers. A job that runs every minute was not caused by any test. It is not traced, and the run page's live feed lists this among the things to check when no steps arrive.
  • Background queue jobs that do not adopt a context. Same: lines in the run, no test.
  • Work handed to another thread (@Async, an executor, CompletableFuture) is not followed automatically on the JVM; the context has to be carried across the hand-off.
  • Start-up code runs once at boot, before any test is in scope. The run page tells start-up code apart from traffic that ran with no test in scope.

Delayed and late messages

Traffic can only choose among runs that are already open. A run named in a message is honoured while it is open, or for 10 minutes after it finished. A consumer that is a little behind still lands in the right run. A message delayed longer than that, by a long TTL, a delayed retry or a backed-up queue, files its work in the consuming agent's own run.

Checking that the context survived

  1. Open a test that publishes a message and look at its flow: the consumer should be the next hop.
  2. Watch the application cards while the run is going: a consumer service that never shows live is not tracing, or not being reached.
  3. Look at the service map: a publisher with no edge to its consumer marks a hop that lost the context.
  4. Open a consumer file on the run page: Tests that touched this file should name the tests that published to it.

Services in a running CoverOps run, each showing live while it sends trace frames

CoverOps service map with an edge from the publishing service to the consuming service

What carrying the context buys you

  • Consumers stop being anonymous. A consumer's lines appear under the tests that published to it, so "which test covers the refund email" has an answer.
  • Test selection follows the message. A change in a consumer selects the tests whose footprint reaches it, including the ones that only reach it through the queue.
  • Failure diagnosis sees the whole path. When a test fails, its footprint, consumer included, is compared with what changed since it last passed.
  • Changed-code coverage counts consumer lines that the build's tests ran through a queue, not only the lines behind HTTP endpoints.

Limits to know

  • The broker itself is not measured, only code in a process with an agent.
  • Automatic carrying is on the JVM (RabbitMQ publish and Spring AMQP listeners) and on Ruby publishes; elsewhere it is by hand.
  • Messages handled more than 10 minutes after the run finished do not land in it.
  • Consumers in one process that handle messages of overlapping tests share a coverage window: each test keeps all of its lines, and the overlap is recorded.

This post is part of the functional test coverage in distributed systems series. For Kafka specifically, see following a test through Kafka; for what each test reached, per-test coverage across microservices. The concepts guide has the full propagation table, and the integration test coverage page has the product summary.

Related posts

  • Parallel functional tests and per-test coverage: what stays exact, what is shared

    Functional suites run in parallel to fit into CI, and every parallel test hits the same long-running services. Line counters cannot say which of two simultaneous requests ran a line. Here is what CoverOps keeps exact anyway, what it shares and labels, how each agent draws the line, and how to keep the shared part small.

  • Paralel fonksiyonel testlerde test bazında coverage: ne kesin kalır, ne paylaşılır

    Fonksiyonel suite'ler CI süresine sığmak için paralel koşar ve her paralel test aynı uzun ömürlü servislere gider. Satır sayaçları, aynı anda gelen iki istekten hangisinin bir satırı çalıştırdığını söyleyemez. CoverOps'un yine de neyi kesin tuttuğunu, neyi paylaştırıp işaretlediğini, her agent'ın sınırı nasıl çizdiğini ve paylaşılan kısmı nasıl küçük tutacağınızı anlatıyoruz.

  • Changed-code coverage as a merge gate when a change spans services

    Diff coverage from one repository's unit tests cannot see that the new lines in the inventory consumer only run when an end-to-end test places an order. Here is how to gate a merge on the changed lines your functional tests actually ran, in every service, and how to keep a service that did not run from quietly passing the gate.

See which tests reach your own code

We connect one of your services in a demo and show what your tests executed, and what they never reached.