| 1 | /** |
| 2 | * \file t/tap.h |
| 3 | * |
| 4 | * \brief |
| 5 | * Helpers for following the Test Anything Protocol. |
| 6 | * |
| 7 | * Its interface mimics Test::More from Perl: |
| 8 | * https://perldoc.perl.org/Test/More.html |
| 9 | * |
| 10 | * Unlike Test::More, a test failure raises an exception and aborts the whole subtest. |
| 11 | */ |
| 12 | |
| 13 | #pragma once |
| 14 | |
| 15 | #include <exception> |
| 16 | #include <iostream> |
| 17 | |
| 18 | inline namespace tap { |
| 19 | |
| 20 | struct failure : std::runtime_error { |
| 21 | failure(const std::string& what) : std::runtime_error(what) {} |
| 22 | }; |
| 23 | |
| 24 | template <typename F> |
| 25 | static void run(F test, const char *name) |
| 26 | { |
| 27 | bool ok = false; |
| 28 | try { |
| 29 | test(); |
| 30 | ok = true; |
| 31 | } catch (failure& e) { |
| 32 | std::cerr << "# fail: " << e.what() << "\n"; |
| 33 | } catch (const ot::status &rc) { |
| 34 | std::cerr << "# unexpected error: " << rc.message << "\n"; |
| 35 | } |
| 36 | std::cout << (ok ? "ok" : "not ok") << " - " << name << "\n"; |
| 37 | } |
| 38 | |
| 39 | void plan(int tests) |
| 40 | { |
| 41 | std::cout << "1.." << tests << "\n"; |
| 42 | } |
| 43 | |
| 44 | template <typename T, typename U> |
| 45 | void is(const T& got, const U& expected, const char* name) |
| 46 | { |
| 47 | if (got != expected) { |
| 48 | std::cerr << "# got: " << got << "\n" |
| 49 | "# expected: " << expected << "\n"; |
| 50 | throw failure(name); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | template <typename T, typename U> |
| 55 | void opaque_is(const T& got, const U& expected, const char* name) |
| 56 | { |
| 57 | if (got != expected) |
| 58 | throw failure(name); |
| 59 | } |
| 60 | |
| 61 | template <> |
| 62 | void is(const ot::status& got, const ot::st& expected, const char* name) |
| 63 | { |
| 64 | if (got.code != expected) { |
| 65 | if (got.code == ot::st::ok) |
| 66 | std::cerr << "# unexpected success\n"; |
| 67 | else |
| 68 | std::cerr << "# unexpected error: " << got.message << "\n"; |
| 69 | throw failure(name); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | } |