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