| 1 | // 300-Gen-OwnGenerator.cpp |
| 2 | // Shows how to define a custom generator. |
| 3 | |
| 4 | // Specifically we will implement a random number generator for integers |
| 5 | // It will have infinite capacity and settable lower/upper bound |
| 6 | |
| 7 | #include <catch2/catch_test_macros.hpp> |
| 8 | #include <catch2/generators/catch_generators.hpp> |
| 9 | #include <catch2/generators/catch_generators_adapters.hpp> |
| 10 | |
| 11 | #include <random> |
| 12 | |
| 13 | namespace { |
| 14 | |
| 15 | // This class shows how to implement a simple generator for Catch tests |
| 16 | class RandomIntGenerator : public Catch::Generators::IGenerator<int> { |
| 17 | std::minstd_rand m_rand; |
| 18 | std::uniform_int_distribution<> m_dist; |
| 19 | int current_number; |
| 20 | public: |
| 21 | |
| 22 | RandomIntGenerator(int low, int high): |
| 23 | m_rand(std::random_device{}()), |
| 24 | m_dist(low, high) |
| 25 | { |
| 26 | static_cast<void>(next()); |
| 27 | } |
| 28 | |
| 29 | int const& get() const override; |
| 30 | bool next() override { |
| 31 | current_number = m_dist(m_rand); |
| 32 | return true; |
| 33 | } |
| 34 | }; |
| 35 | |
| 36 | // Avoids -Wweak-vtables |
| 37 | int const& RandomIntGenerator::get() const { |
| 38 | return current_number; |
| 39 | } |
| 40 | |
| 41 | // This helper function provides a nicer UX when instantiating the generator |
| 42 | // Notice that it returns an instance of GeneratorWrapper<int>, which |
| 43 | // is a value-wrapper around std::unique_ptr<IGenerator<int>>. |
| 44 | Catch::Generators::GeneratorWrapper<int> random(int low, int high) { |
| 45 | return Catch::Generators::GeneratorWrapper<int>( |
| 46 | new RandomIntGenerator(low, high) |
| 47 | // Another possibility: |
| 48 | // Catch::Detail::make_unique<RandomIntGenerator>(low, high) |
| 49 | ); |
| 50 | } |
| 51 | |
| 52 | } // end anonymous namespaces |
| 53 | |
| 54 | // The two sections in this test case are equivalent, but the first one |
| 55 | // is much more readable/nicer to use |
| 56 | TEST_CASE("Generating random ints", "[example][generator]") { |
| 57 | SECTION("Nice UX") { |
| 58 | auto i = GENERATE(take(100, random(-100, 100))); |
| 59 | REQUIRE(i >= -100); |
| 60 | REQUIRE(i <= 100); |
| 61 | } |
| 62 | SECTION("Creating the random generator directly") { |
| 63 | auto i = GENERATE(take(100, GeneratorWrapper<int>(Catch::Detail::make_unique<RandomIntGenerator>(-100, 100)))); |
| 64 | REQUIRE(i >= -100); |
| 65 | REQUIRE(i <= 100); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | // Compiling and running this file will result in 400 successful assertions |