1 #include <cstdio>
2 #include <cstring>
3 #include <fstream>
4 #include <iostream>
5 #include <map>
6 #include <memory>
7 #include <random>
8 #include <sstream>
9 #include <streambuf>
10 
11 #include "../src/benchmark_api_internal.h"
12 #include "../src/check.h"  // NOTE: check.h is for internal use only!
13 #include "../src/log.h"    // NOTE: log.h is for internal use only
14 #include "../src/re.h"     // NOTE: re.h is for internal use only
15 #include "output_test.h"
16 
17 // ========================================================================= //
18 // ------------------------------ Internals -------------------------------- //
19 // ========================================================================= //
20 namespace internal {
21 namespace {
22 
23 using TestCaseList = std::vector<TestCase>;
24 
25 // Use a vector because the order elements are added matters during iteration.
26 // std::map/unordered_map don't guarantee that.
27 // For example:
28 //  SetSubstitutions({{"%HelloWorld", "Hello"}, {"%Hello", "Hi"}});
29 //     Substitute("%HelloWorld") // Always expands to Hello.
30 using SubMap = std::vector<std::pair<std::string, std::string>>;
31 
GetTestCaseList(TestCaseID ID)32 TestCaseList& GetTestCaseList(TestCaseID ID) {
33   // Uses function-local statics to ensure initialization occurs
34   // before first use.
35   static TestCaseList lists[TC_NumID];
36   return lists[ID];
37 }
38 
GetSubstitutions()39 SubMap& GetSubstitutions() {
40   // Don't use 'dec_re' from header because it may not yet be initialized.
41   // clang-format off
42   static std::string safe_dec_re = "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?";
43   static std::string time_re = "([0-9]+[.])?[0-9]+";
44   static std::string percentage_re = "[0-9]+[.][0-9]{2}";
45   static SubMap map = {
46       {"%float", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"},
47       // human-readable float
48       {"%hrfloat", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?[kKMGTPEZYmunpfazy]?i?"},
49       {"%percentage", percentage_re},
50       {"%int", "[ ]*[0-9]+"},
51       {" %s ", "[ ]+"},
52       {"%time", "[ ]*" + time_re + "[ ]+ns"},
53       {"%console_report", "[ ]*" + time_re + "[ ]+ns [ ]*" + time_re + "[ ]+ns [ ]*[0-9]+"},
54       {"%console_percentage_report", "[ ]*" + percentage_re + "[ ]+% [ ]*" + percentage_re + "[ ]+% [ ]*[0-9]+"},
55       {"%console_us_report", "[ ]*" + time_re + "[ ]+us [ ]*" + time_re + "[ ]+us [ ]*[0-9]+"},
56       {"%console_ms_report", "[ ]*" + time_re + "[ ]+ms [ ]*" + time_re + "[ ]+ms [ ]*[0-9]+"},
57       {"%console_s_report", "[ ]*" + time_re + "[ ]+s [ ]*" + time_re + "[ ]+s [ ]*[0-9]+"},
58       {"%console_time_only_report", "[ ]*" + time_re + "[ ]+ns [ ]*" + time_re + "[ ]+ns"},
59       {"%console_us_report", "[ ]*" + time_re + "[ ]+us [ ]*" + time_re + "[ ]+us [ ]*[0-9]+"},
60       {"%console_us_time_only_report", "[ ]*" + time_re + "[ ]+us [ ]*" + time_re + "[ ]+us"},
61       {"%csv_header",
62        "name,iterations,real_time,cpu_time,time_unit,bytes_per_second,"
63        "items_per_second,label,error_occurred,error_message"},
64       {"%csv_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,,,,,"},
65       {"%csv_us_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",us,,,,,"},
66       {"%csv_ms_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ms,,,,,"},
67       {"%csv_s_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",s,,,,,"},
68       {"%csv_bytes_report",
69        "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns," + safe_dec_re + ",,,,"},
70       {"%csv_items_report",
71        "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,," + safe_dec_re + ",,,"},
72       {"%csv_bytes_items_report",
73        "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns," + safe_dec_re +
74        "," + safe_dec_re + ",,,"},
75       {"%csv_label_report_begin", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,,,"},
76       {"%csv_label_report_end", ",,"}};
77   // clang-format on
78   return map;
79 }
80 
PerformSubstitutions(std::string source)81 std::string PerformSubstitutions(std::string source) {
82   SubMap const& subs = GetSubstitutions();
83   using SizeT = std::string::size_type;
84   for (auto const& KV : subs) {
85     SizeT pos;
86     SizeT next_start = 0;
87     while ((pos = source.find(KV.first, next_start)) != std::string::npos) {
88       next_start = pos + KV.second.size();
89       source.replace(pos, KV.first.size(), KV.second);
90     }
91   }
92   return source;
93 }
94 
CheckCase(std::stringstream& remaining_output, TestCase const& TC, TestCaseList const& not_checks)95 void CheckCase(std::stringstream& remaining_output, TestCase const& TC,
96                TestCaseList const& not_checks) {
97   std::string first_line;
98   bool on_first = true;
99   std::string line;
100   while (remaining_output.eof() == false) {
101     BM_CHECK(remaining_output.good());
102     std::getline(remaining_output, line);
103     if (on_first) {
104       first_line = line;
105       on_first = false;
106     }
107     for (const auto& NC : not_checks) {
108       BM_CHECK(!NC.regex->Match(line))
109           << "Unexpected match for line \"" << line << "\" for MR_Not regex \""
110           << NC.regex_str << "\""
111           << "\n    actual regex string \"" << TC.substituted_regex << "\""
112           << "\n    started matching near: " << first_line;
113     }
114     if (TC.regex->Match(line)) return;
115     BM_CHECK(TC.match_rule != MR_Next)
116         << "Expected line \"" << line << "\" to match regex \"" << TC.regex_str
117         << "\""
118         << "\n    actual regex string \"" << TC.substituted_regex << "\""
119         << "\n    started matching near: " << first_line;
120   }
121   BM_CHECK(remaining_output.eof() == false)
122       << "End of output reached before match for regex \"" << TC.regex_str
123       << "\" was found"
124       << "\n    actual regex string \"" << TC.substituted_regex << "\""
125       << "\n    started matching near: " << first_line;
126 }
127 
CheckCases(TestCaseList const& checks, std::stringstream& output)128 void CheckCases(TestCaseList const& checks, std::stringstream& output) {
129   std::vector<TestCase> not_checks;
130   for (size_t i = 0; i < checks.size(); ++i) {
131     const auto& TC = checks[i];
132     if (TC.match_rule == MR_Not) {
133       not_checks.push_back(TC);
134       continue;
135     }
136     CheckCase(output, TC, not_checks);
137     not_checks.clear();
138   }
139 }
140 
141 class TestReporter : public benchmark::BenchmarkReporter {
142  public:
TestReporter(std::vector<benchmark::BenchmarkReporter*> reps)143   TestReporter(std::vector<benchmark::BenchmarkReporter*> reps)
144       : reporters_(std::move(reps)) {}
145 
146   bool ReportContext(const Context& context) override {
147     bool last_ret = false;
148     bool first = true;
149     for (auto rep : reporters_) {
150       bool new_ret = rep->ReportContext(context);
151       BM_CHECK(first || new_ret == last_ret)
152           << "Reports return different values for ReportContext";
153       first = false;
154       last_ret = new_ret;
155     }
156     (void)first;
157     return last_ret;
158   }
159 
160   void ReportRuns(const std::vector<Run>& report) override {
161     for (auto rep : reporters_) rep->ReportRuns(report);
162   }
163   void Finalize() override {
164     for (auto rep : reporters_) rep->Finalize();
165   }
166 
167  private:
168   std::vector<benchmark::BenchmarkReporter*> reporters_;
169 };
170 }  // namespace
171 
172 }  // end namespace internal
173 
174 // ========================================================================= //
175 // -------------------------- Results checking ----------------------------- //
176 // ========================================================================= //
177 
178 namespace internal {
179 
180 // Utility class to manage subscribers for checking benchmark results.
181 // It works by parsing the CSV output to read the results.
182 class ResultsChecker {
183  public:
184   struct PatternAndFn : public TestCase {  // reusing TestCase for its regexes
PatternAndFninternal::ResultsChecker::PatternAndFn185     PatternAndFn(const std::string& rx, ResultsCheckFn fn_)
186         : TestCase(rx), fn(std::move(fn_)) {}
187     ResultsCheckFn fn;
188   };
189 
190   std::vector<PatternAndFn> check_patterns;
191   std::vector<Results> results;
192   std::vector<std::string> field_names;
193 
194   void Add(const std::string& entry_pattern, const ResultsCheckFn& fn);
195 
196   void CheckResults(std::stringstream& output);
197 
198  private:
199   void SetHeader_(const std::string& csv_header);
200   void SetValues_(const std::string& entry_csv_line);
201 
202   std::vector<std::string> SplitCsv_(const std::string& line);
203 };
204 
205 // store the static ResultsChecker in a function to prevent initialization
206 // order problems
GetResultsChecker()207 ResultsChecker& GetResultsChecker() {
208   static ResultsChecker rc;
209   return rc;
210 }
211 
212 // add a results checker for a benchmark
Add(const std::string& entry_pattern, const ResultsCheckFn& fn)213 void ResultsChecker::Add(const std::string& entry_pattern,
214                          const ResultsCheckFn& fn) {
215   check_patterns.emplace_back(entry_pattern, fn);
216 }
217 
218 // check the results of all subscribed benchmarks
CheckResults(std::stringstream& output)219 void ResultsChecker::CheckResults(std::stringstream& output) {
220   // first reset the stream to the start
221   {
222     auto start = std::stringstream::pos_type(0);
223     // clear before calling tellg()
224     output.clear();
225     // seek to zero only when needed
226     if (output.tellg() > start) output.seekg(start);
227     // and just in case
228     output.clear();
229   }
230   // now go over every line and publish it to the ResultsChecker
231   std::string line;
232   bool on_first = true;
233   while (output.eof() == false) {
234     BM_CHECK(output.good());
235     std::getline(output, line);
236     if (on_first) {
237       SetHeader_(line);  // this is important
238       on_first = false;
239       continue;
240     }
241     SetValues_(line);
242   }
243   // finally we can call the subscribed check functions
244   for (const auto& p : check_patterns) {
245     BM_VLOG(2) << "--------------------------------\n";
246     BM_VLOG(2) << "checking for benchmarks matching " << p.regex_str << "...\n";
247     for (const auto& r : results) {
248       if (!p.regex->Match(r.name)) {
249         BM_VLOG(2) << p.regex_str << " is not matched by " << r.name << "\n";
250         continue;
251       }
252       BM_VLOG(2) << p.regex_str << " is matched by " << r.name << "\n";
253       BM_VLOG(1) << "Checking results of " << r.name << ": ... \n";
254       p.fn(r);
255       BM_VLOG(1) << "Checking results of " << r.name << ": OK.\n";
256     }
257   }
258 }
259 
260 // prepare for the names in this header
SetHeader_(const std::string& csv_header)261 void ResultsChecker::SetHeader_(const std::string& csv_header) {
262   field_names = SplitCsv_(csv_header);
263 }
264 
265 // set the values for a benchmark
SetValues_(const std::string& entry_csv_line)266 void ResultsChecker::SetValues_(const std::string& entry_csv_line) {
267   if (entry_csv_line.empty()) return;  // some lines are empty
268   BM_CHECK(!field_names.empty());
269   auto vals = SplitCsv_(entry_csv_line);
270   BM_CHECK_EQ(vals.size(), field_names.size());
271   results.emplace_back(vals[0]);  // vals[0] is the benchmark name
272   auto& entry = results.back();
273   for (size_t i = 1, e = vals.size(); i < e; ++i) {
274     entry.values[field_names[i]] = vals[i];
275   }
276 }
277 
278 // a quick'n'dirty csv splitter (eliminating quotes)
SplitCsv_(const std::string& line)279 std::vector<std::string> ResultsChecker::SplitCsv_(const std::string& line) {
280   std::vector<std::string> out;
281   if (line.empty()) return out;
282   if (!field_names.empty()) out.reserve(field_names.size());
283   size_t prev = 0, pos = line.find_first_of(','), curr = pos;
284   while (pos != line.npos) {
285     BM_CHECK(curr > 0);
286     if (line[prev] == '"') ++prev;
287     if (line[curr - 1] == '"') --curr;
288     out.push_back(line.substr(prev, curr - prev));
289     prev = pos + 1;
290     pos = line.find_first_of(',', pos + 1);
291     curr = pos;
292   }
293   curr = line.size();
294   if (line[prev] == '"') ++prev;
295   if (line[curr - 1] == '"') --curr;
296   out.push_back(line.substr(prev, curr - prev));
297   return out;
298 }
299 
300 }  // end namespace internal
301 
AddChecker(const std::string& bm_name, const ResultsCheckFn& fn)302 size_t AddChecker(const std::string& bm_name, const ResultsCheckFn& fn) {
303   auto& rc = internal::GetResultsChecker();
304   rc.Add(bm_name, fn);
305   return rc.results.size();
306 }
307 
NumThreads() const308 int Results::NumThreads() const {
309   auto pos = name.find("/threads:");
310   if (pos == name.npos) return 1;
311   auto end = name.find('/', pos + 9);
312   std::stringstream ss;
313   ss << name.substr(pos + 9, end);
314   int num = 1;
315   ss >> num;
316   BM_CHECK(!ss.fail());
317   return num;
318 }
319 
NumIterations() const320 double Results::NumIterations() const { return GetAs<double>("iterations"); }
321 
GetTime(BenchmarkTime which) const322 double Results::GetTime(BenchmarkTime which) const {
323   BM_CHECK(which == kCpuTime || which == kRealTime);
324   const char* which_str = which == kCpuTime ? "cpu_time" : "real_time";
325   double val = GetAs<double>(which_str);
326   auto unit = Get("time_unit");
327   BM_CHECK(unit);
328   if (*unit == "ns") {
329     return val * 1.e-9;
330   }
331   if (*unit == "us") {
332     return val * 1.e-6;
333   }
334   if (*unit == "ms") {
335     return val * 1.e-3;
336   }
337   if (*unit == "s") {
338     return val;
339   }
340   BM_CHECK(1 == 0) << "unknown time unit: " << *unit;
341   return 0;
342 }
343 
344 // ========================================================================= //
345 // -------------------------- Public API Definitions------------------------ //
346 // ========================================================================= //
347 
TestCase(std::string re, int rule)348 TestCase::TestCase(std::string re, int rule)
349     : regex_str(std::move(re)),
350       match_rule(rule),
351       substituted_regex(internal::PerformSubstitutions(regex_str)),
352       regex(std::make_shared<benchmark::Regex>()) {
353   std::string err_str;
354   regex->Init(substituted_regex, &err_str);
355   BM_CHECK(err_str.empty())
356       << "Could not construct regex \"" << substituted_regex << "\""
357       << "\n    originally \"" << regex_str << "\""
358       << "\n    got error: " << err_str;
359 }
360 
AddCases(TestCaseID ID, std::initializer_list<TestCase> il)361 int AddCases(TestCaseID ID, std::initializer_list<TestCase> il) {
362   auto& L = internal::GetTestCaseList(ID);
363   L.insert(L.end(), il);
364   return 0;
365 }
366 
SetSubstitutions( std::initializer_list<std::pair<std::string, std::string>> il)367 int SetSubstitutions(
368     std::initializer_list<std::pair<std::string, std::string>> il) {
369   auto& subs = internal::GetSubstitutions();
370   for (auto KV : il) {
371     bool exists = false;
372     KV.second = internal::PerformSubstitutions(KV.second);
373     for (auto& EKV : subs) {
374       if (EKV.first == KV.first) {
375         EKV.second = std::move(KV.second);
376         exists = true;
377         break;
378       }
379     }
380     if (!exists) subs.push_back(std::move(KV));
381   }
382   return 0;
383 }
384 
385 // Disable deprecated warnings temporarily because we need to reference
386 // CSVReporter but don't want to trigger -Werror=-Wdeprecated-declarations
387 BENCHMARK_DISABLE_DEPRECATED_WARNING
388 
RunOutputTests(int argc, char* argv[])389 void RunOutputTests(int argc, char* argv[]) {
390   using internal::GetTestCaseList;
391   benchmark::Initialize(&argc, argv);
392   auto options = benchmark::internal::GetOutputOptions(/*force_no_color*/ true);
393   benchmark::ConsoleReporter CR(options);
394   benchmark::JSONReporter JR;
395   benchmark::CSVReporter CSVR;
396   struct ReporterTest {
397     std::string name;
398     std::vector<TestCase>& output_cases;
399     std::vector<TestCase>& error_cases;
400     benchmark::BenchmarkReporter& reporter;
401     std::stringstream out_stream;
402     std::stringstream err_stream;
403 
404     ReporterTest(const std::string& n, std::vector<TestCase>& out_tc,
405                  std::vector<TestCase>& err_tc,
406                  benchmark::BenchmarkReporter& br)
407         : name(n), output_cases(out_tc), error_cases(err_tc), reporter(br) {
408       reporter.SetOutputStream(&out_stream);
409       reporter.SetErrorStream(&err_stream);
410     }
411   } TestCases[] = {
412       {std::string("ConsoleReporter"), GetTestCaseList(TC_ConsoleOut),
413        GetTestCaseList(TC_ConsoleErr), CR},
414       {std::string("JSONReporter"), GetTestCaseList(TC_JSONOut),
415        GetTestCaseList(TC_JSONErr), JR},
416       {std::string("CSVReporter"), GetTestCaseList(TC_CSVOut),
417        GetTestCaseList(TC_CSVErr), CSVR},
418   };
419 
420   // Create the test reporter and run the benchmarks.
421   std::cout << "Running benchmarks...\n";
422   internal::TestReporter test_rep({&CR, &JR, &CSVR});
423   benchmark::RunSpecifiedBenchmarks(&test_rep);
424 
425   for (auto& rep_test : TestCases) {
426     std::string msg =
427         std::string("\nTesting ") + rep_test.name + std::string(" Output\n");
428     std::string banner(msg.size() - 1, '-');
429     std::cout << banner << msg << banner << "\n";
430 
431     std::cerr << rep_test.err_stream.str();
432     std::cout << rep_test.out_stream.str();
433 
434     internal::CheckCases(rep_test.error_cases, rep_test.err_stream);
435     internal::CheckCases(rep_test.output_cases, rep_test.out_stream);
436 
437     std::cout << "\n";
438   }
439 
440   // now that we know the output is as expected, we can dispatch
441   // the checks to subscribees.
442   auto& csv = TestCases[2];
443   // would use == but gcc spits a warning
444   BM_CHECK(csv.name == std::string("CSVReporter"));
445   internal::GetResultsChecker().CheckResults(csv.out_stream);
446 }
447 
448 BENCHMARK_RESTORE_DEPRECATED_WARNING
449 
SubstrCnt(const std::string& haystack, const std::string& pat)450 int SubstrCnt(const std::string& haystack, const std::string& pat) {
451   if (pat.length() == 0) return 0;
452   int count = 0;
453   for (size_t offset = haystack.find(pat); offset != std::string::npos;
454        offset = haystack.find(pat, offset + pat.length()))
455     ++count;
456   return count;
457 }
458 
ToHex(int ch)459 static char ToHex(int ch) {
460   return ch < 10 ? static_cast<char>('0' + ch)
461                  : static_cast<char>('a' + (ch - 10));
462 }
463 
RandomHexChar()464 static char RandomHexChar() {
465   static std::mt19937 rd{std::random_device{}()};
466   static std::uniform_int_distribution<int> mrand{0, 15};
467   return ToHex(mrand(rd));
468 }
469 
GetRandomFileName()470 static std::string GetRandomFileName() {
471   std::string model = "test.%%%%%%";
472   for (auto& ch : model) {
473     if (ch == '%') ch = RandomHexChar();
474   }
475   return model;
476 }
477 
FileExists(std::string const& name)478 static bool FileExists(std::string const& name) {
479   std::ifstream in(name.c_str());
480   return in.good();
481 }
482 
GetTempFileName()483 static std::string GetTempFileName() {
484   // This function attempts to avoid race conditions where two tests
485   // create the same file at the same time. However, it still introduces races
486   // similar to tmpnam.
487   int retries = 3;
488   while (--retries) {
489     std::string name = GetRandomFileName();
490     if (!FileExists(name)) return name;
491   }
492   std::cerr << "Failed to create unique temporary file name" << std::endl;
493   std::abort();
494 }
495 
GetFileReporterOutput(int argc, char* argv[])496 std::string GetFileReporterOutput(int argc, char* argv[]) {
497   std::vector<char*> new_argv(argv, argv + argc);
498   assert(static_cast<decltype(new_argv)::size_type>(argc) == new_argv.size());
499 
500   std::string tmp_file_name = GetTempFileName();
501   std::cout << "Will be using this as the tmp file: " << tmp_file_name << '\n';
502 
503   std::string tmp = "--benchmark_out=";
504   tmp += tmp_file_name;
505   new_argv.emplace_back(const_cast<char*>(tmp.c_str()));
506 
507   argc = int(new_argv.size());
508 
509   benchmark::Initialize(&argc, new_argv.data());
510   benchmark::RunSpecifiedBenchmarks();
511 
512   // Read the output back from the file, and delete the file.
513   std::ifstream tmp_stream(tmp_file_name);
514   std::string output = std::string((std::istreambuf_iterator<char>(tmp_stream)),
515                                    std::istreambuf_iterator<char>());
516   std::remove(tmp_file_name.c_str());
517 
518   return output;
519 }
520