301-Gen-MapTypeConversion.cpp 1.8 KB

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