300-Gen-OwnGenerator.cpp 1.9 KB

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