• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 6546858227

17 Oct 2023 12:02PM UTC coverage: 91.71% (+0.002%) from 91.708%
6546858227

push

github

randombit
Merge GH #3760 Move constant time memory comparisons to ct_utils.h

80095 of 87335 relevant lines covered (91.71%)

8508512.25 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

78.91
/src/tests/tests.cpp
1
/*
2
* (C) 2014,2015 Jack Lloyd
3
*
4
* Botan is released under the Simplified BSD License (see license.txt)
5
*/
6

7
#include "tests.h"
8

9
#include <botan/hex.h>
10
#include <botan/internal/cpuid.h>
11
#include <botan/internal/filesystem.h>
12
#include <botan/internal/fmt.h>
13
#include <botan/internal/parsing.h>
14
#include <botan/internal/stl_util.h>
15
#include <fstream>
16
#include <iomanip>
17
#include <sstream>
18

19
#if defined(BOTAN_HAS_BIGINT)
20
   #include <botan/bigint.h>
21
#endif
22

23
#if defined(BOTAN_HAS_EC_CURVE_GFP)
24
   #include <botan/ec_point.h>
25
#endif
26

27
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
28
   #include <stdlib.h>
29
   #include <unistd.h>
30
#endif
31

32
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)
33
   #include <version>
34
   #if defined(__cpp_lib_filesystem)
35
      #include <filesystem>
36
   #endif
37
#endif
38

39
namespace Botan_Tests {
40

41
void Test::Result::merge(const Result& other, bool ignore_test_name) {
105,614✔
42
   if(who() != other.who()) {
105,614✔
43
      if(!ignore_test_name) {
59✔
44
         throw Test_Error("Merging tests from different sources");
×
45
      }
46

47
      // When deliberately merging results with different names, the code location is
48
      // likely inconsistent and must be discarded.
49
      m_where.reset();
59✔
50
   } else {
51
      m_where = other.m_where;
105,555✔
52
   }
53

54
   m_timestamp = std::min(m_timestamp, other.m_timestamp);
105,614✔
55
   m_ns_taken += other.m_ns_taken;
105,614✔
56
   m_tests_passed += other.m_tests_passed;
105,614✔
57
   m_fail_log.insert(m_fail_log.end(), other.m_fail_log.begin(), other.m_fail_log.end());
105,614✔
58
   m_log.insert(m_log.end(), other.m_log.begin(), other.m_log.end());
105,614✔
59
}
105,614✔
60

61
void Test::Result::start_timer() {
759✔
62
   if(m_started == 0) {
759✔
63
      m_started = Test::timestamp();
759✔
64
   }
65
}
759✔
66

67
void Test::Result::end_timer() {
843✔
68
   if(m_started > 0) {
843✔
69
      m_ns_taken += Test::timestamp() - m_started;
1,516✔
70
      m_started = 0;
758✔
71
   }
72
}
843✔
73

74
void Test::Result::test_note(const std::string& note, const char* extra) {
2,669✔
75
   if(!note.empty()) {
2,669✔
76
      std::ostringstream out;
2,669✔
77
      out << who() << " " << note;
2,669✔
78
      if(extra) {
2,669✔
79
         out << ": " << extra;
12✔
80
      }
81
      m_log.push_back(out.str());
2,669✔
82
   }
2,669✔
83
}
2,669✔
84

85
void Test::Result::note_missing(const std::string& whatever) {
275✔
86
   static std::set<std::string> s_already_seen;
275✔
87

88
   if(!s_already_seen.contains(whatever)) {
275✔
89
      test_note("Skipping tests due to missing " + whatever);
5✔
90
      s_already_seen.insert(whatever);
5✔
91
   }
92
}
275✔
93

94
bool Test::Result::ThrowExpectations::check(const std::string& test_name, Test::Result& result) {
46,086✔
95
   m_consumed = true;
46,086✔
96

97
   try {
46,086✔
98
      m_fn();
46,086✔
99
      if(!m_expect_success) {
62✔
100
         return result.test_failure(test_name + " failed to throw expected exception");
4✔
101
      }
102
   } catch(const std::exception& ex) {
46,024✔
103
      if(m_expect_success) {
46,022✔
104
         return result.test_failure(test_name + " threw unexpected exception: " + ex.what());
2✔
105
      }
106
      if(m_expected_exception_type.has_value() && m_expected_exception_type.value() != typeid(ex)) {
46,021✔
107
         return result.test_failure(test_name + " threw unexpected exception: " + ex.what());
4✔
108
      }
109
      if(m_expected_message.has_value() && m_expected_message.value() != ex.what()) {
46,019✔
110
         return result.test_failure(test_name + " threw exception with unexpected message (expected: '" +
3✔
111
                                    m_expected_message.value() + "', got: '" + ex.what() + "')");
3✔
112
      }
113
   } catch(...) {
46,024✔
114
      if(m_expect_success || m_expected_exception_type.has_value() || m_expected_message.has_value()) {
2✔
115
         return result.test_failure(test_name + " threw unexpected unknown exception");
1✔
116
      }
117
   }
2✔
118

119
   return result.test_success(test_name + " behaved as expected");
92,158✔
120
}
121

122
bool Test::Result::test_throws(const std::string& what, const std::function<void()>& fn) {
45,828✔
123
   return ThrowExpectations(fn).check(what, *this);
91,656✔
124
}
125

126
bool Test::Result::test_throws(const std::string& what, const std::string& expected, const std::function<void()>& fn) {
154✔
127
   return ThrowExpectations(fn).expect_message(expected).check(what, *this);
308✔
128
}
129

130
bool Test::Result::test_no_throw(const std::string& what, const std::function<void()>& fn) {
61✔
131
   return ThrowExpectations(fn).expect_success().check(what, *this);
122✔
132
}
133

134
bool Test::Result::test_success(const std::string& note) {
2,992,803✔
135
   if(Test::options().log_success()) {
2,992,696✔
136
      test_note(note);
×
137
   }
138
   ++m_tests_passed;
2,992,803✔
139
   return true;
402,522✔
140
}
141

142
bool Test::Result::test_failure(const std::string& what, const std::string& error) {
1✔
143
   return test_failure(who() + " " + what + " with error " + error);
2✔
144
}
145

146
void Test::Result::test_failure(const std::string& what, const uint8_t buf[], size_t buf_len) {
1✔
147
   test_failure(who() + ": " + what + " buf len " + std::to_string(buf_len) + " value " +
2✔
148
                Botan::hex_encode(buf, buf_len));
1✔
149
}
1✔
150

151
bool Test::Result::test_failure(const std::string& err) {
25✔
152
   m_fail_log.push_back(err);
25✔
153

154
   if(Test::options().abort_on_first_fail() && m_who != "Failing Test") {
25✔
155
      std::abort();
×
156
   }
157
   return false;
25✔
158
}
159

160
namespace {
161

162
bool same_contents(const uint8_t x[], const uint8_t y[], size_t len) {
171,923✔
163
   return (len == 0) ? true : std::memcmp(x, y, len) == 0;
170,586✔
164
}
165

166
}  // namespace
167

168
bool Test::Result::test_ne(const std::string& what,
1,944✔
169
                           const uint8_t produced[],
170
                           size_t produced_len,
171
                           const uint8_t expected[],
172
                           size_t expected_len) {
173
   if(produced_len == expected_len && same_contents(produced, expected, expected_len)) {
1,944✔
174
      return test_failure(who() + ": " + what + " produced matching");
2✔
175
   }
176
   return test_success();
3,884✔
177
}
178

179
bool Test::Result::test_eq(const char* producer,
171,733✔
180
                           const std::string& what,
181
                           const uint8_t produced[],
182
                           size_t produced_size,
183
                           const uint8_t expected[],
184
                           size_t expected_size) {
185
   if(produced_size == expected_size && same_contents(produced, expected, expected_size)) {
171,733✔
186
      return test_success();
343,464✔
187
   }
188

189
   std::ostringstream err;
1✔
190

191
   err << who();
1✔
192

193
   if(producer) {
1✔
194
      err << " producer '" << producer << "'";
×
195
   }
196

197
   err << " unexpected result for " << what;
1✔
198

199
   if(produced_size != expected_size) {
1✔
200
      err << " produced " << produced_size << " bytes expected " << expected_size;
1✔
201
   }
202

203
   std::vector<uint8_t> xor_diff(std::min(produced_size, expected_size));
2✔
204
   size_t bytes_different = 0;
1✔
205

206
   for(size_t i = 0; i != xor_diff.size(); ++i) {
4✔
207
      xor_diff[i] = produced[i] ^ expected[i];
3✔
208
      bytes_different += (xor_diff[i] > 0);
3✔
209
   }
210

211
   err << "\nProduced: " << Botan::hex_encode(produced, produced_size)
1✔
212
       << "\nExpected: " << Botan::hex_encode(expected, expected_size);
3✔
213

214
   if(bytes_different > 0) {
1✔
215
      err << "\nXOR Diff: " << Botan::hex_encode(xor_diff);
1✔
216
   }
217

218
   return test_failure(err.str());
2✔
219
}
1✔
220

221
bool Test::Result::test_is_nonempty(const std::string& what_is_it, const std::string& to_examine) {
29,322✔
222
   if(to_examine.empty()) {
29,322✔
223
      return test_failure(what_is_it + " was empty");
1✔
224
   }
225
   return test_success();
58,642✔
226
}
227

228
bool Test::Result::test_eq(const std::string& what, const std::string& produced, const std::string& expected) {
61,644✔
229
   return test_is_eq(what, produced, expected);
61,644✔
230
}
231

232
bool Test::Result::test_eq(const std::string& what, const char* produced, const char* expected) {
20✔
233
   return test_is_eq(what, std::string(produced), std::string(expected));
34✔
234
}
235

236
bool Test::Result::test_eq(const std::string& what, size_t produced, size_t expected) {
125,507✔
237
   return test_is_eq(what, produced, expected);
125,507✔
238
}
239

240
bool Test::Result::test_eq_sz(const std::string& what, size_t produced, size_t expected) {
665✔
241
   return test_is_eq(what, produced, expected);
665✔
242
}
243

244
bool Test::Result::test_eq(const std::string& what,
107✔
245
                           const Botan::OctetString& produced,
246
                           const Botan::OctetString& expected) {
247
   std::ostringstream out;
107✔
248
   out << m_who << " " << what;
107✔
249

250
   if(produced == expected) {
107✔
251
      out << " produced expected result " << produced.to_string();
214✔
252
      return test_success(out.str());
214✔
253
   } else {
254
      out << " produced unexpected result '" << produced.to_string() << "' expected '" << expected.to_string() << "'";
×
255
      return test_failure(out.str());
×
256
   }
257
}
107✔
258

259
bool Test::Result::test_lt(const std::string& what, size_t produced, size_t expected) {
4,940✔
260
   if(produced >= expected) {
4,940✔
261
      std::ostringstream err;
1✔
262
      err << m_who << " " << what;
1✔
263
      err << " unexpected result " << produced << " >= " << expected;
1✔
264
      return test_failure(err.str());
1✔
265
   }
1✔
266

267
   return test_success();
9,878✔
268
}
269

270
bool Test::Result::test_lte(const std::string& what, size_t produced, size_t expected) {
1,017,710✔
271
   if(produced > expected) {
1,017,710✔
272
      std::ostringstream err;
1✔
273
      err << m_who << " " << what << " unexpected result " << produced << " > " << expected;
1✔
274
      return test_failure(err.str());
1✔
275
   }
1✔
276

277
   return test_success();
2,035,418✔
278
}
279

280
bool Test::Result::test_gte(const std::string& what, size_t produced, size_t expected) {
1,130,141✔
281
   if(produced < expected) {
1,130,141✔
282
      std::ostringstream err;
1✔
283
      err << m_who;
1✔
284
      err << " " << what;
1✔
285
      err << " unexpected result " << produced << " < " << expected;
1✔
286
      return test_failure(err.str());
1✔
287
   }
1✔
288

289
   return test_success();
2,260,280✔
290
}
291

292
bool Test::Result::test_gt(const std::string& what, size_t produced, size_t expected) {
14,408✔
293
   if(produced <= expected) {
14,408✔
294
      std::ostringstream err;
×
295
      err << m_who;
×
296
      err << " " << what;
×
297
      err << " unexpected result " << produced << " <= " << expected;
×
298
      return test_failure(err.str());
×
299
   }
×
300

301
   return test_success();
28,816✔
302
}
303

304
bool Test::Result::test_ne(const std::string& what, const std::string& str1, const std::string& str2) {
25✔
305
   if(str1 != str2) {
25✔
306
      return test_success(str1 + " != " + str2);
63✔
307
   }
308

309
   return test_failure(who() + " " + what + " produced matching strings " + str1);
2✔
310
}
311

312
bool Test::Result::test_ne(const std::string& what, size_t produced, size_t expected) {
9✔
313
   if(produced != expected) {
9✔
314
      return test_success();
16✔
315
   }
316

317
   std::ostringstream err;
1✔
318
   err << who() << " " << what << " produced " << produced << " unexpected value";
1✔
319
   return test_failure(err.str());
1✔
320
}
1✔
321

322
#if defined(BOTAN_HAS_BIGINT)
323
bool Test::Result::test_eq(const std::string& what, const BigInt& produced, const BigInt& expected) {
10,524✔
324
   return test_is_eq(what, produced, expected);
10,524✔
325
}
326

327
bool Test::Result::test_ne(const std::string& what, const BigInt& produced, const BigInt& expected) {
96✔
328
   if(produced != expected) {
96✔
329
      return test_success();
190✔
330
   }
331

332
   std::ostringstream err;
1✔
333
   err << who() << " " << what << " produced " << produced << " prohibited value";
1✔
334
   return test_failure(err.str());
1✔
335
}
1✔
336
#endif
337

338
#if defined(BOTAN_HAS_EC_CURVE_GFP)
339
bool Test::Result::test_eq(const std::string& what, const Botan::EC_Point& a, const Botan::EC_Point& b) {
3,135✔
340
   //return test_is_eq(what, a, b);
341
   if(a == b) {
3,135✔
342
      return test_success();
6,270✔
343
   }
344

345
   std::ostringstream err;
×
346
   err << who() << " " << what << " a=(" << a.get_affine_x() << "," << a.get_affine_y() << ")"
×
347
       << " b=(" << b.get_affine_x() << "," << b.get_affine_y();
×
348
   return test_failure(err.str());
×
349
}
×
350
#endif
351

352
bool Test::Result::test_eq(const std::string& what, bool produced, bool expected) {
284,256✔
353
   return test_is_eq(what, produced, expected);
284,256✔
354
}
355

356
bool Test::Result::test_rc_init(const std::string& func, int rc) {
39✔
357
   if(rc == 0) {
39✔
358
      return test_success();
78✔
359
   } else {
360
      std::ostringstream msg;
×
361
      msg << m_who;
×
362
      msg << " " << func;
×
363

364
      // -40 is BOTAN_FFI_ERROR_NOT_IMPLEMENTED
365
      if(rc == -40) {
×
366
         msg << " returned not implemented";
×
367
      } else {
368
         msg << " unexpectedly failed with error code " << rc;
×
369
      }
370

371
      if(rc == -40) {
×
372
         this->test_note(msg.str());
×
373
      } else {
374
         this->test_failure(msg.str());
×
375
      }
376
      return false;
×
377
   }
×
378
}
379

380
bool Test::Result::test_rc(const std::string& func, int expected, int rc) {
232✔
381
   if(expected != rc) {
232✔
382
      std::ostringstream err;
1✔
383
      err << m_who;
1✔
384
      err << " call to " << func << " unexpectedly returned " << rc;
1✔
385
      err << " but expecting " << expected;
1✔
386
      return test_failure(err.str());
1✔
387
   }
1✔
388

389
   return test_success();
462✔
390
}
391

392
std::vector<std::string> Test::possible_providers(const std::string& /*unused*/) {
×
393
   return Test::provider_filter({"base"});
×
394
}
395

396
//static
397
std::string Test::format_time(uint64_t ns) {
1,016✔
398
   std::ostringstream o;
1,016✔
399

400
   if(ns > 1000000000) {
1,016✔
401
      o << std::setprecision(2) << std::fixed << ns / 1000000000.0 << " sec";
132✔
402
   } else {
403
      o << std::setprecision(2) << std::fixed << ns / 1000000.0 << " msec";
884✔
404
   }
405

406
   return o.str();
2,032✔
407
}
1,016✔
408

409
Test::Result::Result(std::string who, const std::vector<Result>& downstream_results) : Result(std::move(who)) {
24✔
410
   for(const auto& result : downstream_results) {
71✔
411
      merge(result, true /* ignore non-matching test names */);
59✔
412
   }
413
}
12✔
414

415
// TODO: this should move to `StdoutReporter`
416
std::string Test::Result::result_string() const {
1,765✔
417
   const bool verbose = Test::options().verbose();
1,765✔
418

419
   if(tests_run() == 0 && !verbose) {
1,765✔
420
      return "";
13✔
421
   }
422

423
   std::ostringstream report;
1,752✔
424

425
   report << who() << " ran ";
1,752✔
426

427
   if(tests_run() == 0) {
1,752✔
428
      report << "ZERO";
×
429
   } else {
430
      report << tests_run();
1,752✔
431
   }
432
   report << " tests";
1,752✔
433

434
   if(m_ns_taken > 0) {
1,752✔
435
      report << " in " << format_time(m_ns_taken);
2,030✔
436
   }
437

438
   if(tests_failed()) {
1,752✔
439
      report << " " << tests_failed() << " FAILED";
25✔
440
   } else {
441
      report << " all ok";
1,727✔
442
   }
443

444
   report << "\n";
1,752✔
445

446
   for(size_t i = 0; i != m_fail_log.size(); ++i) {
1,777✔
447
      report << "Failure " << (i + 1) << ": " << m_fail_log[i];
25✔
448
      if(m_where) {
25✔
449
         report << " (at " << m_where->path << ":" << m_where->line << ")";
×
450
      }
451
      report << "\n";
25✔
452
   }
453

454
   if(!m_fail_log.empty() || tests_run() == 0 || verbose) {
1,752✔
455
      for(size_t i = 0; i != m_log.size(); ++i) {
25✔
456
         report << "Note " << (i + 1) << ": " << m_log[i] << "\n";
×
457
      }
458
   }
459

460
   return report.str();
1,752✔
461
}
1,752✔
462

463
namespace {
464

465
class Test_Registry {
466
   public:
467
      static Test_Registry& instance() {
989✔
468
         static Test_Registry registry;
990✔
469
         return registry;
989✔
470
      }
471

472
      void register_test(const std::string& category,
324✔
473
                         const std::string& name,
474
                         bool smoke_test,
475
                         bool needs_serialization,
476
                         std::function<std::unique_ptr<Test>()> maker_fn) {
477
         if(m_tests.contains(name)) {
324✔
478
            throw Test_Error("Duplicate registration of test '" + name + "'");
×
479
         }
480

481
         if(m_tests.contains(category)) {
324✔
482
            throw Test_Error("'" + category + "' cannot be used as category, test exists");
×
483
         }
484

485
         if(m_categories.contains(name)) {
324✔
486
            throw Test_Error("'" + name + "' cannot be used as test name, category exists");
×
487
         }
488

489
         if(smoke_test) {
324✔
490
            m_smoke_tests.push_back(name);
10✔
491
         }
492

493
         if(needs_serialization) {
324✔
494
            m_mutexed_tests.push_back(name);
20✔
495
         }
496

497
         m_tests.emplace(name, std::move(maker_fn));
324✔
498
         m_categories.emplace(category, name);
324✔
499
      }
324✔
500

501
      std::unique_ptr<Test> get_test(const std::string& test_name) const {
324✔
502
         auto i = m_tests.find(test_name);
324✔
503
         if(i != m_tests.end()) {
324✔
504
            return i->second();
324✔
505
         }
506
         return nullptr;
×
507
      }
508

509
      std::set<std::string> registered_tests() const { return Botan::map_keys_as_set(m_tests); }
×
510

511
      std::set<std::string> registered_test_categories() const { return Botan::map_keys_as_set(m_categories); }
×
512

513
      std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
1✔
514
                                                       const std::set<std::string>& to_be_skipped) {
515
         std::vector<std::string> result;
1✔
516

517
         // TODO: this is O(n^2), but we have a relatively small number of tests.
518
         auto insert_if_not_exists_and_not_skipped = [&](const std::string& test_name) {
325✔
519
            if(!Botan::value_exists(result, test_name) && to_be_skipped.find(test_name) == to_be_skipped.end()) {
324✔
520
               result.push_back(test_name);
314✔
521
            }
522
         };
325✔
523

524
         if(requested.empty()) {
1✔
525
            /*
526
            If nothing was requested on the command line, run everything. First
527
            run the "essentials" to smoke test, then everything else in
528
            alphabetical order.
529
            */
530
            result = m_smoke_tests;
1✔
531
            for(const auto& [test_name, _] : m_tests) {
325✔
532
               insert_if_not_exists_and_not_skipped(test_name);
324✔
533
            }
534
         } else {
535
            for(const auto& r : requested) {
×
536
               if(m_tests.find(r) != m_tests.end()) {
×
537
                  insert_if_not_exists_and_not_skipped(r);
×
538
               } else if(auto elems = m_categories.equal_range(r); elems.first != m_categories.end()) {
×
539
                  for(; elems.first != elems.second; ++elems.first) {
×
540
                     insert_if_not_exists_and_not_skipped(elems.first->second);
×
541
                  }
542
               } else {
543
                  throw Botan_Tests::Test_Error("Unknown test suite or category: " + r);
×
544
               }
545
            }
546
         }
547

548
         return result;
1✔
549
      }
×
550

551
      bool needs_serialization(const std::string& test_name) const {
340✔
552
         return Botan::value_exists(m_mutexed_tests, test_name);
16✔
553
      }
554

555
   private:
556
      Test_Registry() = default;
1✔
557

558
   private:
559
      std::map<std::string, std::function<std::unique_ptr<Test>()>> m_tests;
560
      std::multimap<std::string, std::string> m_categories;
561
      std::vector<std::string> m_smoke_tests;
562
      std::vector<std::string> m_mutexed_tests;
563
};
564

565
}  // namespace
566

567
// static Test:: functions
568

569
//static
570
void Test::register_test(const std::string& category,
324✔
571
                         const std::string& name,
572
                         bool smoke_test,
573
                         bool needs_serialization,
574
                         std::function<std::unique_ptr<Test>()> maker_fn) {
575
   Test_Registry::instance().register_test(category, name, smoke_test, needs_serialization, std::move(maker_fn));
648✔
576
}
324✔
577

578
//static
579
uint64_t Test::timestamp() {
89,473✔
580
   auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
89,473✔
581
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
89,469✔
582
}
583

584
//static
585
std::vector<Test::Result> Test::flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists) {
4✔
586
   std::vector<Test::Result> results;
4✔
587
   for(auto& result_list : result_lists) {
24✔
588
      for(auto& result : result_list) {
65✔
589
         results.emplace_back(std::move(result));
45✔
590
      }
591
   }
592
   return results;
4✔
593
}
×
594

595
//static
596
std::set<std::string> Test::registered_tests() {
×
597
   return Test_Registry::instance().registered_tests();
×
598
}
599

600
//static
601
std::set<std::string> Test::registered_test_categories() {
×
602
   return Test_Registry::instance().registered_test_categories();
×
603
}
604

605
//static
606
std::unique_ptr<Test> Test::get_test(const std::string& test_name) {
324✔
607
   return Test_Registry::instance().get_test(test_name);
324✔
608
}
609

610
//static
611
bool Test::test_needs_serialization(const std::string& test_name) {
324✔
612
   return Test_Registry::instance().needs_serialization(test_name);
324✔
613
}
614

615
//static
616
std::vector<std::string> Test::filter_registered_tests(const std::vector<std::string>& requested,
1✔
617
                                                       const std::set<std::string>& to_be_skipped) {
618
   return Test_Registry::instance().filter_registered_tests(requested, to_be_skipped);
1✔
619
}
620

621
//static
622
std::string Test::temp_file_name(const std::string& basename) {
21✔
623
   // TODO add a --tmp-dir option to the tests to specify where these files go
624

625
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
626

627
   // POSIX only calls for 6 'X' chars but OpenBSD allows arbitrary amount
628
   std::string mkstemp_basename = "/tmp/" + basename + ".XXXXXXXXXX";
21✔
629

630
   int fd = ::mkstemp(&mkstemp_basename[0]);
21✔
631

632
   // error
633
   if(fd < 0) {
21✔
634
      return "";
×
635
   }
636

637
   ::close(fd);
21✔
638

639
   return mkstemp_basename;
42✔
640
#else
641
   // For now just create the temp in the current working directory
642
   return basename;
643
#endif
644
}
21✔
645

646
bool Test::copy_file(const std::string& from, const std::string& to) {
1✔
647
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(__cpp_lib_filesystem)
648
   std::error_code ec;  // don't throw, just return false on error
1✔
649
   return std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
1✔
650
#else
651
   // TODO: implement fallbacks to POSIX or WIN32
652
   // ... but then again: it's 2023 and we're using C++20 :o)
653
   BOTAN_UNUSED(from, to);
654
   throw Botan::No_Filesystem_Access();
655
#endif
656
}
657

658
std::string Test::read_data_file(const std::string& path) {
27✔
659
   const std::string fsname = Test::data_file(path);
27✔
660
   std::ifstream file(fsname.c_str());
27✔
661
   if(!file.good()) {
27✔
662
      throw Test_Error("Error reading from " + fsname);
×
663
   }
664

665
   return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
27✔
666
}
54✔
667

668
std::vector<uint8_t> Test::read_binary_data_file(const std::string& path) {
34✔
669
   const std::string fsname = Test::data_file(path);
34✔
670
   std::ifstream file(fsname.c_str(), std::ios::binary);
34✔
671
   if(!file.good()) {
34✔
672
      throw Test_Error("Error reading from " + fsname);
×
673
   }
674

675
   std::vector<uint8_t> contents;
34✔
676

677
   while(file.good()) {
74✔
678
      std::vector<uint8_t> buf(4096);
40✔
679
      file.read(reinterpret_cast<char*>(buf.data()), buf.size());
40✔
680
      const size_t got = static_cast<size_t>(file.gcount());
40✔
681

682
      if(got == 0 && file.eof()) {
40✔
683
         break;
684
      }
685

686
      contents.insert(contents.end(), buf.data(), buf.data() + got);
40✔
687
   }
40✔
688

689
   return contents;
68✔
690
}
68✔
691

692
// static member variables of Test
693

694
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
695
Test_Options Test::m_opts;
696
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
697
std::shared_ptr<Botan::RandomNumberGenerator> Test::m_test_rng;
698

699
//static
700
void Test::set_test_options(const Test_Options& opts) {
1✔
701
   m_opts = opts;
1✔
702
}
1✔
703

704
//static
705
void Test::set_test_rng(std::shared_ptr<Botan::RandomNumberGenerator> rng) {
1✔
706
   m_test_rng = std::move(rng);
1✔
707
}
1✔
708

709
//static
710
std::string Test::data_file(const std::string& what) {
255✔
711
   return Test::data_dir() + "/" + what;
510✔
712
}
713

714
//static
715
std::string Test::data_file_as_temporary_copy(const std::string& what) {
1✔
716
   auto tmp_basename = what;
1✔
717
   std::replace(tmp_basename.begin(), tmp_basename.end(), '/', '_');
1✔
718
   auto temp_file = temp_file_name("tmp-" + tmp_basename);
1✔
719
   if(temp_file.empty()) {
1✔
720
      return "";
×
721
   }
722
   if(!Test::copy_file(data_file(what), temp_file)) {
2✔
723
      return "";
×
724
   }
725
   return temp_file;
2✔
726
}
2✔
727

728
//static
729
std::vector<std::string> Test::provider_filter(const std::vector<std::string>& in) {
42,125✔
730
   if(m_opts.provider().empty()) {
42,125✔
731
      return in;
42,125✔
732
   }
733
   for(auto&& provider : in) {
×
734
      if(provider == m_opts.provider()) {
×
735
         return std::vector<std::string>{provider};
×
736
      }
737
   }
738
   return std::vector<std::string>{};
42,125✔
739
}
740

741
//static
742
Botan::RandomNumberGenerator& Test::rng() {
540,044✔
743
   if(!m_test_rng) {
540,044✔
744
      throw Test_Error("Test requires RNG but no RNG set with Test::set_test_rng");
×
745
   }
746
   return *m_test_rng;
540,044✔
747
}
748

749
//static
750
std::shared_ptr<Botan::RandomNumberGenerator> Test::rng_as_shared() {
109✔
751
   if(!m_test_rng) {
109✔
752
      throw Test_Error("Test requires RNG but no RNG set with Test::set_test_rng");
×
753
   }
754
   return m_test_rng;
109✔
755
}
756

757
std::string Test::random_password() {
108✔
758
   const size_t len = 1 + Test::rng().next_byte() % 32;
108✔
759
   return Botan::hex_encode(Test::rng().random_vec(len));
216✔
760
}
761

762
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(const std::string& key) const {
12✔
763
   auto i = m_vars.find(key);
12✔
764
   if(i == m_vars.end()) {
12✔
765
      throw Test_Error("Test missing variable " + key);
×
766
   }
767

768
   std::vector<std::vector<uint8_t>> bin_list;
12✔
769

770
   for(auto&& part : Botan::split_on(i->second, ',')) {
62✔
771
      try {
50✔
772
         bin_list.push_back(Botan::hex_decode(part));
100✔
773
      } catch(std::exception& e) {
×
774
         std::ostringstream oss;
×
775
         oss << "Bad input '" << part << "'"
×
776
             << " in binary list key " << key << " - " << e.what();
×
777
         throw Test_Error(oss.str());
×
778
      }
×
779
   }
12✔
780

781
   return bin_list;
12✔
782
}
×
783

784
std::vector<uint8_t> VarMap::get_req_bin(const std::string& key) const {
131,174✔
785
   auto i = m_vars.find(key);
131,174✔
786
   if(i == m_vars.end()) {
131,174✔
787
      throw Test_Error("Test missing variable " + key);
×
788
   }
789

790
   try {
131,174✔
791
      return Botan::hex_decode(i->second);
131,174✔
792
   } catch(std::exception& e) {
×
793
      std::ostringstream oss;
×
794
      oss << "Bad input '" << i->second << "'"
×
795
          << " for key " << key << " - " << e.what();
×
796
      throw Test_Error(oss.str());
×
797
   }
×
798
}
799

800
std::string VarMap::get_opt_str(const std::string& key, const std::string& def_value) const {
13,564✔
801
   auto i = m_vars.find(key);
13,564✔
802
   if(i == m_vars.end()) {
13,564✔
803
      return def_value;
13,513✔
804
   }
805
   return i->second;
51✔
806
}
807

808
bool VarMap::get_req_bool(const std::string& key) const {
19✔
809
   auto i = m_vars.find(key);
19✔
810
   if(i == m_vars.end()) {
19✔
811
      throw Test_Error("Test missing variable " + key);
×
812
   }
813

814
   if(i->second == "true") {
19✔
815
      return true;
816
   } else if(i->second == "false") {
11✔
817
      return false;
818
   } else {
819
      throw Test_Error("Invalid boolean for key '" + key + "' value '" + i->second + "'");
×
820
   }
821
}
822

823
size_t VarMap::get_req_sz(const std::string& key) const {
4,368✔
824
   auto i = m_vars.find(key);
4,368✔
825
   if(i == m_vars.end()) {
4,368✔
826
      throw Test_Error("Test missing variable " + key);
×
827
   }
828
   return Botan::to_u32bit(i->second);
4,368✔
829
}
830

831
uint8_t VarMap::get_req_u8(const std::string& key) const {
17✔
832
   const size_t s = this->get_req_sz(key);
17✔
833
   if(s > 256) {
17✔
834
      throw Test_Error("Invalid " + key + " expected uint8_t got " + std::to_string(s));
×
835
   }
836
   return static_cast<uint8_t>(s);
17✔
837
}
838

839
uint32_t VarMap::get_req_u32(const std::string& key) const {
3✔
840
   return static_cast<uint32_t>(get_req_sz(key));
3✔
841
}
842

843
uint64_t VarMap::get_req_u64(const std::string& key) const {
15✔
844
   auto i = m_vars.find(key);
15✔
845
   if(i == m_vars.end()) {
15✔
846
      throw Test_Error("Test missing variable " + key);
×
847
   }
848
   try {
15✔
849
      return std::stoull(i->second);
15✔
850
   } catch(std::exception&) {
×
851
      throw Test_Error("Invalid u64 value '" + i->second + "'");
×
852
   }
×
853
}
854

855
size_t VarMap::get_opt_sz(const std::string& key, const size_t def_value) const {
26,987✔
856
   auto i = m_vars.find(key);
26,987✔
857
   if(i == m_vars.end()) {
26,987✔
858
      return def_value;
859
   }
860
   return Botan::to_u32bit(i->second);
11,934✔
861
}
862

863
uint64_t VarMap::get_opt_u64(const std::string& key, const uint64_t def_value) const {
3,538✔
864
   auto i = m_vars.find(key);
3,538✔
865
   if(i == m_vars.end()) {
3,538✔
866
      return def_value;
867
   }
868
   try {
641✔
869
      return std::stoull(i->second);
3,538✔
870
   } catch(std::exception&) {
×
871
      throw Test_Error("Invalid u64 value '" + i->second + "'");
×
872
   }
×
873
}
874

875
std::vector<uint8_t> VarMap::get_opt_bin(const std::string& key) const {
36,993✔
876
   auto i = m_vars.find(key);
36,993✔
877
   if(i == m_vars.end()) {
36,993✔
878
      return std::vector<uint8_t>();
36,993✔
879
   }
880

881
   try {
11,204✔
882
      return Botan::hex_decode(i->second);
11,204✔
883
   } catch(std::exception&) {
×
884
      throw Test_Error("Test invalid hex input '" + i->second + "'" + +" for key " + key);
×
885
   }
×
886
}
887

888
std::string VarMap::get_req_str(const std::string& key) const {
39,580✔
889
   auto i = m_vars.find(key);
39,580✔
890
   if(i == m_vars.end()) {
39,580✔
891
      throw Test_Error("Test missing variable " + key);
×
892
   }
893
   return i->second;
39,580✔
894
}
895

896
#if defined(BOTAN_HAS_BIGINT)
897
Botan::BigInt VarMap::get_req_bn(const std::string& key) const {
36,605✔
898
   auto i = m_vars.find(key);
36,605✔
899
   if(i == m_vars.end()) {
36,605✔
900
      throw Test_Error("Test missing variable " + key);
×
901
   }
902

903
   try {
36,605✔
904
      return Botan::BigInt(i->second);
36,605✔
905
   } catch(std::exception&) {
×
906
      throw Test_Error("Test invalid bigint input '" + i->second + "' for key " + key);
×
907
   }
×
908
}
909

910
Botan::BigInt VarMap::get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const
80✔
911

912
{
913
   auto i = m_vars.find(key);
80✔
914
   if(i == m_vars.end()) {
80✔
915
      return def_value;
104✔
916
   }
917

918
   try {
56✔
919
      return Botan::BigInt(i->second);
56✔
920
   } catch(std::exception&) {
×
921
      throw Test_Error("Test invalid bigint input '" + i->second + "' for key " + key);
×
922
   }
×
923
}
924
#endif
925

926
Text_Based_Test::Text_Based_Test(const std::string& data_src,
152✔
927
                                 const std::string& required_keys_str,
928
                                 const std::string& optional_keys_str) :
152✔
929
      m_data_src(data_src) {
456✔
930
   if(required_keys_str.empty()) {
152✔
931
      throw Test_Error("Invalid test spec");
×
932
   }
933

934
   std::vector<std::string> required_keys = Botan::split_on(required_keys_str, ',');
152✔
935
   std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
152✔
936

937
   m_required_keys.insert(required_keys.begin(), required_keys.end());
152✔
938
   m_optional_keys.insert(optional_keys.begin(), optional_keys.end());
152✔
939
   m_output_key = required_keys.at(required_keys.size() - 1);
152✔
940
}
152✔
941

942
std::string Text_Based_Test::get_next_line() {
141,386✔
943
   while(true) {
141,614✔
944
      if(m_cur == nullptr || m_cur->good() == false) {
141,614✔
945
         if(m_srcs.empty()) {
388✔
946
            if(m_first) {
304✔
947
               const std::string full_path = Test::data_dir() + "/" + m_data_src;
152✔
948
               if(full_path.find(".vec") != std::string::npos) {
152✔
949
                  m_srcs.push_back(full_path);
140✔
950
               } else {
951
                  const auto fs = Botan::get_files_recursive(full_path);
12✔
952
                  m_srcs.assign(fs.begin(), fs.end());
12✔
953
                  if(m_srcs.empty()) {
12✔
954
                     throw Test_Error("Error reading test data dir " + full_path);
×
955
                  }
956
               }
12✔
957

958
               m_first = false;
152✔
959
            } else {
152✔
960
               return "";  // done
152✔
961
            }
962
         }
963

964
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
320✔
965
         m_cur_src_name = m_srcs[0];
236✔
966

967
         // Reinit cpuid on new file if needed
968
         if(m_cpu_flags.empty() == false) {
236✔
969
            m_cpu_flags.clear();
12✔
970
            Botan::CPUID::initialize();
12✔
971
         }
972

973
         if(!m_cur->good()) {
236✔
974
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
975
         }
976

977
         m_srcs.pop_front();
236✔
978
      }
979

980
      while(m_cur->good()) {
205,806✔
981
         std::string line;
205,578✔
982
         std::getline(*m_cur, line);
205,578✔
983

984
         if(line.empty()) {
205,578✔
985
            continue;
50,828✔
986
         }
987

988
         if(line[0] == '#') {
154,750✔
989
            if(line.compare(0, 6, "#test ") == 0) {
13,532✔
990
               return line;
16✔
991
            } else {
992
               continue;
13,516✔
993
            }
994
         }
995

996
         return line;
282,452✔
997
      }
205,578✔
998
   }
999
}
1000

1001
namespace {
1002

1003
// strips leading and trailing but not internal whitespace
1004
std::string strip_ws(const std::string& in) {
281,214✔
1005
   const char* whitespace = " ";
281,214✔
1006

1007
   const auto first_c = in.find_first_not_of(whitespace);
281,214✔
1008
   if(first_c == std::string::npos) {
281,214✔
1009
      return "";
977✔
1010
   }
1011

1012
   const auto last_c = in.find_last_not_of(whitespace);
280,237✔
1013

1014
   return in.substr(first_c, last_c - first_c + 1);
280,237✔
1015
}
1016

1017
std::vector<uint64_t> parse_cpuid_bits(const std::vector<std::string>& tok) {
16✔
1018
   std::vector<uint64_t> bits;
16✔
1019
   for(size_t i = 1; i < tok.size(); ++i) {
55✔
1020
      const std::vector<Botan::CPUID::CPUID_bits> more = Botan::CPUID::bit_from_string(tok[i]);
39✔
1021
      bits.insert(bits.end(), more.begin(), more.end());
39✔
1022
   }
39✔
1023

1024
   return bits;
16✔
1025
}
×
1026

1027
}  // namespace
1028

1029
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) {
43,899✔
1030
   return false;
43,899✔
1031
}
1032

1033
std::vector<Test::Result> Text_Based_Test::run() {
152✔
1034
   std::vector<Test::Result> results;
152✔
1035

1036
   std::string header, header_or_name = m_data_src;
152✔
1037
   VarMap vars;
152✔
1038
   size_t test_cnt = 0;
152✔
1039

1040
   while(true) {
141,386✔
1041
      const std::string line = get_next_line();
141,386✔
1042
      if(line.empty())  // EOF
141,386✔
1043
      {
1044
         break;
1045
      }
1046

1047
      if(line.compare(0, 6, "#test ") == 0) {
141,234✔
1048
         std::vector<std::string> pragma_tokens = Botan::split_on(line.substr(6), ' ');
16✔
1049

1050
         if(pragma_tokens.empty()) {
16✔
1051
            throw Test_Error("Empty pragma found in " + m_cur_src_name);
×
1052
         }
1053

1054
         if(pragma_tokens[0] != "cpuid") {
16✔
1055
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_cur_src_name);
×
1056
         }
1057

1058
         if(!Test_Registry::instance().needs_serialization(this->test_name())) {
16✔
1059
            throw Test_Error(Botan::fmt("'{}' used cpuid control but is not serialized", this->test_name()));
×
1060
         }
1061

1062
         m_cpu_flags = parse_cpuid_bits(pragma_tokens);
16✔
1063

1064
         continue;
16✔
1065
      } else if(line[0] == '#') {
141,234✔
1066
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_cur_src_name);
×
1067
      }
1068

1069
      if(line[0] == '[' && line[line.size() - 1] == ']') {
141,218✔
1070
         header = line.substr(1, line.size() - 2);
611✔
1071
         header_or_name = header;
611✔
1072
         test_cnt = 0;
611✔
1073
         vars.clear();
611✔
1074
         continue;
611✔
1075
      }
1076

1077
      const std::string test_id = "test " + std::to_string(test_cnt);
140,607✔
1078

1079
      auto equal_i = line.find_first_of('=');
140,607✔
1080

1081
      if(equal_i == std::string::npos) {
140,607✔
1082
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1083
         continue;
×
1084
      }
1085

1086
      std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
140,607✔
1087
      std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
140,607✔
1088

1089
      if(!m_required_keys.contains(key) && !m_optional_keys.contains(key)) {
140,607✔
1090
         auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key));
×
1091
         results.push_back(r);
×
1092
      }
×
1093

1094
      vars.add(key, val);
140,607✔
1095

1096
      if(key == m_output_key) {
140,607✔
1097
         try {
43,976✔
1098
            for(auto& req_key : m_required_keys) {
225,980✔
1099
               if(!vars.has_key(req_key)) {
364,008✔
1100
                  auto r =
×
1101
                     Test::Result::Failure(header_or_name, Botan::fmt("{} missing required key {}", test_id, req_key));
×
1102
                  results.push_back(r);
×
1103
               }
×
1104
            }
1105

1106
            if(skip_this_test(header, vars)) {
43,976✔
1107
               continue;
×
1108
            }
1109

1110
            ++test_cnt;
43,976✔
1111

1112
            uint64_t start = Test::timestamp();
43,976✔
1113

1114
            Test::Result result = run_one_test(header, vars);
43,976✔
1115
            if(!m_cpu_flags.empty()) {
43,976✔
1116
               for(const auto& cpuid_u64 : m_cpu_flags) {
17,911✔
1117
                  Botan::CPUID::CPUID_bits cpuid_bit = static_cast<Botan::CPUID::CPUID_bits>(cpuid_u64);
12,320✔
1118
                  if(Botan::CPUID::has_cpuid_bit(cpuid_bit)) {
12,320✔
1119
                     Botan::CPUID::clear_cpuid_bit(cpuid_bit);
9,672✔
1120
                     // now re-run the test
1121
                     result.merge(run_one_test(header, vars));
9,672✔
1122
                  }
1123
               }
1124
               Botan::CPUID::initialize();
5,591✔
1125
            }
1126
            result.set_ns_consumed(Test::timestamp() - start);
43,976✔
1127

1128
            if(result.tests_failed()) {
43,976✔
1129
               std::ostringstream oss;
×
1130
               oss << "Test # " << test_cnt << " ";
×
1131
               if(!header.empty()) {
×
1132
                  oss << header << " ";
×
1133
               }
1134
               oss << "failed ";
×
1135

1136
               for(const auto& k : m_required_keys) {
×
1137
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1138
               }
1139

1140
               result.test_note(oss.str());
×
1141
            }
×
1142
            results.push_back(result);
43,976✔
1143
         } catch(std::exception& e) {
43,976✔
1144
            std::ostringstream oss;
×
1145
            oss << "Test # " << test_cnt << " ";
×
1146
            if(!header.empty()) {
×
1147
               oss << header << " ";
×
1148
            }
1149

1150
            for(const auto& k : m_required_keys) {
×
1151
               oss << k << "=" << vars.get_req_str(k) << " ";
×
1152
            }
1153

1154
            oss << "failed with exception '" << e.what() << "'";
×
1155

1156
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1157
         }
×
1158

1159
         if(clear_between_callbacks()) {
43,976✔
1160
            vars.clear();
170,176✔
1161
         }
1162
      }
1163
   }
262,904✔
1164

1165
   if(results.empty()) {
152✔
1166
      return results;
1167
   }
1168

1169
   try {
152✔
1170
      std::vector<Test::Result> final_tests = run_final_tests();
152✔
1171
      results.insert(results.end(), final_tests.begin(), final_tests.end());
152✔
1172
   } catch(std::exception& e) {
152✔
1173
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1174
   }
×
1175

1176
   m_first = true;
152✔
1177

1178
   return results;
152✔
1179
}
295✔
1180

1181
std::map<std::string, std::string> Test_Options::report_properties() const {
1✔
1182
   std::map<std::string, std::string> result;
1✔
1183

1184
   for(const auto& prop : m_report_properties) {
3✔
1185
      const auto colon = prop.find(':');
2✔
1186
      // props without a colon separator or without a name are not allowed
1187
      if(colon == std::string::npos || colon == 0) {
2✔
1188
         throw Test_Error("--report-properties should be of the form <key>:<value>,<key>:<value>,...");
×
1189
      }
1190

1191
      result.insert_or_assign(prop.substr(0, colon), prop.substr(colon + 1, prop.size() - colon - 1));
4✔
1192
   }
1193

1194
   return result;
1✔
1195
}
×
1196

1197
}  // namespace Botan_Tests
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc