Skip to content

Commit 6d6e575

Browse files
Unit tests for range
This gives examples of how to use the class.
1 parent b3b1036 commit 6d6e575

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

unit/Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ SRC += analyses/ai/ai.cpp \
4242
util/message.cpp \
4343
util/optional.cpp \
4444
util/pointer_offset_size.cpp \
45+
util/range.cpp \
4546
util/replace_symbol.cpp \
4647
util/sharing_map.cpp \
4748
util/sharing_node.cpp \

unit/util/range.cpp

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*******************************************************************\
2+
3+
Module: Unit tests for range
4+
5+
Author: Romain Brenguier, romain.brenguier@diffblue.com
6+
7+
\*******************************************************************/
8+
9+
#include <vector>
10+
11+
#include <util/range.h>
12+
#include "../testing-utils/catch.hpp"
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)
33+
.map<std::size_t>([](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)
46+
.filter([&](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 = make_range(list)
55+
.filter([&](const std::string &s) -> bool { return s[0] == 'a';})
56+
.map<std::size_t>([&](const std::string &s) { return s.length(); });
57+
// Note that everything is performed on the fly, so none of the filter
58+
// and map functions have been computed yet, and no intermediary container
59+
// is created.
60+
std::size_t total = 0;
61+
for(const auto &l : range)
62+
total += l;
63+
REQUIRE(total == 8);
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)