TLA Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3 : // Copyright (c) 2026 Michael Vandeberg
4 : //
5 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
6 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 : //
8 : // Official repository: https://github.com/cppalliance/capy
9 : //
10 :
11 : #ifndef BOOST_CAPY_TEST_FUSE_HPP
12 : #define BOOST_CAPY_TEST_FUSE_HPP
13 :
14 : #include <boost/capy/detail/config.hpp>
15 : #include <boost/capy/concept/context_runnable.hpp>
16 : #include <boost/capy/error.hpp>
17 : #include <boost/capy/test/run_blocking.hpp>
18 : #include <system_error>
19 : #include <concepts>
20 : #include <cstddef>
21 : #include <exception>
22 : #include <limits>
23 : #include <memory>
24 : #include <source_location>
25 : #include <type_traits>
26 :
27 : /*
28 : LLM/AI Instructions for fuse-based test patterns:
29 :
30 : When f.armed() runs a test, it injects errors at successive points
31 : via maybe_fail(). Operations like read_stream::read_some() and
32 : write_stream::write_some() call maybe_fail() internally.
33 :
34 : CORRECT pattern - early return on injected error:
35 :
36 : auto [ec, n] = co_await rs.read_some(buf);
37 : if(ec)
38 : co_return; // fuse injected error, exit gracefully
39 : // ... continue with success path
40 :
41 : WRONG pattern - asserting success unconditionally:
42 :
43 : auto [ec, n] = co_await rs.read_some(buf);
44 : BOOST_TEST(! ec); // FAILS when fuse injects error!
45 :
46 : The fuse mechanism tests error handling by failing at each point
47 : in sequence. Tests must handle injected errors by returning early,
48 : not by asserting that operations always succeed.
49 : */
50 :
51 : namespace boost {
52 : namespace capy {
53 : namespace test {
54 :
55 : /** Reruns a code path, injecting a failure at one later point on each pass.
56 :
57 : This class enables exhaustive testing of error handling
58 : paths by injecting failures at successive points in code.
59 : Each iteration fails at a later point until the code path
60 : completes without encountering a failure. The @ref armed
61 : method runs in two phases: first with error codes, then
62 : with exceptions. The @ref inert method runs once without
63 : automatic failure injection.
64 :
65 : @par Thread Safety
66 :
67 : @b Not @b thread @b safe. Instances must not be accessed
68 : from different logical threads of operation concurrently.
69 : This includes coroutines - accessing the same fuse from
70 : multiple concurrent coroutines causes non-deterministic
71 : test behavior.
72 :
73 : @note A fuse supports a single @ref armed or @ref inert run.
74 : Copies share the same state. A second run on the same state
75 : may skip error-code injection. After any @ref fail call, every
76 : later run on that state reports failure. Construct a new fuse
77 : for each run.
78 :
79 : @par Basic Inline Usage
80 :
81 : @par !example example_1
82 :
83 :
84 : @par Named Fuse with armed()
85 :
86 : @par !example example_2
87 :
88 :
89 : @par Using inert() for Single-Run Tests
90 :
91 : @par !example example_3
92 :
93 :
94 : @par Dependency Injection (Standalone Usage)
95 :
96 : A default-constructed fuse is a no-op when used outside
97 : of @ref armed or @ref inert. This enables passing a fuse
98 : to classes for dependency injection without affecting
99 : normal operation.
100 :
101 : @par !example example_4
102 :
103 :
104 : @par Custom Error Code
105 :
106 : @par !example example_5
107 :
108 :
109 : @par Checking the Result
110 :
111 : @par !example example_6
112 :
113 :
114 : @par Test Framework Integration
115 :
116 : @par !example example_7
117 :
118 : */
119 : class fuse
120 : {
121 : struct state
122 : {
123 : std::size_t n = (std::numeric_limits<std::size_t>::max)();
124 : std::size_t i = 0;
125 : bool triggered = false;
126 : bool throws = false;
127 : bool stopped = false;
128 : bool inert = true;
129 : std::error_code ec;
130 : std::source_location loc;
131 : std::exception_ptr ep;
132 : };
133 :
134 : std::shared_ptr<state> p_;
135 :
136 : /** Return true if testing should continue.
137 :
138 : On the first call, initializes the failure point to 0.
139 : After a triggered failure, increments the failure point
140 : and resets for the next iteration. Returns false when
141 : the test completes without triggering a failure.
142 : */
143 HIT 1326 : explicit operator bool() const noexcept
144 : {
145 1326 : auto& s = *p_;
146 1326 : if(s.n == (std::numeric_limits<std::size_t>::max)())
147 : {
148 : // First call: start round 0
149 313 : s.n = 0;
150 313 : return true;
151 : }
152 1013 : if(s.triggered)
153 : {
154 : // Previous round triggered, try next failure point
155 707 : s.n++;
156 707 : s.i = 0;
157 707 : s.triggered = false;
158 707 : return true;
159 : }
160 : // Test completed without trigger: success
161 306 : return false;
162 : }
163 :
164 : public:
165 : /** Converts to `bool`, reporting success, and carries the failure point on failure.
166 :
167 : Contains the outcome of @ref armed or @ref inert
168 : and, on failure, the source location of the failing
169 : point. Converts to `bool` for convenient success
170 : checking.
171 :
172 : @par Example
173 :
174 : @par !example example
175 :
176 : */
177 : struct result
178 : {
179 : /// Source location of the failing point, set only on failure.
180 : std::source_location loc = {};
181 :
182 : /** Exception associated with the failure, or null if none.
183 :
184 : Holds the exception passed to @ref fail. Under @ref inert
185 : it also holds an exception that escaped the test function.
186 : Under @ref armed an escaping exception is not stored.
187 : */
188 : std::exception_ptr ep = nullptr;
189 :
190 : /// True if the test completed without a failure.
191 : bool success = true;
192 :
193 : /** Return whether the test completed without a failure.
194 :
195 : @return @ref success.
196 : */
197 42 : constexpr explicit operator bool() const noexcept
198 : {
199 42 : return success;
200 : }
201 : };
202 :
203 : /** Construct a fuse with a custom error code.
204 :
205 : @par Example
206 :
207 : @par !example example_1
208 :
209 :
210 : @param ec The error code to deliver at failure points.
211 : */
212 259 : explicit fuse(std::error_code ec)
213 259 : : p_(std::make_shared<state>())
214 : {
215 259 : p_->ec = ec;
216 259 : }
217 :
218 : /** Construct a fuse with the default error code.
219 :
220 : The default error code is `error::test_failure`.
221 :
222 : @par Example
223 :
224 : @par !example example_2
225 :
226 : */
227 256 : fuse()
228 256 : : fuse(error::test_failure)
229 : {
230 256 : }
231 :
232 : /** Return an error or throw at the current failure point.
233 :
234 : When running under @ref armed, increments the internal
235 : counter. When the counter reaches the current failure
236 : point, returns the stored error code (or throws
237 : `std::system_error` in exception mode) and records
238 : the source location.
239 :
240 : When called outside of @ref armed or @ref inert (standalone
241 : usage), or when running under @ref inert, always returns
242 : an empty error code. This enables dependency injection
243 : where the fuse is a no-op in production code.
244 :
245 : @par Example
246 :
247 : @par !example example_1
248 :
249 :
250 : @par Standalone Usage
251 :
252 : @par !example example_2
253 :
254 :
255 : @param loc The source location of the call site,
256 : captured automatically.
257 :
258 : @throws std::system_error When in exception mode
259 : and at the failure point (not thrown outside @ref armed).
260 :
261 : @return The stored error code at the failure point, otherwise
262 : an empty error code.
263 : */
264 : std::error_code
265 1749 : maybe_fail(
266 : std::source_location loc = std::source_location::current())
267 : {
268 1749 : auto& s = *p_;
269 1749 : if(s.inert)
270 326 : return {};
271 1423 : if(s.i < s.n)
272 1152 : ++s.i;
273 1423 : if(s.i == s.n)
274 : {
275 707 : s.triggered = true;
276 707 : s.loc = loc;
277 707 : if(s.throws)
278 347 : throw std::system_error(s.ec);
279 360 : return s.ec;
280 : }
281 716 : return {};
282 : }
283 :
284 : /** Record a test failure.
285 :
286 : Call this from the test function to indicate a failure
287 : condition. The call only records the failure: the test
288 : function keeps running, so return from it right after the
289 : call. Once the test function returns, @ref armed or
290 : @ref inert reports a failed @ref result and runs no
291 : further rounds.
292 :
293 : @par Example
294 :
295 : @par !example example_1
296 :
297 :
298 : @param loc The source location of the call site,
299 : captured automatically.
300 : */
301 : void
302 3 : fail(
303 : std::source_location loc =
304 : std::source_location::current()) noexcept
305 : {
306 3 : p_->loc = loc;
307 3 : p_->stopped = true;
308 3 : }
309 :
310 : /** Record a test failure with an associated exception.
311 :
312 : Call this from the test function to indicate a failure
313 : condition with an associated exception. The call only
314 : records the failure: the test function keeps running, so
315 : return from it right after the call. Once the test function
316 : returns, @ref armed or @ref inert reports a failed
317 : @ref result holding `ep`.
318 :
319 : @par Example
320 :
321 : @par !example example_2
322 :
323 :
324 : @param ep The exception pointer to capture.
325 :
326 : @param loc The source location of the call site,
327 : captured automatically.
328 : */
329 : void
330 2 : fail(
331 : std::exception_ptr ep,
332 : std::source_location loc =
333 : std::source_location::current()) noexcept
334 : {
335 2 : p_->ep = ep;
336 2 : p_->loc = loc;
337 2 : p_->stopped = true;
338 2 : }
339 :
340 : private:
341 : /* Drive the two-phase armed loop, invoking `do_iter` once per round.
342 :
343 : Phase 1 delivers injected failures as error codes; phase 2 as
344 : exceptions. Shared by the two coroutine `armed` overloads: each
345 : supplies a nullary `do_iter` that runs one iteration — via
346 : @ref run_blocking, or via a caller-supplied runner — so the round
347 : sequence and failure handling stay identical across them.
348 : */
349 : template<class DoIter>
350 : result
351 134 : run_phases(DoIter&& do_iter)
352 : {
353 134 : result r;
354 :
355 : // Phase 1: error code mode
356 134 : p_->throws = false;
357 134 : p_->inert = false;
358 134 : p_->n = (std::numeric_limits<std::size_t>::max)();
359 581 : while(*this)
360 : {
361 : try
362 : {
363 448 : do_iter();
364 : }
365 2 : catch(...)
366 : {
367 1 : r.success = false;
368 1 : r.loc = p_->loc;
369 1 : r.ep = p_->ep;
370 1 : p_->inert = true;
371 1 : return r;
372 : }
373 447 : if(p_->stopped)
374 : {
375 MIS 0 : r.success = false;
376 0 : r.loc = p_->loc;
377 0 : r.ep = p_->ep;
378 0 : p_->inert = true;
379 0 : return r;
380 : }
381 : }
382 :
383 : // Phase 2: exception mode
384 HIT 133 : p_->throws = true;
385 133 : p_->n = (std::numeric_limits<std::size_t>::max)();
386 133 : p_->i = 0;
387 133 : p_->triggered = false;
388 578 : while(*this)
389 : {
390 : try
391 : {
392 445 : do_iter();
393 : }
394 624 : catch(std::system_error const& ex)
395 : {
396 312 : if(ex.code() != p_->ec)
397 : {
398 MIS 0 : r.success = false;
399 0 : r.loc = p_->loc;
400 0 : r.ep = p_->ep;
401 0 : p_->inert = true;
402 0 : return r;
403 : }
404 : }
405 0 : catch(...)
406 : {
407 0 : r.success = false;
408 0 : r.loc = p_->loc;
409 0 : r.ep = p_->ep;
410 0 : p_->inert = true;
411 0 : return r;
412 : }
413 HIT 445 : if(p_->stopped)
414 : {
415 MIS 0 : r.success = false;
416 0 : r.loc = p_->loc;
417 0 : r.ep = p_->ep;
418 0 : p_->inert = true;
419 0 : return r;
420 : }
421 : }
422 HIT 133 : p_->inert = true;
423 133 : return r;
424 MIS 0 : }
425 :
426 : public:
427 : /** Run a test function with systematic failure injection.
428 :
429 : Repeatedly invokes the provided function, failing at
430 : successive points until the function completes without
431 : encountering a failure. First runs the complete loop
432 : using error codes, then runs using exceptions.
433 :
434 : In the error-code phase, any exception escaping `fn` ends the
435 : run with a failed @ref result. In the exception phase, a
436 : `std::system_error` carrying the fuse's error code counts as an
437 : injected failure, and the next round starts. Any other
438 : exception ends the run with a failed @ref result. An exception
439 : escaping `fn` is not stored in `result::ep`.
440 :
441 : On failure, `result::loc` holds the location of the last
442 : triggered @ref maybe_fail or of the @ref fail call.
443 :
444 : @par Example
445 :
446 : @par !example example_2
447 :
448 :
449 : @param fn The test function to invoke. It receives
450 : a reference to the fuse and should call @ref maybe_fail
451 : at each potential failure point.
452 :
453 : @return A @ref result indicating success or failure.
454 : */
455 : template<class F>
456 : result
457 HIT 26 : armed(F&& fn)
458 : {
459 26 : result r;
460 :
461 : // Phase 1: error code mode
462 26 : p_->throws = false;
463 26 : p_->inert = false;
464 26 : p_->n = (std::numeric_limits<std::size_t>::max)();
465 92 : while(*this)
466 : {
467 : try
468 : {
469 72 : fn(*this);
470 : }
471 6 : catch(...)
472 : {
473 3 : r.success = false;
474 3 : r.loc = p_->loc;
475 3 : r.ep = p_->ep;
476 3 : p_->inert = true;
477 3 : return r;
478 : }
479 69 : if(p_->stopped)
480 : {
481 3 : r.success = false;
482 3 : r.loc = p_->loc;
483 3 : r.ep = p_->ep;
484 3 : p_->inert = true;
485 3 : return r;
486 : }
487 : }
488 :
489 : // Phase 2: exception mode
490 20 : p_->throws = true;
491 20 : p_->n = (std::numeric_limits<std::size_t>::max)();
492 20 : p_->i = 0;
493 20 : p_->triggered = false;
494 75 : while(*this)
495 : {
496 : try
497 : {
498 55 : fn(*this);
499 : }
500 70 : catch(std::system_error const& ex)
501 : {
502 35 : if(ex.code() != p_->ec)
503 : {
504 MIS 0 : r.success = false;
505 0 : r.loc = p_->loc;
506 0 : r.ep = p_->ep;
507 0 : p_->inert = true;
508 0 : return r;
509 : }
510 : }
511 0 : catch(...)
512 : {
513 0 : r.success = false;
514 0 : r.loc = p_->loc;
515 0 : r.ep = p_->ep;
516 0 : p_->inert = true;
517 0 : return r;
518 : }
519 HIT 55 : if(p_->stopped)
520 : {
521 MIS 0 : r.success = false;
522 0 : r.loc = p_->loc;
523 0 : r.ep = p_->ep;
524 0 : p_->inert = true;
525 0 : return r;
526 : }
527 : }
528 HIT 20 : p_->inert = true;
529 20 : return r;
530 MIS 0 : }
531 :
532 : /** Run a coroutine test function with systematic failure injection.
533 :
534 : Repeatedly invokes the provided coroutine function, failing at
535 : successive points until the function completes without
536 : encountering a failure. First runs the complete loop
537 : using error codes, then runs using exceptions.
538 :
539 : This overload handles lambdas that return an @ref ContextRunnable
540 : (such as `task<void>`), executing them synchronously via
541 : @ref run_blocking.
542 :
543 : In the error-code phase, any exception escaping `fn` ends the
544 : run with a failed @ref result. In the exception phase, a
545 : `std::system_error` carrying the fuse's error code counts as an
546 : injected failure, and the next round starts. Any other
547 : exception ends the run with a failed @ref result. An exception
548 : escaping `fn` is not stored in `result::ep`.
549 :
550 : On failure, `result::loc` holds the location of the last
551 : triggered @ref maybe_fail or of the @ref fail call.
552 :
553 : @par Example
554 :
555 : @par !example example_3
556 :
557 :
558 : @param fn The coroutine test function to invoke. It receives
559 : a reference to the fuse and should call @ref maybe_fail
560 : at each potential failure point.
561 :
562 : @return A @ref result indicating success or failure.
563 : */
564 : template<class F>
565 : requires ContextRunnable<std::invoke_result_t<F, fuse&>>
566 : result
567 HIT 131 : armed(F&& fn)
568 : {
569 1445 : return run_phases([&]{ run_blocking()(fn(*this)); });
570 : }
571 :
572 : /** Run a coroutine test function on a caller-supplied runner.
573 :
574 : Behaves like the @ref ContextRunnable overload of @ref armed, but
575 : instead of driving each iteration through @ref run_blocking, it
576 : hands the coroutine to `run_one`. This lets a caller run each
577 : iteration on any execution context it chooses. Operations built
578 : on `corosio::timeout` or `corosio::delay` in particular require
579 : an `io_context`, because they abort on a non-`io_context`
580 : executor. `fuse` never learns about the context;
581 : the caller owns the drive loop.
582 :
583 : @par Runner contract
584 : `run_one` is invoked once per round with the @ref ContextRunnable
585 : produced by `fn`. It must run that task to completion
586 : synchronously and *return* any exception the task raised as a
587 : `std::exception_ptr` (null on success). It must not rethrow.
588 : `armed` rethrows the returned pointer from its own synchronous
589 : code, so the exception phase observes injected failures. An
590 : exception escaping a `run_async` completion handler would
591 : instead call `std::terminate`. Capture the exception in the error
592 : handler and return it once the run loop is done.
593 :
594 : @par Example
595 : @par !example example_1
596 :
597 :
598 : @param run_one A callable invoked with each iteration's task; it
599 : runs the task to completion and returns any escaped exception
600 : (null on success) without rethrowing.
601 :
602 : @param fn The coroutine test function to invoke.
603 :
604 : @return A @ref result indicating success or failure.
605 : */
606 : template<class Runner, class F>
607 : requires ContextRunnable<std::invoke_result_t<F, fuse&>>
608 : && std::same_as<
609 : std::invoke_result_t<Runner&, std::invoke_result_t<F, fuse&>>,
610 : std::exception_ptr>
611 : result
612 3 : armed(Runner&& run_one, F&& fn)
613 : {
614 14 : return run_phases([&]{
615 23 : if(auto ep = run_one(fn(*this)))
616 12 : std::rethrow_exception(ep);
617 6 : });
618 : }
619 :
620 : /** Alias for @ref armed.
621 :
622 : Allows the fuse to be invoked directly as a function
623 : object for more concise syntax.
624 :
625 : @par Example
626 :
627 : @par !example example
628 :
629 :
630 : @param fn The test function to run under failure injection.
631 :
632 : @return The @ref result of the armed run.
633 :
634 : @see @ref armed
635 : */
636 : template<class F>
637 : result
638 15 : operator()(F&& fn)
639 : {
640 15 : return armed(std::forward<F>(fn));
641 : }
642 :
643 : /** Alias for @ref armed (coroutine overload).
644 :
645 : @param fn The test coroutine factory to run under failure injection.
646 :
647 : @return The @ref result of the armed run.
648 :
649 : @see @ref armed
650 : */
651 : template<class F>
652 : requires ContextRunnable<std::invoke_result_t<F, fuse&>>
653 : result
654 : operator()(F&& fn)
655 : {
656 : return armed(std::forward<F>(fn));
657 : }
658 :
659 : /** Run a test function once without failure injection.
660 :
661 : Invokes the provided function exactly once. Calls to
662 : @ref maybe_fail always return an empty error code and
663 : never throw. A call to @ref fail or an exception escaping
664 : `fn` signals a test failure. The escaping exception is
665 : stored in `result::ep`.
666 :
667 : On failure after a @ref fail call, `result::loc` holds the
668 : location of that call.
669 :
670 : This is useful for running tests where you want to
671 : manually control failures, or for quick single-run
672 : tests without systematic error injection.
673 :
674 : @par Example
675 :
676 : @par !example example_1
677 :
678 :
679 : @param fn The test function to invoke. It receives
680 : a reference to the fuse. Calls to @ref maybe_fail
681 : always succeed.
682 :
683 : @return A @ref result indicating success or failure.
684 : */
685 : template<class F>
686 : result
687 9 : inert(F&& fn)
688 : {
689 9 : result r;
690 9 : p_->inert = true;
691 : try
692 : {
693 9 : fn(*this);
694 : }
695 2 : catch(...)
696 : {
697 1 : r.success = false;
698 1 : r.loc = p_->loc;
699 1 : r.ep = std::current_exception();
700 1 : return r;
701 : }
702 8 : if(p_->stopped)
703 : {
704 2 : r.success = false;
705 2 : r.loc = p_->loc;
706 2 : r.ep = p_->ep;
707 : }
708 8 : return r;
709 MIS 0 : }
710 :
711 : /** Run a coroutine test function once without failure injection.
712 :
713 : Invokes the provided coroutine function exactly once using
714 : @ref run_blocking. Calls to @ref maybe_fail always return
715 : an empty error code and never throw. A call to @ref fail or
716 : an exception escaping the coroutine signals a test failure.
717 : The escaping exception is stored in `result::ep`.
718 :
719 : On failure after a @ref fail call, `result::loc` holds the
720 : location of that call.
721 :
722 : @par Example
723 :
724 : @par !example example_2
725 :
726 :
727 : @param fn The coroutine test function to invoke. It receives
728 : a reference to the fuse. Calls to @ref maybe_fail
729 : always succeed.
730 :
731 : @return A @ref result indicating success or failure.
732 : */
733 : template<class F>
734 : requires ContextRunnable<std::invoke_result_t<F, fuse&>>
735 : result
736 HIT 44 : inert(F&& fn)
737 : {
738 44 : result r;
739 44 : p_->inert = true;
740 : try
741 : {
742 44 : run_blocking()(fn(*this));
743 : }
744 MIS 0 : catch(...)
745 : {
746 0 : r.success = false;
747 0 : r.loc = p_->loc;
748 0 : r.ep = std::current_exception();
749 0 : return r;
750 : }
751 HIT 44 : if(p_->stopped)
752 : {
753 MIS 0 : r.success = false;
754 0 : r.loc = p_->loc;
755 0 : r.ep = p_->ep;
756 : }
757 HIT 44 : return r;
758 MIS 0 : }
759 : };
760 :
761 : } // test
762 : } // capy
763 : } // boost
764 :
765 : #endif
|