Debian Codegraph @

3rdparty/catch2/examples/301-Gen-MapTypeConversion.cpp

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