File: 301-Gen-MapTypeConversion.cpp

package info (click to toggle)
log4cplus 2.0.8-1.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,592 kB
  • sloc: cpp: 53,091; sh: 10,537; ansic: 1,845; python: 1,226; perl: 263; makefile: 209; xml: 85; objc: 59
file content (58 lines) | stat: -rw-r--r-- 1,887 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// 301-Gen-MapTypeConversion.cpp
// Shows how to use map to modify generator's return type.

// Specifically we wrap a std::string returning generator with a generator
// that converts the strings using stoi, so the returned type is actually
// an int.

#include <catch2/catch.hpp>

#include <string>
#include <sstream>

// Returns a line from a stream. You could have it e.g. read lines from
// a file, but to avoid problems with paths in examples, we will use
// a fixed stringstream.
class LineGenerator : public Catch::Generators::IGenerator<std::string> {
    std::string m_line;
    std::stringstream m_stream;
public:
    LineGenerator() {
        m_stream.str("1\n2\n3\n4\n");
        if (!next()) {
            throw Catch::GeneratorException("Couldn't read a single line");
        }
    }

    std::string const& get() const override;
    
    bool next() override {
        return !!std::getline(m_stream, m_line);
    }
};

std::string const& LineGenerator::get() const {
    return m_line;
}

// This helper function provides a nicer UX when instantiating the generator
// Notice that it returns an instance of GeneratorWrapper<std::string>, which
// is a value-wrapper around std::unique_ptr<IGenerator<std::string>>.
Catch::Generators::GeneratorWrapper<std::string> lines(std::string /* ignored for example */) {
    return Catch::Generators::GeneratorWrapper<std::string>(
        std::unique_ptr<Catch::Generators::IGenerator<std::string>>(
            new LineGenerator()
        )
    );
}



TEST_CASE("filter can convert types inside the generator expression", "[example][generator]") {
    auto num = GENERATE(map<int>([](std::string const& line) { return std::stoi(line); },
                                 lines("fake-file")));
                                 
    REQUIRE(num > 0);
}

// Compiling and running this file will result in 4 successful assertions