Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git

check.h (8215B) · raw


      1 /// @file check.h
      2 /// @brief A minimal test framework: TEST cases, CHECK and CHECK_EQ.
      3 ///
      4 /// Each test file is a program of its own and includes this header exactly
      5 /// once. The header defines `main`, which runs every TEST of the file in the
      6 /// order they are written, so a test file looks like this:
      7 /// @code
      8 ///     #include "check.h"
      9 ///
     10 ///     TEST(addition) {
     11 ///       CHECK_EQ(1 + 1, 2);
     12 ///     }
     13 /// @endcode
     14 /// A failed check is recorded and the test case goes on, so one run shows every
     15 /// problem. The program exits with status 1 if any check failed.
     16 ///
     17 /// Every test case is listed with its result and its time as it finishes. The
     18 /// builder passes `--color` and `--live` when the output goes to a terminal;
     19 /// then the case that is running is shown on the last line, as `running`, and
     20 /// that line is rewritten when the case ends. A failed case is listed again at
     21 /// the end with the messages of its failed checks. `--quiet` lists nothing but
     22 /// the failures.
     23 #pragma once
     24 
     25 #include <algorithm>
     26 #include <chrono>
     27 #include <cstddef>
     28 #include <cstdio>
     29 #include <string>
     30 #include <type_traits>
     31 #include <vector>
     32 
     33 namespace kumo_test {
     34 
     35 /// @brief One test case: a name and the function that runs it.
     36 struct Case {
     37   const char* name;
     38   void (*run)();
     39 };
     40 
     41 /// @brief Every test case of the program, filled in before `main` starts.
     42 inline std::vector<Case>& cases() {
     43   static std::vector<Case> list;
     44   return list;
     45 }
     46 
     47 /// @brief The number of failed checks in the test case that is running.
     48 inline int& failed_checks() {
     49   static int count = 0;
     50   return count;
     51 }
     52 
     53 /// @brief The messages of the failed checks of the test case that is running,
     54 ///        kept to be printed under its name.
     55 inline std::string& failure_report() {
     56   static std::string text;
     57   return text;
     58 }
     59 
     60 /// @brief Records a failed check.
     61 inline void fail(const char* file, int line, const std::string& message) {
     62   failure_report() += "    " + std::string(file) + ":" + std::to_string(line) +
     63                       ": " + message + "\n";
     64   ++failed_checks();
     65 }
     66 
     67 /// @brief Adds a test case to cases() when a global of this type is created.
     68 struct Registrar {
     69   Registrar(const char* name, void (*run)()) { cases().push_back({name, run}); }
     70 };
     71 
     72 /// @brief Turns a value into text for a failure message.
     73 template <typename T>
     74 std::string show(const T& value) {
     75   if constexpr (std::is_arithmetic_v<T>) {
     76     return std::to_string(value);
     77   } else if constexpr (std::is_enum_v<T>) {
     78     return std::to_string(static_cast<long long>(value));
     79   } else {
     80     return "(value cannot be printed)";
     81   }
     82 }
     83 
     84 /// @brief Pads @p text with spaces on the right up to @p width characters.
     85 inline std::string pad(const std::string& text, size_t width) {
     86   return text.size() >= width ? text
     87                               : text + std::string(width - text.size(), ' ');
     88 }
     89 
     90 /// @brief Pads @p text with spaces on the left up to @p width characters.
     91 inline std::string pad_left(const std::string& text, size_t width) {
     92   return text.size() >= width ? text
     93                               : std::string(width - text.size(), ' ') + text;
     94 }
     95 
     96 /// @brief Formats the time a test case took: `<1 ms`, `12 ms`, `1.50 s`.
     97 inline std::string format_time(std::chrono::steady_clock::duration time) {
     98   const auto us =
     99       std::chrono::duration_cast<std::chrono::microseconds>(time).count();
    100   if (us < 1000) return "<1 ms";
    101   if (us < 1000000) return std::to_string(us / 1000) + " ms";
    102   char buffer[32];
    103   std::snprintf(buffer, sizeof(buffer), "%.2f s",
    104                 static_cast<double>(us) / 1e6);
    105   return buffer;
    106 }
    107 
    108 }  // namespace kumo_test
    109 
    110 /// @brief Defines a test case and registers it; the body follows the macro.
    111 #define TEST(name)                                                       \
    112   static void name();                                                    \
    113   static ::kumo_test::Registrar kumo_test_registrar_##name(#name, name); \
    114   static void name()
    115 
    116 /// @brief Records a failure, with the line, if @p condition is false.
    117 #define CHECK(condition)                                                     \
    118   do {                                                                       \
    119     if (!(condition)) {                                                      \
    120       ::kumo_test::fail(__FILE__, __LINE__, "CHECK(" #condition ") failed"); \
    121     }                                                                        \
    122   } while (0)
    123 
    124 /// @brief Records a failure, with both values, if @p actual != @p expected.
    125 ///
    126 /// Both arguments are evaluated once.
    127 #define CHECK_EQ(actual, expected)                                 \
    128   do {                                                             \
    129     const auto& kumo_test_actual = (actual);                       \
    130     const auto& kumo_test_expected = (expected);                   \
    131     if (!(kumo_test_actual == kumo_test_expected)) {               \
    132       ::kumo_test::fail(                                           \
    133           __FILE__, __LINE__,                                      \
    134           std::string("CHECK_EQ(") + #actual + ", " + #expected +  \
    135               ") failed: " + ::kumo_test::show(kumo_test_actual) + \
    136               " != " + ::kumo_test::show(kumo_test_expected));     \
    137     }                                                              \
    138   } while (0)
    139 
    140 /// @brief Runs every registered test case, listing each one as it goes.
    141 ///
    142 /// @param argc Argument count.
    143 /// @param argv `--color` colors the words `ok` and `FAIL`; `--live` shows the
    144 ///             running case on the last line and rewrites it when it ends;
    145 ///             `--quiet` lists only the failures.
    146 int main(int argc, char** argv) {
    147   bool color = false;
    148   bool live = false;
    149   bool quiet = false;
    150   for (int i = 1; i < argc; ++i) {
    151     const std::string arg = argv[i];
    152     if (arg == "--color") color = true;
    153     if (arg == "--live") live = true;
    154     if (arg == "-q" || arg == "--quiet") quiet = true;
    155   }
    156   const auto paint = [color](const char* code, const std::string& text) {
    157     return color ? std::string("\033[") + code + "m" + text + "\033[0m" : text;
    158   };
    159 
    160   // The names are padded to one width for every program, not to the longest of
    161   // each, so that the results line up from one program to the next. A longer
    162   // name only moves the column of its own program. A line is then 75 columns
    163   // wide, as wide as the rules the builder draws between the programs.
    164   constexpr size_t kNameWidth = 60;
    165   size_t width = kNameWidth;
    166   for (const kumo_test::Case& test : kumo_test::cases()) {
    167     width = std::max(width, std::string(test.name).size());
    168   }
    169 
    170   struct Failure {
    171     std::string name;
    172     std::string report;
    173   };
    174   std::vector<Failure> failures;
    175   for (const kumo_test::Case& test : kumo_test::cases()) {
    176     kumo_test::failed_checks() = 0;
    177     kumo_test::failure_report().clear();
    178 
    179     // The name goes out before the case runs, and is flushed, so that if the
    180     // case crashes the last line says which one it was.
    181     const std::string label = "  " + kumo_test::pad(test.name, width) + "  ";
    182     if (!quiet) {
    183       std::printf("%s%s", label.c_str(),
    184                   live ? paint("2", "running").c_str() : "");
    185       std::fflush(stdout);
    186     }
    187 
    188     const auto began = std::chrono::steady_clock::now();
    189     test.run();
    190     const std::string took =
    191         kumo_test::format_time(std::chrono::steady_clock::now() - began);
    192     const bool failed = kumo_test::failed_checks() != 0;
    193 
    194     if (!quiet) {
    195       // On a terminal, erase "running" and write the result in its place.
    196       if (live) std::printf("\r\033[2K%s", label.c_str());
    197       std::printf(
    198           "%s %s\n",
    199           failed ? paint("31", "FAIL").c_str() : paint("32", "ok  ").c_str(),
    200           paint("2", kumo_test::pad_left(took, 6)).c_str());
    201       std::fflush(stdout);
    202     }
    203     if (failed) failures.push_back({test.name, kumo_test::failure_report()});
    204   }
    205 
    206   // The messages come after the list, so that they do not break it up.
    207   if (!failures.empty() && !quiet) std::printf("\n");
    208   for (const Failure& failure : failures) {
    209     std::printf("  %s  %s\n%s", paint("31", "FAIL").c_str(),
    210                 failure.name.c_str(), failure.report.c_str());
    211   }
    212   return failures.empty() ? 0 : 1;
    213 }