|
| 1 | +/*******************************************************************\ |
| 2 | +
|
| 3 | +Module: Unit tests for range |
| 4 | +
|
| 5 | +Author: Romain Brenguier, [email protected] |
| 6 | +
|
| 7 | +\*******************************************************************/ |
| 8 | + |
| 9 | +#include <vector> |
| 10 | + |
| 11 | +#include <testing-utils/catch.hpp> |
| 12 | +#include <util/range.h> |
| 13 | + |
| 14 | +SCENARIO("range tests", "[core][util][range]") |
| 15 | +{ |
| 16 | + GIVEN("A vector with three strings") |
| 17 | + { |
| 18 | + std::vector<std::string> list; |
| 19 | + list.emplace_back("abc"); |
| 20 | + list.emplace_back("cdef"); |
| 21 | + list.emplace_back("acdef"); |
| 22 | + auto range = make_range(list); |
| 23 | + std::size_t total_length = 0; |
| 24 | + THEN("Use range-for to compute the total length") |
| 25 | + { |
| 26 | + for(const auto &s : range) |
| 27 | + total_length += s.length(); |
| 28 | + REQUIRE(total_length == 12); |
| 29 | + } |
| 30 | + THEN("Use map to compute individual lengths") |
| 31 | + { |
| 32 | + auto length_range = make_range(list).map<std::size_t>( |
| 33 | + [](const std::string &s) { return s.length(); }); |
| 34 | + auto it = length_range.begin(); |
| 35 | + REQUIRE(*it == 3); |
| 36 | + ++it; |
| 37 | + REQUIRE(*it == 4); |
| 38 | + ++it; |
| 39 | + REQUIRE(*it == 5); |
| 40 | + ++it; |
| 41 | + REQUIRE(it == length_range.end()); |
| 42 | + } |
| 43 | + THEN("Filter using lengths") |
| 44 | + { |
| 45 | + auto filtered_range = make_range(list).filter( |
| 46 | + [&](const std::string &s) { return s.length() == 4; }); |
| 47 | + auto it = filtered_range.begin(); |
| 48 | + REQUIRE(*it == "cdef"); |
| 49 | + ++it; |
| 50 | + REQUIRE(it == filtered_range.end()); |
| 51 | + } |
| 52 | + THEN("Filter, map and use range-for on the same list") |
| 53 | + { |
| 54 | + auto range = |
| 55 | + make_range(list) |
| 56 | + .filter([&](const std::string &s) -> bool { return s[0] == 'a'; }) |
| 57 | + .map<std::size_t>([&](const std::string &s) { return s.length(); }); |
| 58 | + // Note that everything is performed on the fly, so none of the filter |
| 59 | + // and map functions have been computed yet, and no intermediary container |
| 60 | + // is created. |
| 61 | + std::size_t total = 0; |
| 62 | + for(const auto &l : range) |
| 63 | + total += l; |
| 64 | + REQUIRE(total == 8); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments