• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // 301-Gen-MapTypeConversion.cpp
2 // Shows how to use map to modify generator's return type.
3 
4 // TODO
5 
6 #include <catch2/catch.hpp>
7 
8 #include <string>
9 #include <sstream>
10 
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:
LineGenerator()18     LineGenerator() {
19         m_stream.str("1\n2\n3\n4\n");
20         if (!next()) {
21             throw Catch::GeneratorException("Couldn't read a single line");
22         }
23     }
24 
get() const25     std::string const& get() const override {
26         return m_line;
27     }
28 
next()29     bool next() override {
30         return !!std::getline(m_stream, m_line);
31     }
32 };
33 
34 // This helper function provides a nicer UX when instantiating the generator
35 // Notice that it returns an instance of GeneratorWrapper<std::string>, which
36 // is a value-wrapper around std::unique_ptr<IGenerator<std::string>>.
lines(std::string)37 Catch::Generators::GeneratorWrapper<std::string> lines(std::string /* ignored for example */) {
38     return Catch::Generators::GeneratorWrapper<std::string>(
39         std::unique_ptr<Catch::Generators::IGenerator<std::string>>(
40             new LineGenerator()
41         )
42     );
43 }
44 
45 
46 
47 TEST_CASE("filter can convert types inside the generator expression", "[example][generator]") {
__anonf1d2ebcb0102(std::string const& line) 48     auto num = GENERATE(map<int>([](std::string const& line) { return std::stoi(line); },
49                                  lines("fake-file")));
50 
51     REQUIRE(num > 0);
52 }
53 
54 // Compiling and running this file will result in 4 successful assertions
55