Debian Codegraph @

src/external/catch2/tests/SelfTest/UsageTests/Generators.tests.cpp

raw
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 #include <catch2/catch_test_macros.hpp>
10 #include <catch2/generators/catch_generator_exception.hpp>
11 #include <catch2/generators/catch_generators_adapters.hpp>
12 #include <catch2/generators/catch_generators_random.hpp>
13 #include <catch2/generators/catch_generators_range.hpp>
14
15 #include <cstring>
16
17
18 // Generators and sections can be nested freely
19 TEST_CASE("Generators -- simple", "[generators]") {
20 auto i = GENERATE(1, 2, 3);
21 SECTION("one") {
22 auto j = GENERATE(values({ -3, -2, -1 }));
23 REQUIRE(j < i);
24 }
25
26 SECTION("two") {
27 // You can also explicitly set type for generators via Catch::Generators::as
28 auto str = GENERATE(as<std::string>{}, "a", "bb", "ccc");
29 REQUIRE(4u * i > str.size());
30 }
31 }
32
33 // You can create a cartesian-product of generators by creating multiple ones
34 TEST_CASE("3x3x3 ints", "[generators]") {
35 auto x = GENERATE(1, 2, 3);
36 auto y = GENERATE(4, 5, 6);
37 auto z = GENERATE(7, 8, 9);
38 // These assertions will be run 27 times (3x3x3)
39 CHECK(x < y);
40 CHECK(y < z);
41 REQUIRE(x < z);
42 }
43
44 // You can also create data tuples
45 TEST_CASE("tables", "[generators]") {
46 // Note that this will not compile with libstdc++ older than libstdc++6
47 // See https://stackoverflow.com/questions/12436586/tuple-vector-and-initializer-list
48 // for possible workarounds
49 // auto data = GENERATE(table<char const*, int>({
50 // {"first", 5},
51 // {"second", 6},
52 // {"third", 5},
53 // {"etc...", 6}
54 // }));
55
56 // Workaround for the libstdc++ bug mentioned above
57 using tuple_type = std::tuple<char const*, int>;
58 auto data = GENERATE(table<char const*, int>({
59 tuple_type{"first", 5},
60 tuple_type{"second", 6},
61 tuple_type{"third", 5},
62 tuple_type{"etc...", 6}
63 }));
64
65 REQUIRE(strlen(std::get<0>(data)) == static_cast<size_t>(std::get<1>(data)));
66 }
67
68
69 #ifdef __cpp_structured_bindings
70
71 // Structured bindings make the table utility much nicer to use
72 TEST_CASE( "strlen2", "[approvals][generators]" ) {
73 using tuple_type = std::tuple<std::string, int>; // see above workaround
74 auto [test_input, expected] =
75 GENERATE( table<std::string, size_t>( { tuple_type{ "one", 3 },
76 tuple_type{ "two", 3 },
77 tuple_type{ "three", 5 },
78 tuple_type{ "four", 4 } } ) );
79
80 REQUIRE( test_input.size() == expected );
81 }
82 #endif
83
84
85 // An alternate way of doing data tables without structured bindings
86 struct Data { std::string str; size_t len; };
87
88 TEST_CASE( "strlen3", "[generators]" ) {
89 auto data = GENERATE( values<Data>({
90 {"one", 3},
91 {"two", 3},
92 {"three", 5},
93 {"four", 4}
94 }));
95
96 REQUIRE( data.str.size() == data.len );
97 }
98
99
100
101 #ifdef __cpp_structured_bindings
102
103 // Based on example from https://docs.cucumber.io/gherkin/reference/#scenario-outline
104 // (thanks to https://github.com/catchorg/Catch2/issues/850#issuecomment-399504851)
105
106 // Note that GIVEN, WHEN, and THEN now forward onto DYNAMIC_SECTION instead of SECTION.
107 // DYNAMIC_SECTION takes its name as a stringstream-style expression, so can be formatted using
108 // variables in scope - such as the generated variables here. This reads quite nicely in the
109 // test name output (the full scenario description).
110
111 static auto eatCucumbers( int start, int eat ) -> int { return start-eat; }
112
113 SCENARIO("Eating cucumbers", "[generators][approvals]") {
114 using tuple_type = std::tuple<int, int, int>;
115 auto [start, eat, left] = GENERATE( table<int, int, int>(
116 { tuple_type{ 12, 5, 7 }, tuple_type{ 20, 5, 15 } } ) );
117
118 GIVEN( "there are " << start << " cucumbers" )
119 WHEN( "I eat " << eat << " cucumbers" )
120 THEN( "I should have " << left << " cucumbers" ) {
121 REQUIRE( eatCucumbers( start, eat ) == left );
122 }
123 }
124 #endif
125
126 // There are also some generic generator manipulators
127 TEST_CASE("Generators -- adapters", "[generators][generic]") {
128 // TODO: This won't work yet, introduce GENERATE_VAR?
129 //auto numbers = Catch::Generators::values({ 1, 2, 3, 4, 5, 6 });
130 SECTION("Filtering by predicate") {
131 SECTION("Basic usage") {
132 // This filters out all odd (false) numbers, giving [2, 4, 6]
133 auto i = GENERATE(filter([] (int val) { return val % 2 == 0; }, values({ 1, 2, 3, 4, 5, 6 })));
134 REQUIRE(i % 2 == 0);
135 }
136 SECTION("Throws if there are no matching values") {
137 using namespace Catch::Generators;
138 REQUIRE_THROWS_AS(filter([] (int) {return false; }, value(1)), Catch::GeneratorException);
139 }
140 }
141 SECTION("Shortening a range") {
142 // This takes the first 3 elements from the values, giving back [1, 2, 3]
143 auto i = GENERATE(take(3, values({ 1, 2, 3, 4, 5, 6 })));
144 REQUIRE(i < 4);
145 }
146 SECTION("Transforming elements") {
147 SECTION("Same type") {
148 // This doubles values [1, 2, 3] into [2, 4, 6]
149 auto i = GENERATE(map([] (int val) { return val * 2; }, values({ 1, 2, 3 })));
150 REQUIRE(i % 2 == 0);
151 }
152 SECTION("Different type") {
153 // This takes a generator that returns ints and maps them into strings
154 auto i = GENERATE(map<std::string>([] (int val) { return std::to_string(val); }, values({ 1, 2, 3 })));
155 REQUIRE(i.size() == 1);
156 }
157 SECTION("Different deduced type") {
158 // This takes a generator that returns ints and maps them into strings
159 auto i = GENERATE(map([] (int val) { return std::to_string(val); }, values({ 1, 2, 3 })));
160 REQUIRE(i.size() == 1);
161 }
162 }
163 SECTION("Repeating a generator") {
164 // This will return values [1, 2, 3, 1, 2, 3]
165 auto j = GENERATE(repeat(2, values({ 1, 2, 3 })));
166 REQUIRE(j > 0);
167 }
168 SECTION("Chunking a generator into sized pieces") {
169 SECTION("Number of elements in source is divisible by chunk size") {
170 auto chunk2 = GENERATE(chunk(2, values({ 1, 1, 2, 2, 3, 3 })));
171 REQUIRE(chunk2.size() == 2);
172 REQUIRE(chunk2.front() == chunk2.back());
173 }
174 SECTION("Number of elements in source is not divisible by chunk size") {
175 auto chunk2 = GENERATE(chunk(2, values({ 1, 1, 2, 2, 3 })));
176 REQUIRE(chunk2.size() == 2);
177 REQUIRE(chunk2.front() == chunk2.back());
178 REQUIRE(chunk2.front() < 3);
179 }
180 SECTION("Chunk size of zero") {
181 auto chunk2 = GENERATE(take(3, chunk(0, value(1))));
182 REQUIRE(chunk2.size() == 0);
183 }
184 SECTION("Throws on too small generators") {
185 using namespace Catch::Generators;
186 REQUIRE_THROWS_AS(chunk(2, value(1)), Catch::GeneratorException);
187 }
188 }
189 }
190
191 // Note that because of the non-reproducibility of distributions,
192 // anything involving the random generators cannot be part of approvals
193 TEST_CASE("Random generator", "[generators][approvals]") {
194 SECTION("Infer int from integral arguments") {
195 auto val = GENERATE(take(4, random(0, 1)));
196 STATIC_REQUIRE(std::is_same<decltype(val), int>::value);
197 REQUIRE(0 <= val);
198 REQUIRE(val <= 1);
199 }
200 SECTION("Infer double from double arguments") {
201 auto val = GENERATE(take(4, random(0., 1.)));
202 STATIC_REQUIRE(std::is_same<decltype(val), double>::value);
203 REQUIRE(0. <= val);
204 REQUIRE(val < 1);
205 }
206 }
207
208
209 TEST_CASE("Nested generators and captured variables", "[generators]") {
210 // Workaround for old libstdc++
211 using record = std::tuple<int, int>;
212 // Set up 3 ranges to generate numbers from
213 auto extent = GENERATE(table<int, int>({
214 record{3, 7},
215 record{-5, -3},
216 record{90, 100}
217 }));
218
219 auto from = std::get<0>(extent);
220 auto to = std::get<1>(extent);
221
222 auto values = GENERATE_COPY(range(from, to));
223 REQUIRE(values > -6);
224 }
225
226 namespace {
227 size_t call_count = 0;
228 size_t test_count = 0;
229 std::vector<int> make_data() {
230 return { 1, 3, 5, 7, 9, 11 };
231 }
232 std::vector<int> make_data_counted() {
233 ++call_count;
234 return make_data();
235 }
236 }
237
238 #if defined(__clang__)
239 #pragma clang diagnostic push
240 #pragma clang diagnostic ignored "-Wexit-time-destructors"
241 #endif
242
243 TEST_CASE("Copy and then generate a range", "[generators]") {
244 SECTION("from var and iterators") {
245 static auto data = make_data();
246
247 // It is important to notice that a generator is only initialized
248 // **once** per run. What this means is that modifying data will not
249 // modify the underlying generator.
250 auto elem = GENERATE_REF(from_range(data.begin(), data.end()));
251 REQUIRE(elem % 2 == 1);
252 }
253 SECTION("From a temporary container") {
254 auto elem = GENERATE(from_range(make_data_counted()));
255 ++test_count;
256 REQUIRE(elem % 2 == 1);
257 }
258 SECTION("Final validation") {
259 REQUIRE(call_count == 1);
260 REQUIRE(make_data().size() == test_count);
261 }
262 }
263
264 #if defined( __clang__ )
265 # pragma clang diagnostic pop
266 #endif
267
268 TEST_CASE("#1913 - GENERATE inside a for loop should not keep recreating the generator", "[regression][generators]") {
269 static int counter = 0;
270 for (int i = 0; i < 3; ++i) {
271 int _ = GENERATE(1, 2);
272 (void)_;
273 ++counter;
274 }
275 // There should be at most 6 (3 * 2) counter increments
276 REQUIRE(counter < 7);
277 }
278
279 TEST_CASE("#1913 - GENERATEs can share a line", "[regression][generators]") {
280 int i = GENERATE(1, 2); int j = GENERATE(3, 4);
281 REQUIRE(i != j);
282 }
283
284 namespace {
285 class test_generator : public Catch::Generators::IGenerator<int> {
286 public:
287 [[noreturn]] explicit test_generator() {
288 // removing the following line will cause the program to terminate
289 // gracefully.
290 throw Catch::GeneratorException( "failure to init" );
291 }
292
293 auto get() const -> int const& override {
294 static constexpr int value = 1;
295 return value;
296 }
297
298 auto next() -> bool override { return false; }
299 };
300
301 static auto make_test_generator()
302 -> Catch::Generators::GeneratorWrapper<int> {
303 return { new test_generator() };
304 }
305
306 } // namespace
307
308 TEST_CASE( "#2615 - Throwing in constructor generator fails test case but does not abort",
309 "[!shouldfail][regression][generators]" ) {
310 // this should fail the test case, but not abort the application
311 auto sample = GENERATE( make_test_generator() );
312 // this assertion shouldn't trigger
313 REQUIRE( sample == 0 );
314 }
315
316 TEST_CASE( "GENERATE can combine literals and generators", "[generators]" ) {
317 auto i = GENERATE( 2,
318 4,
319 take( 2,
320 filter( []( int val ) { return val % 2 == 0; },
321 random( -100, 100 ) ) ) );
322 REQUIRE( i % 2 == 0 );
323 }