• 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 
25     std::string const& get() const override;
26 
next()27     bool next() override {
28         return !!std::getline(m_stream, m_line);
29     }
30 };
31 
get() const32 std::string const& LineGenerator::get() const {
33     return m_line;
34 }
35 
36 // This helper function provides a nicer UX when instantiating the generator
37 // Notice that it returns an instance of GeneratorWrapper<std::string>, which
38 // is a value-wrapper around std::unique_ptr<IGenerator<std::string>>.
lines(std::string)39 Catch::Generators::GeneratorWrapper<std::string> lines(std::string /* ignored for example */) {
40     return Catch::Generators::GeneratorWrapper<std::string>(
41         std::unique_ptr<Catch::Generators::IGenerator<std::string>>(
42             new LineGenerator()
43         )
44     );
45 }
46 
47 
48 
49 TEST_CASE("filter can convert types inside the generator expression", "[example][generator]") {
__anon1e6a7fee0102(std::string const& line) 50     auto num = GENERATE(map<int>([](std::string const& line) { return std::stoi(line); },
51                                  lines("fake-file")));
52 
53     REQUIRE(num > 0);
54 }
55 
56 // Compiling and running this file will result in 4 successful assertions
57