Driving Tests
Two utilities work together to run Capy code synchronously inside a unit
test. run_blocking drives a coroutine to completion on the calling
thread. fuse injects errors at controlled points and reruns the test body
until every failure path is covered. set_current_thread_name labels worker
threads so that multi-threaded test output is readable.
run_blocking
run_blocking bridges async coroutine code into a synchronous test body.
It creates a single-threaded event loop on the calling thread, starts the
coroutine through it, and blocks until the coroutine finishes or throws.
It uses its own blocking executor in place of a thread pool or I/O context.
#include <boost/capy/test/run_blocking.hpp>
namespace capy = boost::capy;
capy::task<int> compute(int x)
{
co_return x * 2;
}
void test_compute()
{
int result = 0;
capy::test::run_blocking([&](int v) { result = v; })(compute(21));
BOOST_TEST(result == 42);
}
Result Capture
Call run_blocking with a lambda to capture the result. The lambda
receives the coroutine’s result on success. Separate lambdas can
handle the success and error cases independently:
// Discard result; rethrow on exception
capy::test::run_blocking()(my_task());
// Capture result; rethrow on exception
int out = 0;
capy::test::run_blocking([&](int v) { out = v; })(compute(21));
// Capture result; handle exception separately
capy::test::run_blocking(
[&](int v) { out = v; },
[](std::exception_ptr ep) { std::rethrow_exception(ep); }
)(compute(21));
// With a stop token (discards result)
std::stop_source src;
capy::test::run_blocking(src.get_token())(my_task());
// With a stop token and a result handler
capy::test::run_blocking(
src.get_token(), [&](int v) { out = v; })(compute(21));
// With a stop token and separate handlers
capy::test::run_blocking(
src.get_token(),
[&](int v) { out = v; },
[](std::exception_ptr ep) { std::rethrow_exception(ep); }
)(compute(21));
|
|
See test::run_blocking for the complete overload set. Each
overload optionally takes a function to call on success, a function to call on error, or an
external stop token.
Exercising Cancellation
The stop token supplied to run_blocking propagates through the execution
environment to the operations of the mock streams. When the token is requested, the
next awaited mock operation resolves to error::canceled instead of
performing its work, except in the cases listed below. Code under test can therefore be driven down its
cancellation paths without real I/O.
std::stop_source src;
src.request_stop();
capy::test::run_blocking(src.get_token())([&]() -> capy::task<>
{
capy::test::read_stream rs;
rs.provide("ignored");
char buf[32];
auto [ec, n] = co_await rs.read_some(capy::make_buffer(buf));
assert(ec == capy::cond::canceled); // honored the stop token
}());
The mock streams complete synchronously, so they
check the token up front. A connected stream whose read_some is blocked
waiting for its peer is resumed with error::canceled when the token fires. A
read that can satisfy from already-buffered data is unaffected. So is a read on a closed
stream pair, or after the peer called close() with nothing buffered: it returns error::eof. An operation on an
empty buffer sequence completes successfully regardless of the token.
fuse
fuse tests every error-handling path in a coroutine by injecting failures
systematically. Each call to maybe_fail() is a potential failure point.
The returned result converts to bool and, on failure, carries the source
location of the failing call.
#include <boost/capy/test/fuse.hpp>
namespace capy = boost::capy;
void test_with_fuse()
{
capy::test::fuse f;
auto r = f.armed([](capy::test::fuse& f) {
auto ec = f.maybe_fail();
if(ec)
return; // injected error: exit gracefully
ec = f.maybe_fail();
if(ec)
return;
});
BOOST_TEST(r.success);
}
armed() vs. inert()
armed() runs the test body in two full passes (error-code mode, then
exception mode) and is the normal choice for exhaustive error coverage.
inert() runs the test body exactly once with no injection. Calls to
maybe_fail() always return an empty error code and never throw.
Use inert() for happy-path verification ("does this work when nothing
fails?"). Use armed() for fault-tolerance verification ("does this
handle a failure at every async step?"). A typical test suite pairs both:
capy::test::fuse f;
// Smoke test: happy path
auto r1 = f.inert([&](capy::test::fuse&) -> capy::task<void> {
capy::test::read_stream rs(f);
rs.provide("hello");
char buf[8];
auto [ec, n] = co_await rs.read_some(capy::make_buffer(buf));
BOOST_TEST(!ec);
BOOST_TEST(std::string_view(buf, n) == "hello");
});
BOOST_TEST(r1.success);
// Fault coverage: every error site
auto r2 = f.armed([&](capy::test::fuse&) -> capy::task<void> {
capy::test::read_stream rs(f);
rs.provide("hello");
char buf[8];
auto [ec, n] = co_await rs.read_some(capy::make_buffer(buf));
if(ec)
co_return; // fuse injected an error; exit gracefully
BOOST_TEST(std::string_view(buf, n) == "hello");
});
BOOST_TEST(r2.success);
The only difference is the if(ec) co_return; guard. In inert(),
that guard is dead code (maybe_fail() never returns an error); in
armed(), it is essential.
Under inert(), the body fails only by calling f.fail() or by letting an
exception escape. To fail explicitly, call f.fail() from inside the body:
capy::test::fuse f;
auto r = f.inert([](capy::test::fuse& f) {
auto ec = f.maybe_fail(); // always returns {}
assert(!ec);
// f.fail() marks failure explicitly; an escaping exception also fails the run
if(some_condition_failed)
f.fail();
});
BOOST_TEST(r.success);
The Early-Return Pattern
When armed() injects an error, the test body receives it from
maybe_fail(). The body must exit immediately rather than continuing
as though the operation succeeded. The mock streams also call maybe_fail()
internally, so this pattern applies to all I/O calls inside an armed test.
// Correct: early return on injected error
auto [ec, n] = co_await rs.read_some(buf);
if(ec)
co_return; // fuse injected an error -- exit gracefully
// Wrong: asserting success unconditionally
auto [ec, n] = co_await rs.read_some(buf);
BOOST_TEST(!ec); // fails when fuse injects an error
Coroutine Support
armed() detects when the test lambda returns a ContextRunnable (such as
task<void>) and drives it to completion via run_blocking internally.
You do not need to call run_blocking yourself:
capy::test::fuse f;
auto r = f.armed([&](capy::test::fuse&) -> capy::task<void> {
auto ec = f.maybe_fail();
if(ec)
co_return;
auto [ec2, n] = co_await rs.read_some(buf);
if(ec2)
co_return;
});
BOOST_TEST(r.success);
Custom Fail Points
A type that holds a fuse reference can call maybe_fail() from its own
methods to declare additional fail points beyond those built into the
mocks. Outside armed() or inert() the call is a no-op (returns an
empty error code immediately). Inside armed() the call participates in
fault injection alongside every other site.
class widget
{
capy::test::fuse& f_;
public:
explicit widget(capy::test::fuse& f) : f_(f) {}
std::error_code process()
{
auto ec = f_.maybe_fail();
if(ec)
return ec;
// ... actual work ...
return {};
}
};
capy::test::fuse f;
widget w(f);
w.process(); // maybe_fail() returns {}
// both branches exercised
auto r = f.armed([&](capy::test::fuse&) { w.process(); });
BOOST_TEST(r.success);
Custom Error Code
The default injected code is error::test_failure. Pass any
std::error_code to the constructor to change it:
capy::test::fuse f(
std::make_error_code(std::errc::operation_canceled));
auto r = f.armed([](capy::test::fuse& f) {
auto ec = f.maybe_fail();
if(ec)
{
assert(ec == std::errc::operation_canceled);
return;
}
});
BOOST_TEST(r.success);
See test::fuse for the complete member list. It covers both
constructors, the armed/inert/operator() entry points,
maybe_fail, the fail overloads, and `result’s fields.
thread_name
set_current_thread_name names the calling thread so that debuggers,
htop, and core dumps show a recognizable label instead of a generic thread
ID. This is most useful when a test failure occurs inside a thread pool
worker and you need to identify which worker was involved.
Platform limits on the name length:
-
Linux, FreeBSD: 15 characters
-
NetBSD:
PTHREAD_MAX_NAMELEN_NP - 1characters -
macOS: 63 characters
-
Windows: no practical limit
On other platforms the call does nothing.
#include <boost/capy/ex/run_async.hpp>
#include <boost/capy/ex/thread_pool.hpp>
#include <boost/capy/task.hpp>
#include <boost/capy/ex/thread_name.hpp>
namespace capy = boost::capy;
capy::thread_pool pool(4);
capy::run_async(pool.get_executor())([]() -> capy::task<void> {
capy::set_current_thread_name("test-worker-0");
// ... test work runs here; name appears in gdb thread list
co_return;
}());
pool.join();
set_current_thread_name is declared in <boost/capy/ex/thread_name.hpp>,
in namespace boost::capy. It sits beside the executors rather than in the testing toolkit.
Putting It Together
The canonical test skeleton combines a small coroutine and fuse.armed():
#include <boost/capy/task.hpp>
#include <boost/capy/test/fuse.hpp>
namespace capy = boost::capy;
capy::task<int> add(int a, int b)
{
co_return a + b;
}
void test_add()
{
capy::test::fuse f;
auto r = f.armed([&](capy::test::fuse&) -> capy::task<void> {
auto sum = co_await add(3, 4);
BOOST_TEST(sum == 7);
});
BOOST_TEST(r.success);
}
Use the armed(run_one, fn) overload when the operation under test needs a
specific execution context. Operations built on corosio::timeout or
corosio::delay, for example, require an io_context, which run_blocking
does not provide. The caller supplies run_one, which drives each iteration’s
task on a context it owns. run_one returns any exception the task raised as a
std::exception_ptr, or null on success, and armed rethrows it.
fuse never learns about the context — the caller owns the drive loop:
capy::test::fuse f;
auto io_runner = [](capy::task<void> t) -> std::exception_ptr {
corosio::io_context ioc;
std::exception_ptr ep;
capy::run_async(ioc.get_executor(),
[](auto&&...){}, [&ep](std::exception_ptr e){ ep = e; })(std::move(t));
ioc.run();
return ep;
};
auto r = f.armed(
io_runner,
[&](capy::test::fuse&) -> capy::task<void> {
co_await corosio::timeout(some_op(), 5s);
});
BOOST_TEST(r.success);
run_one must return the exception rather than rethrow it. An exception
escaping a run_async completion handler calls std::terminate. The
completion handler therefore captures it, and the runner hands it back once the run loop
is done.
A fresh io_context per iteration (as above) needs no restart(); reuse one
across iterations only if you call restart() between rounds.
Shared State Across Copies
Every copy of a fuse object shares the same state, so all copies respond
to the same armed() or inert() call. Pass a copy of f to each mock at
construction time, then call f.armed(…) once.
For tests that need mocks, replace add with a function that takes a
read_stream, write_stream, or other mock.
Construct those mocks with the same fuse f. The armed loop then exercises every I/O
failure path through both error-code and exception modes automatically.