301-Gen-MapTypeConversion.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // 301-Gen-MapTypeConversion.cpp
  2. // Shows how to use map to modify generator's return type.
  3. // Specifically we wrap a std::string returning generator with a generator
  4. // that converts the strings using stoi, so the returned type is actually
  5. // an int.
  6. #include <catch2/catch_test_macros.hpp>
  7. #include <catch2/generators/catch_generators_adapters.hpp>
  8. #include <string>
  9. #include <sstream>
  10. namespace {
  11. // Returns a line from a stream. You could have it e.g. read lines from
  12. // a file, but to avoid problems with paths in examples, we will use
  13. // a fixed stringstream.
  14. class LineGenerator : public Catch::Generators::IGenerator<std::string> {
  15. std::string m_line;
  16. std::stringstream m_stream;
  17. public:
  18. LineGenerator() {
  19. m_stream.str("1\n2\n3\n4\n");
  20. if (!next()) {
  21. Catch::Generators::Detail::throw_generator_exception("Couldn't read a single line");
  22. }
  23. }
  24. std::string const& get() const override;
  25. bool next() override {
  26. return !!std::getline(m_stream, m_line);
  27. }
  28. };
  29. std::string const& LineGenerator::get() const {
  30. return m_line;
  31. }
  32. // This helper function provides a nicer UX when instantiating the generator
  33. // Notice that it returns an instance of GeneratorWrapper<std::string>, which
  34. // is a value-wrapper around std::unique_ptr<IGenerator<std::string>>.
  35. Catch::Generators::GeneratorWrapper<std::string> lines(std::string /* ignored for example */) {
  36. return Catch::Generators::GeneratorWrapper<std::string>(
  37. new LineGenerator()
  38. );
  39. }
  40. } // end anonymous namespace
  41. TEST_CASE("filter can convert types inside the generator expression", "[example][generator]") {
  42. auto num = GENERATE(map<int>([](std::string const& line) { return std::stoi(line); },
  43. lines("fake-file")));
  44. REQUIRE(num > 0);
  45. }
  46. // Compiling and running this file will result in 4 successful assertions