blob: 5dc951d2bca87b3ff4078d3ce14b6b8c22aab3fe [file] [log] [blame]
Eric Fiselier622fc112018-11-15 19:22:53 +00001#include <cstdio>
Eric Fiselierffc31db2018-07-10 04:02:00 +00002#include <cstring>
Eric Fiselier622fc112018-11-15 19:22:53 +00003#include <fstream>
Eric Fiselierf76a0872016-08-29 19:12:01 +00004#include <iostream>
Eric Fiselierd87eb992016-11-05 00:30:27 +00005#include <map>
6#include <memory>
Eric Fiselier114125f2018-12-14 03:37:13 +00007#include <random>
Eric Fiselierf76a0872016-08-29 19:12:01 +00008#include <sstream>
Eric Fiselier622fc112018-11-15 19:22:53 +00009#include <streambuf>
Eric Fiselierf76a0872016-08-29 19:12:01 +000010
Eric Fiselierffc31db2018-07-10 04:02:00 +000011#include "../src/benchmark_api_internal.h"
Eric Fiselierd87eb992016-11-05 00:30:27 +000012#include "../src/check.h" // NOTE: check.h is for internal use only!
13#include "../src/re.h" // NOTE: re.h is for internal use only
14#include "output_test.h"
Eric Fiselierf76a0872016-08-29 19:12:01 +000015
16// ========================================================================= //
17// ------------------------------ Internals -------------------------------- //
18// ========================================================================= //
Eric Fiselierd87eb992016-11-05 00:30:27 +000019namespace internal {
20namespace {
Eric Fiselierf76a0872016-08-29 19:12:01 +000021
22using TestCaseList = std::vector<TestCase>;
23
24// Use a vector because the order elements are added matters during iteration.
25// std::map/unordered_map don't guarantee that.
26// For example:
27// SetSubstitutions({{"%HelloWorld", "Hello"}, {"%Hello", "Hi"}});
28// Substitute("%HelloWorld") // Always expands to Hello.
29using SubMap = std::vector<std::pair<std::string, std::string>>;
30
31TestCaseList& GetTestCaseList(TestCaseID ID) {
Eric Fiselierd87eb992016-11-05 00:30:27 +000032 // Uses function-local statics to ensure initialization occurs
33 // before first use.
34 static TestCaseList lists[TC_NumID];
35 return lists[ID];
Eric Fiselierf76a0872016-08-29 19:12:01 +000036}
37
38SubMap& GetSubstitutions() {
Eric Fiselierd87eb992016-11-05 00:30:27 +000039 // Don't use 'dec_re' from header because it may not yet be initialized.
Eric Fiselierffc31db2018-07-10 04:02:00 +000040 // clang-format off
Eric Fiselier688edc72017-04-18 07:17:20 +000041 static std::string safe_dec_re = "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?";
Eric Fiselierea9230c2018-12-14 03:48:09 +000042 static std::string time_re = "([0-9]+[.])?[0-9]+";
Eric Fiselierd87eb992016-11-05 00:30:27 +000043 static SubMap map = {
44 {"%float", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"},
Eric Fiselierfd2e3e92018-01-18 04:23:01 +000045 // human-readable float
46 {"%hrfloat", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?[kMGTPEZYmunpfazy]?"},
Eric Fiselierd87eb992016-11-05 00:30:27 +000047 {"%int", "[ ]*[0-9]+"},
48 {" %s ", "[ ]+"},
Eric Fiselierea9230c2018-12-14 03:48:09 +000049 {"%time", "[ ]*" + time_re + "[ ]+ns"},
50 {"%console_report", "[ ]*" + time_re + "[ ]+ns [ ]*" + time_re + "[ ]+ns [ ]*[0-9]+"},
51 {"%console_time_only_report", "[ ]*" + time_re + "[ ]+ns [ ]*" + time_re + "[ ]+ns"},
52 {"%console_us_report", "[ ]*" + time_re + "[ ]+us [ ]*" + time_re + "[ ]+us [ ]*[0-9]+"},
53 {"%console_us_time_only_report", "[ ]*" + time_re + "[ ]+us [ ]*" + time_re + "[ ]+us"},
Eric Fiselierfd2e3e92018-01-18 04:23:01 +000054 {"%csv_header",
55 "name,iterations,real_time,cpu_time,time_unit,bytes_per_second,"
56 "items_per_second,label,error_occurred,error_message"},
Eric Fiselier688edc72017-04-18 07:17:20 +000057 {"%csv_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,,,,,"},
58 {"%csv_us_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",us,,,,,"},
Eric Fiselierd87eb992016-11-05 00:30:27 +000059 {"%csv_bytes_report",
Eric Fiselier688edc72017-04-18 07:17:20 +000060 "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns," + safe_dec_re + ",,,,"},
Eric Fiselierd87eb992016-11-05 00:30:27 +000061 {"%csv_items_report",
Eric Fiselier688edc72017-04-18 07:17:20 +000062 "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,," + safe_dec_re + ",,,"},
Eric Fiselierfd2e3e92018-01-18 04:23:01 +000063 {"%csv_bytes_items_report",
64 "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns," + safe_dec_re +
65 "," + safe_dec_re + ",,,"},
Eric Fiselier688edc72017-04-18 07:17:20 +000066 {"%csv_label_report_begin", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,,,"},
Eric Fiselierd87eb992016-11-05 00:30:27 +000067 {"%csv_label_report_end", ",,"}};
Eric Fiselierffc31db2018-07-10 04:02:00 +000068 // clang-format on
Eric Fiselierd87eb992016-11-05 00:30:27 +000069 return map;
Eric Fiselierf76a0872016-08-29 19:12:01 +000070}
71
72std::string PerformSubstitutions(std::string source) {
Eric Fiselierd87eb992016-11-05 00:30:27 +000073 SubMap const& subs = GetSubstitutions();
74 using SizeT = std::string::size_type;
75 for (auto const& KV : subs) {
76 SizeT pos;
77 SizeT next_start = 0;
78 while ((pos = source.find(KV.first, next_start)) != std::string::npos) {
79 next_start = pos + KV.second.size();
80 source.replace(pos, KV.first.size(), KV.second);
Eric Fiselierf76a0872016-08-29 19:12:01 +000081 }
Eric Fiselierd87eb992016-11-05 00:30:27 +000082 }
83 return source;
Eric Fiselierf76a0872016-08-29 19:12:01 +000084}
85
86void CheckCase(std::stringstream& remaining_output, TestCase const& TC,
Eric Fiselierd87eb992016-11-05 00:30:27 +000087 TestCaseList const& not_checks) {
88 std::string first_line;
89 bool on_first = true;
90 std::string line;
91 while (remaining_output.eof() == false) {
92 CHECK(remaining_output.good());
93 std::getline(remaining_output, line);
94 if (on_first) {
95 first_line = line;
96 on_first = false;
Eric Fiselierf76a0872016-08-29 19:12:01 +000097 }
Eric Fiselierd87eb992016-11-05 00:30:27 +000098 for (const auto& NC : not_checks) {
99 CHECK(!NC.regex->Match(line))
100 << "Unexpected match for line \"" << line << "\" for MR_Not regex \""
101 << NC.regex_str << "\""
102 << "\n actual regex string \"" << TC.substituted_regex << "\""
103 << "\n started matching near: " << first_line;
104 }
105 if (TC.regex->Match(line)) return;
106 CHECK(TC.match_rule != MR_Next)
107 << "Expected line \"" << line << "\" to match regex \"" << TC.regex_str
108 << "\""
Eric Fiselierf76a0872016-08-29 19:12:01 +0000109 << "\n actual regex string \"" << TC.substituted_regex << "\""
110 << "\n started matching near: " << first_line;
Eric Fiselierd87eb992016-11-05 00:30:27 +0000111 }
112 CHECK(remaining_output.eof() == false)
113 << "End of output reached before match for regex \"" << TC.regex_str
114 << "\" was found"
115 << "\n actual regex string \"" << TC.substituted_regex << "\""
116 << "\n started matching near: " << first_line;
Eric Fiselierf76a0872016-08-29 19:12:01 +0000117}
118
Eric Fiselierf76a0872016-08-29 19:12:01 +0000119void CheckCases(TestCaseList const& checks, std::stringstream& output) {
Eric Fiselierd87eb992016-11-05 00:30:27 +0000120 std::vector<TestCase> not_checks;
121 for (size_t i = 0; i < checks.size(); ++i) {
122 const auto& TC = checks[i];
123 if (TC.match_rule == MR_Not) {
124 not_checks.push_back(TC);
125 continue;
Eric Fiselierf76a0872016-08-29 19:12:01 +0000126 }
Eric Fiselierd87eb992016-11-05 00:30:27 +0000127 CheckCase(output, TC, not_checks);
128 not_checks.clear();
129 }
Eric Fiselierf76a0872016-08-29 19:12:01 +0000130}
131
132class TestReporter : public benchmark::BenchmarkReporter {
Eric Fiselierd87eb992016-11-05 00:30:27 +0000133 public:
Eric Fiselierf76a0872016-08-29 19:12:01 +0000134 TestReporter(std::vector<benchmark::BenchmarkReporter*> reps)
Eric Fiselierd87eb992016-11-05 00:30:27 +0000135 : reporters_(reps) {}
Eric Fiselierf76a0872016-08-29 19:12:01 +0000136
137 virtual bool ReportContext(const Context& context) {
138 bool last_ret = false;
139 bool first = true;
140 for (auto rep : reporters_) {
141 bool new_ret = rep->ReportContext(context);
142 CHECK(first || new_ret == last_ret)
143 << "Reports return different values for ReportContext";
144 first = false;
145 last_ret = new_ret;
146 }
Eric Fiselierd87eb992016-11-05 00:30:27 +0000147 (void)first;
Eric Fiselierf76a0872016-08-29 19:12:01 +0000148 return last_ret;
149 }
150
Eric Fiselierd87eb992016-11-05 00:30:27 +0000151 void ReportRuns(const std::vector<Run>& report) {
152 for (auto rep : reporters_) rep->ReportRuns(report);
153 }
154 void Finalize() {
155 for (auto rep : reporters_) rep->Finalize();
156 }
Eric Fiselierf76a0872016-08-29 19:12:01 +0000157
Eric Fiselierd87eb992016-11-05 00:30:27 +0000158 private:
Eric Fiselierffc31db2018-07-10 04:02:00 +0000159 std::vector<benchmark::BenchmarkReporter*> reporters_;
Eric Fiselierf76a0872016-08-29 19:12:01 +0000160};
Eric Fiselierffc31db2018-07-10 04:02:00 +0000161} // namespace
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000162
Eric Fiselierd87eb992016-11-05 00:30:27 +0000163} // end namespace internal
Eric Fiselierf76a0872016-08-29 19:12:01 +0000164
165// ========================================================================= //
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000166// -------------------------- Results checking ----------------------------- //
167// ========================================================================= //
168
169namespace internal {
170
171// Utility class to manage subscribers for checking benchmark results.
172// It works by parsing the CSV output to read the results.
173class ResultsChecker {
174 public:
Eric Fiselierffc31db2018-07-10 04:02:00 +0000175 struct PatternAndFn : public TestCase { // reusing TestCase for its regexes
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000176 PatternAndFn(const std::string& rx, ResultsCheckFn fn_)
Eric Fiselierffc31db2018-07-10 04:02:00 +0000177 : TestCase(rx), fn(fn_) {}
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000178 ResultsCheckFn fn;
179 };
180
Eric Fiselierffc31db2018-07-10 04:02:00 +0000181 std::vector<PatternAndFn> check_patterns;
182 std::vector<Results> results;
183 std::vector<std::string> field_names;
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000184
185 void Add(const std::string& entry_pattern, ResultsCheckFn fn);
186
187 void CheckResults(std::stringstream& output);
188
189 private:
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000190 void SetHeader_(const std::string& csv_header);
191 void SetValues_(const std::string& entry_csv_line);
192
Eric Fiselierffc31db2018-07-10 04:02:00 +0000193 std::vector<std::string> SplitCsv_(const std::string& line);
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000194};
195
196// store the static ResultsChecker in a function to prevent initialization
197// order problems
198ResultsChecker& GetResultsChecker() {
199 static ResultsChecker rc;
200 return rc;
201}
202
203// add a results checker for a benchmark
204void ResultsChecker::Add(const std::string& entry_pattern, ResultsCheckFn fn) {
205 check_patterns.emplace_back(entry_pattern, fn);
206}
207
208// check the results of all subscribed benchmarks
209void ResultsChecker::CheckResults(std::stringstream& output) {
210 // first reset the stream to the start
211 {
Eric Fiselier114125f2018-12-14 03:37:13 +0000212 auto start = std::stringstream::pos_type(0);
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000213 // clear before calling tellg()
214 output.clear();
215 // seek to zero only when needed
Eric Fiselierffc31db2018-07-10 04:02:00 +0000216 if (output.tellg() > start) output.seekg(start);
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000217 // and just in case
218 output.clear();
219 }
220 // now go over every line and publish it to the ResultsChecker
221 std::string line;
222 bool on_first = true;
223 while (output.eof() == false) {
224 CHECK(output.good());
225 std::getline(output, line);
226 if (on_first) {
Eric Fiselierffc31db2018-07-10 04:02:00 +0000227 SetHeader_(line); // this is important
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000228 on_first = false;
229 continue;
230 }
231 SetValues_(line);
232 }
233 // finally we can call the subscribed check functions
Eric Fiselierffc31db2018-07-10 04:02:00 +0000234 for (const auto& p : check_patterns) {
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000235 VLOG(2) << "--------------------------------\n";
236 VLOG(2) << "checking for benchmarks matching " << p.regex_str << "...\n";
Eric Fiselierffc31db2018-07-10 04:02:00 +0000237 for (const auto& r : results) {
238 if (!p.regex->Match(r.name)) {
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000239 VLOG(2) << p.regex_str << " is not matched by " << r.name << "\n";
240 continue;
241 } else {
242 VLOG(2) << p.regex_str << " is matched by " << r.name << "\n";
243 }
244 VLOG(1) << "Checking results of " << r.name << ": ... \n";
245 p.fn(r);
246 VLOG(1) << "Checking results of " << r.name << ": OK.\n";
247 }
248 }
249}
250
251// prepare for the names in this header
252void ResultsChecker::SetHeader_(const std::string& csv_header) {
253 field_names = SplitCsv_(csv_header);
254}
255
256// set the values for a benchmark
257void ResultsChecker::SetValues_(const std::string& entry_csv_line) {
Eric Fiselierffc31db2018-07-10 04:02:00 +0000258 if (entry_csv_line.empty()) return; // some lines are empty
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000259 CHECK(!field_names.empty());
260 auto vals = SplitCsv_(entry_csv_line);
261 CHECK_EQ(vals.size(), field_names.size());
Eric Fiselierffc31db2018-07-10 04:02:00 +0000262 results.emplace_back(vals[0]); // vals[0] is the benchmark name
263 auto& entry = results.back();
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000264 for (size_t i = 1, e = vals.size(); i < e; ++i) {
265 entry.values[field_names[i]] = vals[i];
266 }
267}
268
269// a quick'n'dirty csv splitter (eliminating quotes)
Eric Fiselierffc31db2018-07-10 04:02:00 +0000270std::vector<std::string> ResultsChecker::SplitCsv_(const std::string& line) {
271 std::vector<std::string> out;
272 if (line.empty()) return out;
273 if (!field_names.empty()) out.reserve(field_names.size());
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000274 size_t prev = 0, pos = line.find_first_of(','), curr = pos;
Eric Fiselierffc31db2018-07-10 04:02:00 +0000275 while (pos != line.npos) {
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000276 CHECK(curr > 0);
Eric Fiselierffc31db2018-07-10 04:02:00 +0000277 if (line[prev] == '"') ++prev;
278 if (line[curr - 1] == '"') --curr;
279 out.push_back(line.substr(prev, curr - prev));
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000280 prev = pos + 1;
281 pos = line.find_first_of(',', pos + 1);
282 curr = pos;
283 }
284 curr = line.size();
Eric Fiselierffc31db2018-07-10 04:02:00 +0000285 if (line[prev] == '"') ++prev;
286 if (line[curr - 1] == '"') --curr;
287 out.push_back(line.substr(prev, curr - prev));
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000288 return out;
289}
290
291} // end namespace internal
292
Eric Fiselierffc31db2018-07-10 04:02:00 +0000293size_t AddChecker(const char* bm_name, ResultsCheckFn fn) {
294 auto& rc = internal::GetResultsChecker();
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000295 rc.Add(bm_name, fn);
296 return rc.results.size();
297}
298
299int Results::NumThreads() const {
300 auto pos = name.find("/threads:");
Eric Fiselierffc31db2018-07-10 04:02:00 +0000301 if (pos == name.npos) return 1;
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000302 auto end = name.find('/', pos + 9);
303 std::stringstream ss;
304 ss << name.substr(pos + 9, end);
305 int num = 1;
306 ss >> num;
307 CHECK(!ss.fail());
308 return num;
309}
310
Eric Fiselierffc31db2018-07-10 04:02:00 +0000311double Results::NumIterations() const {
312 return GetAs<double>("iterations");
313}
314
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000315double Results::GetTime(BenchmarkTime which) const {
316 CHECK(which == kCpuTime || which == kRealTime);
Eric Fiselierffc31db2018-07-10 04:02:00 +0000317 const char* which_str = which == kCpuTime ? "cpu_time" : "real_time";
318 double val = GetAs<double>(which_str);
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000319 auto unit = Get("time_unit");
320 CHECK(unit);
Eric Fiselierffc31db2018-07-10 04:02:00 +0000321 if (*unit == "ns") {
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000322 return val * 1.e-9;
Eric Fiselierffc31db2018-07-10 04:02:00 +0000323 } else if (*unit == "us") {
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000324 return val * 1.e-6;
Eric Fiselierffc31db2018-07-10 04:02:00 +0000325 } else if (*unit == "ms") {
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000326 return val * 1.e-3;
Eric Fiselierffc31db2018-07-10 04:02:00 +0000327 } else if (*unit == "s") {
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000328 return val;
329 } else {
330 CHECK(1 == 0) << "unknown time unit: " << *unit;
331 return 0;
332 }
333}
334
335// ========================================================================= //
Eric Fiselierf76a0872016-08-29 19:12:01 +0000336// -------------------------- Public API Definitions------------------------ //
337// ========================================================================= //
338
339TestCase::TestCase(std::string re, int rule)
Eric Fiselierd87eb992016-11-05 00:30:27 +0000340 : regex_str(std::move(re)),
341 match_rule(rule),
Eric Fiselierf76a0872016-08-29 19:12:01 +0000342 substituted_regex(internal::PerformSubstitutions(regex_str)),
Eric Fiselierd87eb992016-11-05 00:30:27 +0000343 regex(std::make_shared<benchmark::Regex>()) {
344 std::string err_str;
Eric Fiselierffc31db2018-07-10 04:02:00 +0000345 regex->Init(substituted_regex, &err_str);
Eric Fiselierd87eb992016-11-05 00:30:27 +0000346 CHECK(err_str.empty()) << "Could not construct regex \"" << substituted_regex
347 << "\""
348 << "\n originally \"" << regex_str << "\""
349 << "\n got error: " << err_str;
Eric Fiselierf76a0872016-08-29 19:12:01 +0000350}
351
352int AddCases(TestCaseID ID, std::initializer_list<TestCase> il) {
Eric Fiselierd87eb992016-11-05 00:30:27 +0000353 auto& L = internal::GetTestCaseList(ID);
354 L.insert(L.end(), il);
355 return 0;
Eric Fiselierf76a0872016-08-29 19:12:01 +0000356}
357
Eric Fiselierd87eb992016-11-05 00:30:27 +0000358int SetSubstitutions(
359 std::initializer_list<std::pair<std::string, std::string>> il) {
360 auto& subs = internal::GetSubstitutions();
361 for (auto KV : il) {
362 bool exists = false;
363 KV.second = internal::PerformSubstitutions(KV.second);
364 for (auto& EKV : subs) {
365 if (EKV.first == KV.first) {
366 EKV.second = std::move(KV.second);
367 exists = true;
368 break;
369 }
Eric Fiselierf76a0872016-08-29 19:12:01 +0000370 }
Eric Fiselierd87eb992016-11-05 00:30:27 +0000371 if (!exists) subs.push_back(std::move(KV));
372 }
373 return 0;
Eric Fiselierf76a0872016-08-29 19:12:01 +0000374}
375
376void RunOutputTests(int argc, char* argv[]) {
377 using internal::GetTestCaseList;
378 benchmark::Initialize(&argc, argv);
Eric Fiselierffc31db2018-07-10 04:02:00 +0000379 auto options = benchmark::internal::GetOutputOptions(/*force_no_color*/ true);
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000380 benchmark::ConsoleReporter CR(options);
Eric Fiselierf76a0872016-08-29 19:12:01 +0000381 benchmark::JSONReporter JR;
382 benchmark::CSVReporter CSVR;
383 struct ReporterTest {
384 const char* name;
385 std::vector<TestCase>& output_cases;
386 std::vector<TestCase>& error_cases;
387 benchmark::BenchmarkReporter& reporter;
388 std::stringstream out_stream;
389 std::stringstream err_stream;
390
Eric Fiselierd87eb992016-11-05 00:30:27 +0000391 ReporterTest(const char* n, std::vector<TestCase>& out_tc,
Eric Fiselierf76a0872016-08-29 19:12:01 +0000392 std::vector<TestCase>& err_tc,
393 benchmark::BenchmarkReporter& br)
394 : name(n), output_cases(out_tc), error_cases(err_tc), reporter(br) {
Eric Fiselierd87eb992016-11-05 00:30:27 +0000395 reporter.SetOutputStream(&out_stream);
396 reporter.SetErrorStream(&err_stream);
Eric Fiselierf76a0872016-08-29 19:12:01 +0000397 }
398 } TestCases[] = {
399 {"ConsoleReporter", GetTestCaseList(TC_ConsoleOut),
Eric Fiselierd87eb992016-11-05 00:30:27 +0000400 GetTestCaseList(TC_ConsoleErr), CR},
401 {"JSONReporter", GetTestCaseList(TC_JSONOut), GetTestCaseList(TC_JSONErr),
402 JR},
403 {"CSVReporter", GetTestCaseList(TC_CSVOut), GetTestCaseList(TC_CSVErr),
404 CSVR},
Eric Fiselierf76a0872016-08-29 19:12:01 +0000405 };
406
407 // Create the test reporter and run the benchmarks.
408 std::cout << "Running benchmarks...\n";
409 internal::TestReporter test_rep({&CR, &JR, &CSVR});
410 benchmark::RunSpecifiedBenchmarks(&test_rep);
411
412 for (auto& rep_test : TestCases) {
Eric Fiselierd87eb992016-11-05 00:30:27 +0000413 std::string msg = std::string("\nTesting ") + rep_test.name + " Output\n";
414 std::string banner(msg.size() - 1, '-');
415 std::cout << banner << msg << banner << "\n";
Eric Fiselierf76a0872016-08-29 19:12:01 +0000416
Eric Fiselierd87eb992016-11-05 00:30:27 +0000417 std::cerr << rep_test.err_stream.str();
418 std::cout << rep_test.out_stream.str();
Eric Fiselierf76a0872016-08-29 19:12:01 +0000419
Eric Fiselierd87eb992016-11-05 00:30:27 +0000420 internal::CheckCases(rep_test.error_cases, rep_test.err_stream);
421 internal::CheckCases(rep_test.output_cases, rep_test.out_stream);
Eric Fiselierf76a0872016-08-29 19:12:01 +0000422
Eric Fiselierd87eb992016-11-05 00:30:27 +0000423 std::cout << "\n";
Eric Fiselierf76a0872016-08-29 19:12:01 +0000424 }
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000425
426 // now that we know the output is as expected, we can dispatch
427 // the checks to subscribees.
Eric Fiselierffc31db2018-07-10 04:02:00 +0000428 auto& csv = TestCases[2];
Eric Fiselierfd2e3e92018-01-18 04:23:01 +0000429 // would use == but gcc spits a warning
430 CHECK(std::strcmp(csv.name, "CSVReporter") == 0);
431 internal::GetResultsChecker().CheckResults(csv.out_stream);
Eric Fiselierf76a0872016-08-29 19:12:01 +0000432}
Eric Fiselier622fc112018-11-15 19:22:53 +0000433
434int SubstrCnt(const std::string& haystack, const std::string& pat) {
435 if (pat.length() == 0) return 0;
436 int count = 0;
437 for (size_t offset = haystack.find(pat); offset != std::string::npos;
438 offset = haystack.find(pat, offset + pat.length()))
439 ++count;
440 return count;
441}
442
Eric Fiselier114125f2018-12-14 03:37:13 +0000443static char ToHex(int ch) {
444 return ch < 10 ? static_cast<char>('0' + ch)
445 : static_cast<char>('a' + (ch - 10));
446}
447
448static char RandomHexChar() {
449 static std::mt19937 rd{std::random_device{}()};
450 static std::uniform_int_distribution<int> mrand{0, 15};
451 return ToHex(mrand(rd));
452}
453
454static std::string GetRandomFileName() {
455 std::string model = "test.%%%%%%";
456 for (auto & ch : model) {
457 if (ch == '%')
458 ch = RandomHexChar();
459 }
460 return model;
461}
462
463static bool FileExists(std::string const& name) {
464 std::ifstream in(name.c_str());
465 return in.good();
466}
467
468static std::string GetTempFileName() {
469 // This function attempts to avoid race conditions where two tests
470 // create the same file at the same time. However, it still introduces races
471 // similar to tmpnam.
472 int retries = 3;
473 while (--retries) {
474 std::string name = GetRandomFileName();
475 if (!FileExists(name))
476 return name;
477 }
478 std::cerr << "Failed to create unique temporary file name" << std::endl;
479 std::abort();
480}
481
Eric Fiselier622fc112018-11-15 19:22:53 +0000482std::string GetFileReporterOutput(int argc, char* argv[]) {
483 std::vector<char*> new_argv(argv, argv + argc);
484 assert(static_cast<decltype(new_argv)::size_type>(argc) == new_argv.size());
485
Eric Fiselier114125f2018-12-14 03:37:13 +0000486 std::string tmp_file_name = GetTempFileName();
Eric Fiselier622fc112018-11-15 19:22:53 +0000487 std::cout << "Will be using this as the tmp file: " << tmp_file_name << '\n';
488
489 std::string tmp = "--benchmark_out=";
490 tmp += tmp_file_name;
491 new_argv.emplace_back(const_cast<char*>(tmp.c_str()));
492
493 argc = int(new_argv.size());
494
495 benchmark::Initialize(&argc, new_argv.data());
496 benchmark::RunSpecifiedBenchmarks();
497
498 // Read the output back from the file, and delete the file.
499 std::ifstream tmp_stream(tmp_file_name);
500 std::string output = std::string((std::istreambuf_iterator<char>(tmp_stream)),
501 std::istreambuf_iterator<char>());
502 std::remove(tmp_file_name.c_str());
503
504 return output;
505}