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

randombit / botan / 27806188297

18 Jun 2026 04:12PM UTC coverage: 89.37% (-0.03%) from 89.397%
27806188297

push

github

web-flow
Merge pull request #5677 from randombit/jack/oid-names

Add OID::registered_name

111637 of 124915 relevant lines covered (89.37%)

10895907.86 hits per line

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

81.19
/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/rng.h>
11
#include <botan/symkey.h>
12
#include <botan/internal/filesystem.h>
13
#include <botan/internal/fmt.h>
14
#include <botan/internal/loadstor.h>
15
#include <botan/internal/parsing.h>
16
#include <botan/internal/stl_util.h>
17
#include <botan/internal/target_info.h>
18
#include <chrono>
19
#include <deque>
20
#include <fstream>
21
#include <iomanip>
22
#include <set>
23
#include <sstream>
24
#include <unordered_set>
25

26
#if defined(BOTAN_HAS_BIGINT)
27
   #include <botan/bigint.h>
28
#endif
29

30
#if defined(BOTAN_HAS_CPUID)
31
   #include <botan/internal/cpuid.h>
32
#endif
33

34
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
35
   #include <botan/ec_point.h>
36
#endif
37

38
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
39
   #include <stdlib.h>
40
   #include <unistd.h>
41
#endif
42

43
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)
44
   #include <version>
45
   #if defined(__cpp_lib_filesystem)
46
      #include <filesystem>
47
   #endif
48
#endif
49

50
#if defined(BOTAN_HAS_ECC_GROUP)
51
   #include <botan/ec_group.h>
52
#endif
53

54
namespace Botan_Tests {
55

56
Test_Error::Test_Error(std::string_view what) : std::runtime_error(std::string(what)) {}
2✔
57

58
Test::Test() = default;
459✔
59

60
Test::~Test() = default;
607✔
61

62
Test::Result::Result(std::string_view who) : m_who(who), m_timestamp(Test::timestamp()) {}
83,672✔
63

64
Test::Result::Result(std::string_view who, const std::vector<Result>& downstream_results) : Result(who) {
14✔
65
   for(const auto& result : downstream_results) {
82✔
66
      merge(result, true /* ignore non-matching test names */);
68✔
67
   }
68
}
14✔
69

70
void Test::Result::merge(const Result& other, bool ignore_test_name) {
128,733✔
71
   if(who() != other.who()) {
128,733✔
72
      if(!ignore_test_name) {
73✔
73
         throw Test_Error("Merging tests from different sources");
×
74
      }
75

76
      // When deliberately merging results with different names, the code location is
77
      // likely inconsistent and must be discarded.
78
      m_where.reset();
73✔
79
   } else {
80
      m_where = other.m_where;
128,660✔
81
   }
82

83
   m_timestamp = std::min(m_timestamp, other.m_timestamp);
128,733✔
84
   m_ns_taken += other.m_ns_taken;
128,733✔
85
   m_tests_passed += other.m_tests_passed;
128,733✔
86
   m_fail_log.insert(m_fail_log.end(), other.m_fail_log.begin(), other.m_fail_log.end());
128,733✔
87
   m_log.insert(m_log.end(), other.m_log.begin(), other.m_log.end());
128,733✔
88
}
128,733✔
89

90
void Test::Result::start_timer() {
1,037✔
91
   if(m_started == 0) {
1,037✔
92
      m_started = Test::timestamp();
2,074✔
93
   }
94
}
1,037✔
95

96
void Test::Result::end_timer() {
1,064✔
97
   if(m_started > 0) {
1,064✔
98
      m_ns_taken += Test::timestamp() - m_started;
2,072✔
99
      m_started = 0;
1,036✔
100
   }
101
}
1,064✔
102

103
void Test::Result::test_note(std::string_view note, std::span<const uint8_t> context) {
12✔
104
   return test_note(note, Botan::hex_encode(context));
24✔
105
}
106

107
void Test::Result::test_note(std::string_view note, std::string_view context) {
2,147✔
108
   m_log.emplace_back(Botan::fmt("{} {}: {}", who(), note, context));
2,147✔
109
}
2,147✔
110

111
void Test::Result::test_note(std::string_view note) {
644✔
112
   m_log.emplace_back(Botan::fmt("{} {}", who(), note));
644✔
113
}
644✔
114

115
void Test::Result::note_missing(std::string_view whatever_sv) {
290✔
116
   static std::set<std::string> s_already_seen;
290✔
117

118
   const std::string whatever(whatever_sv);
290✔
119
   if(!s_already_seen.contains(whatever)) {
290✔
120
      test_note(Botan::fmt("Skipping tests due to missing {}", whatever));
11✔
121
      s_already_seen.insert(whatever);
290✔
122
   }
123
}
290✔
124

125
void Test::Result::require(std::string_view what, bool expr) {
323✔
126
   if(!test_is_true(what, expr)) {
323✔
127
      throw Test_Aborted(Botan::fmt("Test aborted, because required condition was not met: {}", what));
×
128
   }
129
}
323✔
130

131
Test::Result::ThrowExpectations::~ThrowExpectations() {
119,446✔
132
   BOTAN_ASSERT_NOMSG(m_consumed);
119,446✔
133
}
232,482✔
134

135
void Test::Result::ThrowExpectations::assert_that_success_is_not_expected() const {
113,036✔
136
   BOTAN_ASSERT_NOMSG(!m_expect_success);
112,817✔
137
}
112,817✔
138

139
Test::Result::ThrowExpectations& Test::Result::ThrowExpectations::expect_success() {
1,654✔
140
   BOTAN_ASSERT_NOMSG(!m_expected_message && !m_expected_exception_check_fn);
1,654✔
141
   m_expect_success = true;
1,654✔
142
   return *this;
1,654✔
143
}
144

145
Test::Result::ThrowExpectations& Test::Result::ThrowExpectations::expect_message(std::string_view message) {
219✔
146
   assert_that_success_is_not_expected();
219✔
147
   m_expected_message = message;
219✔
148
   return *this;
219✔
149
}
150

151
bool Test::Result::ThrowExpectations::check(std::string_view test_name, Test::Result& result) {
119,446✔
152
   m_consumed = true;
119,446✔
153

154
   try {
119,446✔
155
      m_fn();
119,446✔
156
      if(!m_expect_success) {
1,655✔
157
         return result.test_failure(Botan::fmt("{} failed to throw expected exception", test_name));
2✔
158
      }
159
   } catch(const std::exception& ex) {
117,791✔
160
      if(m_expect_success) {
117,789✔
161
         return result.test_failure(Botan::fmt("{} threw unexpected exception: {}", test_name, ex.what()));
1✔
162
      }
163
      if(m_expected_exception_check_fn && !m_expected_exception_check_fn(std::current_exception())) {
343,422✔
164
         return result.test_failure(Botan::fmt("{} threw unexpected exception: {}", test_name, ex.what()));
2✔
165
      }
166
      if(m_expected_message.has_value()) {
117,786✔
167
         const std::string ex_msg = std::string(ex.what());
216✔
168

169
         // TODO(C++23) std::string::contains
170
         if(ex_msg.find(m_expected_message.value()) == std::string::npos) {
216✔
171
            return result.test_failure(Botan::fmt("{} threw exception with unexpected message (expected {} got {})",
1✔
172
                                                  test_name,
173
                                                  m_expected_message.value(),
1✔
174
                                                  ex_msg));
175
         }
176
      }
216✔
177
   } catch(...) {
117,791✔
178
      if(m_expect_success || m_expected_exception_check_fn || m_expected_message.has_value()) {
2✔
179
         return result.test_failure(Botan::fmt("{} threw unexpected unknown exception", test_name));
1✔
180
      }
181
   }
2✔
182

183
   return result.test_success();
119,439✔
184
}
185

186
bool Test::Result::test_throws(std::string_view what, std::function<void()> fn) {
4,771✔
187
   return ThrowExpectations(std::move(fn)).check(what, *this);
14,313✔
188
}
189

190
bool Test::Result::test_throws(std::string_view what, std::string_view expected, std::function<void()> fn) {
204✔
191
   return ThrowExpectations(std::move(fn)).expect_message(expected).check(what, *this);
612✔
192
}
193

194
bool Test::Result::test_no_throw(std::string_view what, std::function<void()> fn) {
1,654✔
195
   return ThrowExpectations(std::move(fn)).expect_success().check(what, *this);
4,962✔
196
}
197

198
bool Test::Result::test_success(std::string_view note) {
3,917,289✔
199
   if(Test::options().log_success()) {
3,917,273✔
200
      test_note(note);
×
201
   }
202
   ++m_tests_passed;
3,917,289✔
203
   return true;
119,439✔
204
}
205

206
bool Test::Result::test_failure(std::string_view what, std::string_view error) {
2✔
207
   return test_failure(Botan::fmt("{} {} with error {}", who(), what, error));
2✔
208
}
209

210
void Test::Result::test_failure(std::string_view what, const uint8_t buf[], size_t buf_len) {
×
211
   return test_failure(what, {buf, buf_len});
×
212
}
213

214
void Test::Result::test_failure(std::string_view what, std::span<const uint8_t> context) {
1✔
215
   test_failure(Botan::fmt("{} {} with value {}", who(), what, Botan::hex_encode(context)));
2✔
216
}
1✔
217

218
bool Test::Result::test_failure(const char* err) {
×
219
   return test_failure(std::string_view(err));
×
220
}
221

222
bool Test::Result::test_failure(std::string_view err) {
1✔
223
   return test_failure(std::string(err));
1✔
224
}
225

226
bool Test::Result::test_failure(std::string err) {
24✔
227
   m_fail_log.push_back(std::move(err));
24✔
228

229
   if(Test::options().abort_on_first_fail() && m_who != "Failing Test") {
24✔
230
      std::abort();
×
231
   }
232
   return false;
24✔
233
}
234

235
namespace {
236

237
bool same_contents(std::span<const uint8_t> x, std::span<const uint8_t> y) {
349,850✔
238
   if(x.size() != y.size()) {
1,444✔
239
      return false;
240
   }
241
   if(x.empty()) {
349,849✔
242
      return true;
243
   }
244

245
   return std::memcmp(x.data(), y.data(), x.size()) == 0;
348,055✔
246
}
247

248
}  // namespace
249

250
bool Test::Result::test_bin_ne(std::string_view what,
3,360✔
251
                               std::span<const uint8_t> produced,
252
                               std::span<const uint8_t> expected) {
253
   if(produced.size() == expected.size() && same_contents(produced, expected)) {
4,804✔
254
      return test_failure(Botan::fmt("{} {} produced matching bytes", who(), what));
1✔
255
   }
256
   return test_success();
3,359✔
257
}
258

259
bool Test::Result::test_bin_eq(std::string_view what,
617✔
260
                               std::span<const uint8_t> produced,
261
                               std::string_view expected_hex) {
262
   const std::vector<uint8_t> expected = Botan::hex_decode(expected_hex);
617✔
263
   return test_bin_eq(what, produced, expected);
617✔
264
}
617✔
265

266
bool Test::Result::test_bin_eq(std::string_view what,
348,406✔
267
                               std::span<const uint8_t> produced,
268
                               std::span<const uint8_t> expected) {
269
   if(same_contents(produced, expected)) {
695,017✔
270
      return test_success();
348,405✔
271
   }
272

273
   std::ostringstream err;
1✔
274

275
   err << who();
1✔
276

277
   err << " unexpected result for " << what;
1✔
278

279
   if(produced.size() != expected.size()) {
1✔
280
      err << " produced " << produced.size() << " bytes expected " << expected.size();
1✔
281
   }
282

283
   std::vector<uint8_t> xor_diff(std::min(produced.size(), expected.size()));
2✔
284
   size_t bytes_different = 0;
1✔
285

286
   for(size_t i = 0; i != xor_diff.size(); ++i) {
4✔
287
      xor_diff[i] = produced[i] ^ expected[i];
3✔
288
      if(xor_diff[i] > 0) {
3✔
289
         bytes_different++;
3✔
290
      }
291
   }
292

293
   err << "\nProduced: " << Botan::hex_encode(produced) << "\nExpected: " << Botan::hex_encode(expected);
1✔
294

295
   if(bytes_different > 0) {
1✔
296
      err << "\nXOR Diff: " << Botan::hex_encode(xor_diff);
1✔
297
   }
298

299
   return test_failure(err.str());
1✔
300
}
1✔
301

302
bool Test::Result::test_str_not_empty(std::string_view what, std::string_view produced) {
39,448✔
303
   if(produced.empty()) {
39,448✔
304
      return test_failure(what, "was empty");
1✔
305
   } else {
306
      return test_success();
39,447✔
307
   }
308
}
309

310
bool Test::Result::test_str_eq(std::string_view what, std::string_view produced, std::string_view expected) {
78,432✔
311
   if(produced == expected) {
78,432✔
312
      return test_success();
78,432✔
313
   } else {
314
      return test_failure(Botan::fmt("Assertion failure in {} {}: '{}' == '{}'", who(), what, produced, expected));
×
315
   }
316
}
317

318
bool Test::Result::test_str_ne(std::string_view what, std::string_view str1, std::string_view str2) {
17✔
319
   if(str1 != str2) {
17✔
320
      return test_success(Botan::fmt("{} != {}", str1, str2));
16✔
321
   } else {
322
      return test_failure(Botan::fmt("{} {} unexpectedly produced matching strings {}", who(), what, str1));
1✔
323
   }
324
}
325

326
bool Test::Result::test_i16_eq(std::string_view what, int16_t produced, int16_t expected) {
1,025✔
327
   return test_i32_eq(what, produced, expected);
1,025✔
328
}
329

330
bool Test::Result::test_i32_eq(std::string_view what, int32_t produced, int32_t expected) {
1,026✔
331
   if(produced == expected) {
1,026✔
332
      return test_success();
1,026✔
333
   } else {
334
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} == {}", who(), what, produced, expected));
×
335
   }
336
}
337

338
bool Test::Result::test_u8_eq(uint8_t produced, uint8_t expected) {
214✔
339
   return test_sz_eq("comparison", produced, expected);
214✔
340
}
341

342
bool Test::Result::test_u8_eq(std::string_view what, uint8_t produced, uint8_t expected) {
161,609✔
343
   return test_sz_eq(what, produced, expected);
161,609✔
344
}
345

346
bool Test::Result::test_u16_eq(uint16_t produced, uint16_t expected) {
40✔
347
   return test_sz_eq("comparison", produced, expected);
40✔
348
}
349

350
bool Test::Result::test_u16_eq(std::string_view what, uint16_t produced, uint16_t expected) {
66,790✔
351
   return test_sz_eq(what, produced, expected);
66,790✔
352
}
353

354
bool Test::Result::test_u32_eq(uint32_t produced, uint32_t expected) {
16✔
355
   return test_sz_eq("comparison", produced, expected);
16✔
356
}
357

358
bool Test::Result::test_u32_eq(std::string_view what, uint32_t produced, uint32_t expected) {
4,218✔
359
   return test_sz_eq(what, produced, expected);
4,218✔
360
}
361

362
bool Test::Result::test_u64_eq(uint64_t produced, uint64_t expected) {
13✔
363
   return test_u64_eq("comparison", produced, expected);
13✔
364
}
365

366
bool Test::Result::test_u64_eq(std::string_view what, uint64_t produced, uint64_t expected) {
1,571✔
367
   if(produced == expected) {
1,571✔
368
      return test_success();
1,571✔
369
   } else {
370
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} == {}", who(), what, produced, expected));
×
371
   }
372
}
373

374
bool Test::Result::test_u64_lt(std::string_view what, uint64_t produced, uint64_t expected) {
2✔
375
   if(produced < expected) {
2✔
376
      return test_success();
2✔
377
   } else {
378
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} < {}", who(), what, produced, expected));
×
379
   }
380
}
381

382
bool Test::Result::test_sz_eq(std::string_view what, size_t produced, size_t expected) {
310,138✔
383
   if(produced == expected) {
310,138✔
384
      return test_success();
310,137✔
385
   } else {
386
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} == {}", who(), what, produced, expected));
1✔
387
   }
388
}
389

390
bool Test::Result::test_sz_ne(std::string_view what, size_t produced, size_t expected) {
119✔
391
   if(produced != expected) {
119✔
392
      return test_success();
118✔
393
   } else {
394
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} != {}", who(), what, produced, expected));
1✔
395
   }
396
}
397

398
bool Test::Result::test_sz_lt(std::string_view what, size_t produced, size_t expected) {
5,639✔
399
   if(produced < expected) {
5,639✔
400
      return test_success();
5,638✔
401
   } else {
402
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} < {}", who(), what, produced, expected));
1✔
403
   }
404
}
405

406
bool Test::Result::test_sz_lte(std::string_view what, size_t produced, size_t expected) {
1,021,636✔
407
   if(produced <= expected) {
1,021,636✔
408
      return test_success();
1,021,635✔
409
   } else {
410
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} <= {}", who(), what, produced, expected));
1✔
411
   }
412
}
413

414
bool Test::Result::test_sz_gt(std::string_view what, size_t produced, size_t expected) {
30,149✔
415
   if(produced > expected) {
30,149✔
416
      return test_success();
30,149✔
417
   } else {
418
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} > {}", who(), what, produced, expected));
×
419
   }
420
}
421

422
bool Test::Result::test_sz_gte(std::string_view what, size_t produced, size_t expected) {
1,141,359✔
423
   if(produced >= expected) {
1,141,359✔
424
      return test_success();
1,141,358✔
425
   } else {
426
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} >= {}", who(), what, produced, expected));
1✔
427
   }
428
}
429

430
bool Test::Result::test_opt_u8_eq(std::string_view what,
1,215✔
431
                                  std::optional<uint8_t> produced,
432
                                  std::optional<uint8_t> expected) {
433
   if(produced.has_value() and !expected.has_value()) {
1,215✔
434
      return test_failure(Botan::fmt("Assertion {} produced value {} but nullopt was expected", what, *produced));
×
435
   } else if(!produced.has_value() && expected.has_value()) {
1,215✔
436
      return test_failure(Botan::fmt("Assertion {} produced nullopt but {} was expected", what, *expected));
×
437
   } else if(produced.has_value() && expected.has_value()) {
1,215✔
438
      return test_u8_eq(what, *produced, *expected);
10✔
439
   } else {
440
      return test_success();
1,205✔
441
   }
442
}
443

444
bool Test::Result::test_opt_u64_eq(std::string_view what,
23✔
445
                                   std::optional<uint64_t> produced,
446
                                   std::optional<uint64_t> expected) {
447
   if(produced.has_value() and !expected.has_value()) {
23✔
448
      return test_failure(Botan::fmt("Assertion {} produced value {} but nullopt was expected", what, *produced));
×
449
   } else if(!produced.has_value() && expected.has_value()) {
23✔
450
      return test_failure(Botan::fmt("Assertion {} produced nullopt but {} was expected", what, *expected));
×
451
   } else if(produced.has_value() && expected.has_value()) {
23✔
452
      return test_u64_eq(what, *produced, *expected);
23✔
453
   } else {
454
      return test_success();
×
455
   }
456
}
457

458
bool Test::Result::test_opt_str_eq(std::string_view what,
13✔
459
                                   std::optional<std::string> produced,
460
                                   std::optional<std::string> expected) {
461
   if(produced.has_value() and !expected.has_value()) {
13✔
462
      return test_failure(Botan::fmt("Assertion {} produced value {} but nullopt was expected", what, *produced));
×
463
   } else if(!produced.has_value() && expected.has_value()) {
13✔
464
      return test_failure(Botan::fmt("Assertion {} produced nullopt but {} was expected", what, *expected));
×
465
   } else if(produced.has_value() && expected.has_value()) {
13✔
466
      return test_str_eq(what, *produced, *expected);
13✔
467
   } else {
468
      return test_success();
×
469
   }
470
}
471

472
#if defined(BOTAN_HAS_BIGINT)
473
bool Test::Result::test_bn_eq(std::string_view what, const BigInt& produced, const BigInt& expected) {
252,703✔
474
   if(produced == expected) {
252,703✔
475
      return test_success();
252,702✔
476
   } else {
477
      std::ostringstream err;
1✔
478
      err << who() << " " << what << " produced " << produced << " != expected value " << expected;
1✔
479
      return test_failure(err.str());
1✔
480
   }
1✔
481
}
482

483
bool Test::Result::test_bn_ne(std::string_view what, const BigInt& produced, const BigInt& expected) {
97✔
484
   if(produced != expected) {
97✔
485
      return test_success();
96✔
486
   } else {
487
      std::ostringstream err;
1✔
488
      err << who() << " " << what << " produced " << produced << " prohibited value";
1✔
489
      return test_failure(err.str());
1✔
490
   }
1✔
491
}
492
#endif
493

494
bool Test::Result::test_bool_eq(std::string_view what, bool produced, bool expected) {
446,269✔
495
   if(produced == expected) {
446,269✔
496
      return test_success();
446,269✔
497
   } else {
498
      if(expected == true) {
×
499
         return test_failure(Botan::fmt("Assertion failure in {}, {} was unexpectedly false", who(), what));
×
500
      } else {
501
         return test_failure(Botan::fmt("Assertion failure in {}, {} was unexpectedly true", who(), what));
×
502
      }
503
   }
504
}
505

506
bool Test::Result::test_is_true(std::string_view what, bool produced) {
301,622✔
507
   return test_bool_eq(what, produced, true);
301,622✔
508
}
509

510
bool Test::Result::test_is_false(std::string_view what, bool produced) {
136,953✔
511
   return test_bool_eq(what, produced, false);
136,953✔
512
}
513

514
bool Test::Result::test_rc_ok(std::string_view func, int rc) {
2,912✔
515
   if(rc != 0) {
2,912✔
516
      std::ostringstream err;
1✔
517
      err << m_who << " " << func << " unexpectedly failed with error code " << rc;
1✔
518
      return test_failure(err.str());
1✔
519
   }
1✔
520

521
   return test_success();
2,911✔
522
}
523

524
bool Test::Result::test_rc_fail(std::string_view func, std::string_view why, int rc) {
26✔
525
   if(rc == 0) {
26✔
526
      std::ostringstream err;
1✔
527
      err << m_who << " call to " << func << " unexpectedly succeeded expecting failure because " << why;
1✔
528
      return test_failure(err.str());
1✔
529
   }
1✔
530

531
   return test_success();
25✔
532
}
533

534
bool Test::Result::test_rc_init(std::string_view func, int rc) {
121✔
535
   if(rc == 0) {
121✔
536
      return test_success();
121✔
537
   } else {
538
      std::ostringstream msg;
×
539
      msg << m_who;
×
540
      msg << " " << func;
×
541

542
      // -40 is BOTAN_FFI_ERROR_NOT_IMPLEMENTED
543
      if(rc == -40) {
×
544
         msg << " returned not implemented";
×
545
      } else {
546
         msg << " unexpectedly failed with error code " << rc;
×
547
      }
548

549
      if(rc == -40) {
×
550
         this->test_note(msg.str());
×
551
      } else {
552
         this->test_failure(msg.str());
×
553
      }
554
      return false;
×
555
   }
×
556
}
557

558
bool Test::Result::test_rc(std::string_view func, int rc, int expected) {
450✔
559
   if(expected != rc) {
450✔
560
      std::ostringstream err;
1✔
561
      err << m_who;
1✔
562
      err << " call to " << func << " unexpectedly returned " << rc;
1✔
563
      err << " but expecting " << expected;
1✔
564
      return test_failure(err.str());
1✔
565
   }
1✔
566

567
   return test_success();
449✔
568
}
569

570
void Test::initialize(std::string test_name, CodeLocation location) {
459✔
571
   m_test_name = std::move(test_name);
459✔
572
   m_registration_location = location;
459✔
573
}
459✔
574

575
Botan::RandomNumberGenerator& Test::rng() const {
469,142✔
576
   if(!m_test_rng) {
469,142✔
577
      m_test_rng = Test::new_rng(m_test_name);
148✔
578
   }
579

580
   return *m_test_rng;
469,142✔
581
}
582

583
std::optional<std::string> Test::supported_ec_group_name(std::vector<std::string> preferred_groups) {
151✔
584
#if defined(BOTAN_HAS_ECC_GROUP)
585
   if(preferred_groups.empty()) {
151✔
586
      preferred_groups = {
149✔
587
         "secp256r1",
588
         "brainpool256r1",
589
         "secp384r1",
590
         "brainpool384r1",
591
         "secp521r1",
592
         "brainpool512r1",
593
      };
1,192✔
594
   }
595

596
   for(const auto& group : preferred_groups) {
151✔
597
      if(Botan::EC_Group::supports_named_group(group)) {
151✔
598
         return group;
151✔
599
      }
600
   }
601
#else
602
   BOTAN_UNUSED(preferred_groups);
603
#endif
604

605
   return std::nullopt;
×
606
}
298✔
607

608
std::vector<uint8_t> Test::mutate_vec(const std::vector<uint8_t>& v,
97,316✔
609
                                      Botan::RandomNumberGenerator& rng,
610
                                      bool maybe_resize,
611
                                      size_t min_offset) {
612
   std::vector<uint8_t> r = v;
97,316✔
613

614
   if(maybe_resize && (r.empty() || rng.next_byte() < 32)) {
110,951✔
615
      // TODO: occasionally truncate, insert at random index
616
      const size_t add = 1 + (rng.next_byte() % 16);
2,115✔
617
      r.resize(r.size() + add);
2,115✔
618
      rng.randomize(&r[r.size() - add], add);
2,115✔
619
   }
620

621
   if(r.size() > min_offset) {
97,316✔
622
      const size_t offset = std::max<size_t>(min_offset, rng.next_byte() % r.size());
95,778✔
623
      const uint8_t perturb = rng.next_nonzero_byte();
95,778✔
624
      r[offset] ^= perturb;
95,778✔
625
   }
626

627
   return r;
97,316✔
628
}
×
629

630
std::vector<std::string> Test::possible_providers(const std::string& /*alg*/) {
×
631
   return Test::provider_filter({"base"});
×
632
}
633

634
//static
635
std::string Test::format_time(uint64_t nanoseconds) {
1,506✔
636
   std::ostringstream o;
1,506✔
637

638
   if(nanoseconds > 1000000000) {
1,506✔
639
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000000.0 << " sec";
162✔
640
   } else {
641
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000.0 << " msec";
1,344✔
642
   }
643

644
   return o.str();
3,012✔
645
}
1,506✔
646

647
// TODO: this should move to `StdoutReporter`
648
std::string Test::Result::result_string() const {
3,068✔
649
   const bool verbose = Test::options().verbose();
3,068✔
650

651
   if(tests_run() == 0 && !verbose) {
3,068✔
652
      return "";
26✔
653
   }
654

655
   std::ostringstream report;
3,042✔
656

657
   report << who() << " ran ";
3,042✔
658

659
   if(tests_run() == 0) {
3,042✔
660
      report << "ZERO";
×
661
   } else {
662
      report << tests_run();
3,042✔
663
   }
664
   report << " tests";
3,042✔
665

666
   if(m_ns_taken > 0) {
3,042✔
667
      report << " in " << format_time(m_ns_taken);
3,010✔
668
   }
669

670
   if(tests_failed() > 0) {
3,042✔
671
      report << " " << tests_failed() << " FAILED";
24✔
672
   } else {
673
      report << " all ok";
3,018✔
674
   }
675

676
   report << "\n";
3,042✔
677

678
   for(size_t i = 0; i != m_fail_log.size(); ++i) {
3,066✔
679
      report << "Failure " << (i + 1) << ": " << m_fail_log[i];
24✔
680
      if(m_where) {
24✔
681
         report << " (at " << m_where->path << ":" << m_where->line << ")";
×
682
      }
683
      report << "\n";
24✔
684
   }
685

686
   if(!m_fail_log.empty() || tests_run() == 0 || verbose) {
3,042✔
687
      for(size_t i = 0; i != m_log.size(); ++i) {
24✔
688
         report << "Note " << (i + 1) << ": " << m_log[i] << "\n";
×
689
      }
690
   }
691

692
   return report.str();
3,042✔
693
}
3,042✔
694

695
namespace {
696

697
class Test_Registry {
698
   public:
699
      static Test_Registry& instance() {
1,405✔
700
         static Test_Registry registry;
1,406✔
701
         return registry;
1,405✔
702
      }
703

704
      void register_test(const std::string& category,
459✔
705
                         const std::string& name,
706
                         bool smoke_test,
707
                         bool needs_serialization,
708
                         std::function<std::unique_ptr<Test>()> maker_fn) {
709
         if(m_tests.contains(name)) {
459✔
710
            throw Test_Error("Duplicate registration of test '" + name + "'");
×
711
         }
712

713
         if(m_tests.contains(category)) {
459✔
714
            throw Test_Error("'" + category + "' cannot be used as category, test exists");
×
715
         }
716

717
         if(m_categories.contains(name)) {
459✔
718
            throw Test_Error("'" + name + "' cannot be used as test name, category exists");
×
719
         }
720

721
         if(smoke_test) {
459✔
722
            m_smoke_tests.push_back(name);
10✔
723
         }
724

725
         if(needs_serialization) {
459✔
726
            m_mutexed_tests.push_back(name);
22✔
727
         }
728

729
         m_tests.emplace(name, std::move(maker_fn));
459✔
730
         m_categories.emplace(category, name);
459✔
731
      }
459✔
732

733
      std::unique_ptr<Test> get_test(const std::string& test_name) const {
459✔
734
         auto i = m_tests.find(test_name);
459✔
735
         if(i != m_tests.end()) {
459✔
736
            return i->second();
459✔
737
         }
738
         return nullptr;
×
739
      }
740

741
      std::vector<std::string> registered_tests() const {
×
742
         std::vector<std::string> s;
×
743
         s.reserve(m_tests.size());
×
744
         for(auto&& i : m_tests) {
×
745
            s.push_back(i.first);
×
746
         }
747
         return s;
×
748
      }
×
749

750
      std::vector<std::string> registered_test_categories() const {
×
751
         std::set<std::string> s;
×
752
         for(auto&& i : m_categories) {
×
753
            s.insert(i.first);
×
754
         }
755
         return std::vector<std::string>(s.begin(), s.end());
×
756
      }
×
757

758
      std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
1✔
759
                                                       const std::vector<std::string>& to_be_skipped) {
760
         std::vector<std::string> result;
1✔
761

762
         std::set<std::string> to_be_skipped_set(to_be_skipped.begin(), to_be_skipped.end());
1✔
763
         // TODO: this is O(n^2), but we have a relatively small number of tests.
764
         auto insert_if_not_exists_and_not_skipped = [&](const std::string& test_name) {
460✔
765
            if(!Botan::value_exists(result, test_name) && !to_be_skipped_set.contains(test_name)) {
918✔
766
               result.push_back(test_name);
449✔
767
            }
768
         };
460✔
769

770
         if(requested.empty()) {
1✔
771
            /*
772
            If nothing was requested on the command line, run everything. First
773
            run the "essentials" to smoke test, then everything else in
774
            alphabetical order.
775
            */
776
            result = m_smoke_tests;
1✔
777
            for(const auto& [test_name, _] : m_tests) {
460✔
778
               insert_if_not_exists_and_not_skipped(test_name);
459✔
779
            }
780
         } else {
781
            for(const auto& r : requested) {
×
782
               if(m_tests.contains(r)) {
×
783
                  insert_if_not_exists_and_not_skipped(r);
×
784
               } else if(auto elems = m_categories.equal_range(r); elems.first != m_categories.end()) {
×
785
                  for(; elems.first != elems.second; ++elems.first) {
×
786
                     insert_if_not_exists_and_not_skipped(elems.first->second);
×
787
                  }
788
               } else {
789
                  throw Test_Error("Unknown test suite or category: " + r);
×
790
               }
791
            }
792
         }
793

794
         return result;
1✔
795
      }
1✔
796

797
      bool needs_serialization(const std::string& test_name) const {
486✔
798
         return Botan::value_exists(m_mutexed_tests, test_name);
27✔
799
      }
800

801
   private:
802
      Test_Registry() = default;
1✔
803

804
   private:
805
      std::map<std::string, std::function<std::unique_ptr<Test>()>> m_tests;
806
      std::multimap<std::string, std::string> m_categories;
807
      std::vector<std::string> m_smoke_tests;
808
      std::vector<std::string> m_mutexed_tests;
809
};
810

811
}  // namespace
812

813
// static Test:: functions
814

815
//static
816
void Test::register_test(const std::string& category,
459✔
817
                         const std::string& name,
818
                         bool smoke_test,
819
                         bool needs_serialization,
820
                         std::function<std::unique_ptr<Test>()> maker_fn) {
821
   Test_Registry::instance().register_test(category, name, smoke_test, needs_serialization, std::move(maker_fn));
918✔
822
}
459✔
823

824
//static
825
uint64_t Test::timestamp() {
182,541✔
826
   auto now = std::chrono::system_clock::now().time_since_epoch();
182,541✔
827
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
2,073✔
828
}
829

830
//static
831
std::vector<Test::Result> Test::flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists) {
4✔
832
   std::vector<Test::Result> results;
4✔
833
   for(auto& result_list : result_lists) {
26✔
834
      for(auto& result : result_list) {
71✔
835
         results.emplace_back(std::move(result));
49✔
836
      }
837
   }
838
   return results;
4✔
839
}
×
840

841
//static
842
std::vector<std::string> Test::registered_tests() {
×
843
   return Test_Registry::instance().registered_tests();
×
844
}
845

846
//static
847
std::vector<std::string> Test::registered_test_categories() {
×
848
   return Test_Registry::instance().registered_test_categories();
×
849
}
850

851
//static
852
std::unique_ptr<Test> Test::get_test(const std::string& test_name) {
459✔
853
   return Test_Registry::instance().get_test(test_name);
459✔
854
}
855

856
//static
857
bool Test::test_needs_serialization(const std::string& test_name) {
459✔
858
   return Test_Registry::instance().needs_serialization(test_name);
459✔
859
}
860

861
//static
862
std::vector<std::string> Test::filter_registered_tests(const std::vector<std::string>& requested,
1✔
863
                                                       const std::vector<std::string>& to_be_skipped) {
864
   return Test_Registry::instance().filter_registered_tests(requested, to_be_skipped);
1✔
865
}
866

867
//static
868
std::string Test::temp_file_name(const std::string& basename) {
21✔
869
   // TODO add a --tmp-dir option to the tests to specify where these files go
870

871
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
872

873
   // POSIX only calls for 6 'X' chars but OpenBSD allows arbitrary amount
874
   std::string mkstemp_basename = "/tmp/" + basename + ".XXXXXXXXXX";
42✔
875

876
   const int fd = ::mkstemp(mkstemp_basename.data());
21✔
877

878
   // error
879
   if(fd < 0) {
21✔
880
      return "";
×
881
   }
882

883
   ::close(fd);
21✔
884

885
   return mkstemp_basename;
21✔
886
#else
887
   // For now just create the temp in the current working directory
888
   return basename;
889
#endif
890
}
21✔
891

892
bool Test::copy_file(const std::string& from, const std::string& to) {
1✔
893
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(__cpp_lib_filesystem)
894
   std::error_code ec;  // don't throw, just return false on error
1✔
895
   return std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
1✔
896
#else
897
   // TODO: implement fallbacks to POSIX or WIN32
898
   // ... but then again: it's 2023 and we're using C++20 :o)
899
   BOTAN_UNUSED(from, to);
900
   throw Botan::No_Filesystem_Access();
901
#endif
902
}
903

904
std::string Test::read_data_file(const std::string& path) {
39✔
905
   const std::string fsname = Test::data_file(path);
39✔
906
   std::ifstream file(fsname.c_str());
39✔
907
   if(!file.good()) {
39✔
908
      throw Test_Error("Error reading from " + fsname);
×
909
   }
910

911
   return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
78✔
912
}
39✔
913

914
std::vector<uint8_t> Test::read_binary_data_file(const std::string& path) {
41✔
915
   const std::string fsname = Test::data_file(path);
41✔
916
   std::ifstream file(fsname.c_str(), std::ios::binary);
41✔
917
   if(!file.good()) {
41✔
918
      throw Test_Error("Error reading from " + fsname);
×
919
   }
920

921
   std::vector<uint8_t> contents;
41✔
922

923
   while(file.good()) {
89✔
924
      std::vector<uint8_t> buf(4096);
48✔
925
      file.read(reinterpret_cast<char*>(buf.data()), buf.size());
48✔
926
      const size_t got = static_cast<size_t>(file.gcount());
48✔
927

928
      if(got == 0 && file.eof()) {
48✔
929
         break;
930
      }
931

932
      contents.insert(contents.end(), buf.data(), buf.data() + got);
48✔
933
   }
48✔
934

935
   return contents;
82✔
936
}
41✔
937

938
// static member variables of Test
939

940
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
941
Test_Options Test::m_opts;
942
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
943
std::string Test::m_test_rng_seed;
944

945
//static
946
void Test::set_test_options(const Test_Options& opts) {
1✔
947
   m_opts = opts;
1✔
948
}
1✔
949

950
namespace {
951

952
/*
953
* This is a fast, simple, deterministic PRNG that's used for running
954
* the tests. It is not intended to be cryptographically secure.
955
*/
956
class Testsuite_RNG final : public Botan::RandomNumberGenerator {
9✔
957
   public:
958
      std::string name() const override { return "Testsuite_RNG"; }
×
959

960
      void clear() override { m_x = 0; }
×
961

962
      bool accepts_input() const override { return true; }
×
963

964
      bool is_seeded() const override { return true; }
278,163✔
965

966
      void fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) override {
10,005,673✔
967
         for(const auto byte : input) {
10,005,673✔
968
            mix(byte);
×
969
         }
970

971
         for(auto& byte : output) {
72,459,891✔
972
            byte = mix();
62,454,218✔
973
         }
974
      }
10,005,673✔
975

976
      Testsuite_RNG(std::string_view seed, std::string_view test_name) : m_x(0) {
902✔
977
         for(const char c : seed) {
27,060✔
978
            this->mix(static_cast<uint8_t>(c));
26,158✔
979
         }
980
         for(const char c : test_name) {
37,479✔
981
            this->mix(static_cast<uint8_t>(c));
36,577✔
982
         }
983
      }
902✔
984

985
   private:
986
      uint8_t mix(uint8_t input = 0) {
62,516,953✔
987
         m_x ^= input;
62,516,953✔
988
         m_x *= 0xF2E16957;
62,516,953✔
989
         m_x += 0xE50B590F;
62,516,953✔
990
         return static_cast<uint8_t>(m_x >> 27);
62,516,953✔
991
      }
992

993
      uint64_t m_x;
994
};
995

996
}  // namespace
997

998
//static
999
void Test::set_test_rng_seed(std::span<const uint8_t> seed, size_t epoch) {
1✔
1000
   m_test_rng_seed = Botan::fmt("seed={} epoch={}", Botan::hex_encode(seed), epoch);
1✔
1001
}
1✔
1002

1003
//static
1004
std::unique_ptr<Botan::RandomNumberGenerator> Test::new_rng(std::string_view test_name) {
893✔
1005
   return std::make_unique<Testsuite_RNG>(m_test_rng_seed, test_name);
893✔
1006
}
1007

1008
//static
1009
std::shared_ptr<Botan::RandomNumberGenerator> Test::new_shared_rng(std::string_view test_name) {
9✔
1010
   return std::make_shared<Testsuite_RNG>(m_test_rng_seed, test_name);
9✔
1011
}
1012

1013
//static
1014
std::string Test::data_file(const std::string& file) {
1,124✔
1015
   return options().data_dir() + "/" + file;
2,248✔
1016
}
1017

1018
//static
1019
std::string Test::data_file(std::string_view subdir, std::string_view filename) {
4✔
1020
   if(subdir.empty() || filename.empty()) {
4✔
1021
      throw Test_Error("Empty subdir or filename in Test::data_file");
×
1022
   }
1023
   return Botan::fmt("{}/{}/{}", options().data_dir(), subdir, filename);
4✔
1024
}
1025

1026
//static
1027
std::string Test::data_dir(const std::string& subdir) {
1✔
1028
   return options().data_dir() + "/" + subdir;
2✔
1029
}
1030

1031
//static
1032
std::vector<std::string> Test::files_in_data_dir(const std::string& subdir) {
394✔
1033
   auto fs = Botan::get_files_recursive(options().data_dir() + "/" + subdir);
1,182✔
1034
   if(fs.empty()) {
394✔
1035
      throw Test_Error("Test::files_in_data_dir encountered empty subdir " + subdir);
×
1036
   }
1037
   return fs;
394✔
1038
}
×
1039

1040
//static
1041
std::string Test::data_file_as_temporary_copy(const std::string& what) {
1✔
1042
   auto tmp_basename = what;
1✔
1043
   std::replace(tmp_basename.begin(), tmp_basename.end(), '/', '_');
1✔
1044
   auto temp_file = temp_file_name("tmp-" + tmp_basename);
1✔
1045
   if(temp_file.empty()) {
1✔
1046
      return "";
×
1047
   }
1048
   if(!Test::copy_file(data_file(what), temp_file)) {
1✔
1049
      return "";
×
1050
   }
1051
   return temp_file;
1✔
1052
}
1✔
1053

1054
//static
1055
std::vector<std::string> Test::provider_filter(const std::vector<std::string>& providers) {
49,595✔
1056
   if(m_opts.provider().empty()) {
49,595✔
1057
      return providers;
49,595✔
1058
   }
1059
   for(auto&& provider : providers) {
×
1060
      if(provider == m_opts.provider()) {
×
1061
         return std::vector<std::string>{provider};
×
1062
      }
1063
   }
1064
   return std::vector<std::string>{};
×
1065
}
×
1066

1067
std::string Test::random_password(Botan::RandomNumberGenerator& rng) {
222✔
1068
   const size_t len = 1 + rng.next_byte() % 32;
222✔
1069
   return Botan::hex_encode(rng.random_vec(len));
444✔
1070
}
1071

1072
size_t Test::random_index(Botan::RandomNumberGenerator& rng, size_t max) {
8,062✔
1073
   return Botan::load_be(rng.random_array<8>()) % max;
8,062✔
1074
}
1075

1076
void VarMap::clear() {
34,355✔
1077
   m_vars.clear();
×
1078
}
×
1079

1080
namespace {
1081

1082
bool varmap_pair_lt(const std::pair<std::string, std::string>& kv, std::string_view k) {
1,690,541✔
1083
   return kv.first < k;
1,690,541✔
1084
}
1085

1086
}  // namespace
1087

1088
bool VarMap::has_key(std::string_view key) const {
213,569✔
1089
   return get_opt_var(key).has_value();
213,569✔
1090
}
1091

1092
void VarMap::add(std::string_view key, std::string_view value) {
156,221✔
1093
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
156,221✔
1094

1095
   if(i != m_vars.end() && i->first == key) {
163,440✔
1096
      i->second = value;
44,673✔
1097
   } else {
1098
      m_vars.emplace(i, key, value);
111,548✔
1099
   }
1100
}
156,221✔
1101

1102
std::optional<std::string> VarMap::get_opt_var(std::string_view key) const {
293,660✔
1103
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
293,660✔
1104

1105
   if(i != m_vars.end() && i->first == key) {
295,544✔
1106
      return i->second;
241,107✔
1107
   } else {
1108
      return {};
52,553✔
1109
   }
1110
}
1111

1112
const std::string& VarMap::get_req_var(std::string_view key) const {
261,655✔
1113
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
261,655✔
1114

1115
   if(i != m_vars.end() && i->first == key) {
261,655✔
1116
      return i->second;
261,655✔
1117
   } else {
1118
      throw Test_Error(Botan::fmt("Test missing variable '{}'", key));
×
1119
   }
1120
}
1121

1122
std::string VarMap::get_req_str(std::string_view key) const {
53,359✔
1123
   return std::string(get_req_var(key));
53,359✔
1124
}
1125

1126
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(std::string_view key) const {
12✔
1127
   const auto& var = get_req_var(key);
12✔
1128

1129
   std::vector<std::vector<uint8_t>> bin_list;
12✔
1130

1131
   for(auto&& part : Botan::split_on(var, ',')) {
62✔
1132
      try {
50✔
1133
         bin_list.push_back(Botan::hex_decode(part));
100✔
1134
      } catch(std::exception& e) {
×
1135
         std::ostringstream oss;
×
1136
         oss << "Bad input '" << part << "'"
×
1137
             << " in binary list key " << key << " - " << e.what();
×
1138
         throw Test_Error(oss.str());
×
1139
      }
×
1140
   }
12✔
1141

1142
   return bin_list;
12✔
1143
}
×
1144

1145
std::vector<uint8_t> VarMap::get_req_bin(std::string_view key) const {
164,984✔
1146
   const auto& var = get_req_var(key);
164,984✔
1147

1148
   try {
164,984✔
1149
      return Botan::hex_decode(var);
164,984✔
1150
   } catch(std::exception& e) {
×
1151
      throw Test_Error(Botan::fmt("Bad hex input '{}' for key '{}' err '{}'", var, key, e.what()));
×
1152
   }
×
1153
}
1154

1155
std::string VarMap::get_opt_str(std::string_view key, std::string_view def_value) const {
14,468✔
1156
   if(auto v = get_opt_var(key)) {
14,468✔
1157
      return *v;
14,547✔
1158
   } else {
1159
      return std::string(def_value);
28,778✔
1160
   }
14,468✔
1161
}
1162

1163
bool VarMap::get_req_bool(std::string_view key) const {
74✔
1164
   const auto& var = get_req_var(key);
74✔
1165

1166
   if(var == "true") {
74✔
1167
      return true;
1168
   } else if(var == "false") {
34✔
1169
      return false;
1170
   } else {
1171
      throw Test_Error(Botan::fmt("Invalid boolean '{}' for key '{}'", var, key));
×
1172
   }
1173
}
1174

1175
size_t VarMap::get_req_sz(std::string_view key) const {
4,653✔
1176
   return Botan::to_u32bit(get_req_var(key));
4,653✔
1177
}
1178

1179
uint8_t VarMap::get_req_u8(std::string_view key) const {
17✔
1180
   const size_t s = this->get_req_sz(key);
17✔
1181
   if(s > 256) {
17✔
1182
      throw Test_Error(Botan::fmt("Invalid value for '{}' expected uint8_t but got '{}'", key, s));
×
1183
   }
1184
   return static_cast<uint8_t>(s);
17✔
1185
}
1186

1187
uint32_t VarMap::get_req_u32(std::string_view key) const {
14✔
1188
   return static_cast<uint32_t>(get_req_sz(key));
14✔
1189
}
1190

1191
uint64_t VarMap::get_req_u64(std::string_view key) const {
17✔
1192
   const auto& var = get_req_var(key);
17✔
1193
   if(const auto val = Botan::parse_u64(var)) {
17✔
1194
      return *val;
17✔
1195
   } else {
1196
      throw Test_Error(Botan::fmt("Invalid u64 value '{}' for key '{}'", var, key));
×
1197
   }
1198
}
1199

1200
size_t VarMap::get_opt_sz(std::string_view key, const size_t def_value) const {
13,884✔
1201
   if(auto v = get_opt_var(key)) {
13,884✔
1202
      return Botan::to_u32bit(*v);
12,261✔
1203
   } else {
1204
      return def_value;
1205
   }
13,884✔
1206
}
1207

1208
uint64_t VarMap::get_opt_u64(std::string_view key, const uint64_t def_value) const {
4,363✔
1209
   if(auto var = get_opt_var(key)) {
4,363✔
1210
      if(const auto val = Botan::parse_u64(*var)) {
1,053✔
1211
         return *val;
1,053✔
1212
      } else {
1213
         throw Test_Error(Botan::fmt("Invalid u64 value '{}' for key '{}'", *var, key));
×
1214
      }
1215
   } else {
1216
      return def_value;
1217
   }
4,363✔
1218
}
1219

1220
std::vector<uint8_t> VarMap::get_opt_bin(std::string_view key) const {
47,296✔
1221
   if(auto v = get_opt_var(key)) {
47,296✔
1222
      try {
17,835✔
1223
         return Botan::hex_decode(*v);
17,835✔
1224
      } catch(std::exception&) {
×
1225
         throw Test_Error(Botan::fmt("Invalid hex for key '{}' got '{}'", key, *v));
×
1226
      }
×
1227
   } else {
1228
      return {};
29,461✔
1229
   };
47,296✔
1230
}
1231

1232
#if defined(BOTAN_HAS_BIGINT)
1233
Botan::BigInt VarMap::get_req_bn(std::string_view key) const {
38,556✔
1234
   const auto& var = get_req_var(key);
38,556✔
1235

1236
   try {
38,556✔
1237
      return Botan::BigInt(var);
38,556✔
1238
   } catch(std::exception&) {
×
1239
      throw Test_Error(Botan::fmt("Invalid BigInt for key '{}' got '{}'", key, var));
×
1240
   }
×
1241
}
1242

1243
Botan::BigInt VarMap::get_opt_bn(std::string_view key, const Botan::BigInt& def_value) const {
80✔
1244
   if(auto v = get_opt_var(key)) {
80✔
1245
      try {
56✔
1246
         return Botan::BigInt(*v);
56✔
1247
      } catch(std::exception&) {
×
1248
         throw Test_Error(Botan::fmt("Invalid BigInt for key '{}' got '{}'", key, *v));
×
1249
      }
×
1250
   } else {
1251
      return def_value;
24✔
1252
   }
80✔
1253
}
1254
#endif
1255

1256
class Text_Based_Test::Text_Based_Test_Data {
1257
   public:
1258
      Text_Based_Test_Data(const std::string& data_src,
194✔
1259
                           const std::string& required_keys_str,
1260
                           const std::string& optional_keys_str) :
194✔
1261
            m_data_src(data_src) {
388✔
1262
         if(required_keys_str.empty()) {
194✔
1263
            throw Test_Error("Invalid test spec");
×
1264
         }
1265

1266
         m_required_keys = Botan::split_on(required_keys_str, ',');
194✔
1267
         std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
194✔
1268

1269
         m_all_keys.insert(m_required_keys.begin(), m_required_keys.end());
194✔
1270
         m_all_keys.insert(optional_keys.begin(), optional_keys.end());
194✔
1271
         m_output_key = m_required_keys.at(m_required_keys.size() - 1);
194✔
1272
      }
194✔
1273

1274
      std::string get_next_line();
1275

1276
      const std::string& current_source_name() const { return m_cur_src_name; }
×
1277

1278
      bool known_key(const std::string& key) const;
1279

1280
      const std::vector<std::string>& required_keys() const { return m_required_keys; }
48,536✔
1281

1282
      const std::string& output_key() const { return m_output_key; }
156,221✔
1283

1284
      const std::vector<std::string>& cpu_flags() const { return m_cpu_flags; }
48,395✔
1285

1286
      void set_cpu_flags(std::vector<std::string> flags) { m_cpu_flags = std::move(flags); }
27✔
1287

1288
      const std::string& initial_data_src_name() const { return m_data_src; }
194✔
1289

1290
   private:
1291
      std::string m_data_src;
1292
      std::vector<std::string> m_required_keys;
1293
      std::unordered_set<std::string> m_all_keys;
1294
      std::string m_output_key;
1295

1296
      bool m_first = true;
1297
      std::unique_ptr<std::istream> m_cur;
1298
      std::string m_cur_src_name;
1299
      std::deque<std::string> m_srcs;
1300
      std::vector<std::string> m_cpu_flags;
1301
};
1302

1303
Text_Based_Test::Text_Based_Test(const std::string& data_src,
194✔
1304
                                 const std::string& required_keys,
1305
                                 const std::string& optional_keys) :
194✔
1306
      m_data(std::make_unique<Text_Based_Test_Data>(data_src, required_keys, optional_keys)) {}
194✔
1307

1308
Text_Based_Test::~Text_Based_Test() = default;
194✔
1309

1310
std::string Text_Based_Test::Text_Based_Test_Data::get_next_line() {
157,279✔
1311
   while(true) {
157,553✔
1312
      if(m_cur == nullptr || m_cur->good() == false) {
157,553✔
1313
         if(m_srcs.empty()) {
478✔
1314
            if(m_first) {
388✔
1315
               if(m_data_src.ends_with(".vec")) {
194✔
1316
                  m_srcs.push_back(Test::data_file(m_data_src));
364✔
1317
               } else {
1318
                  const auto fs = Test::files_in_data_dir(m_data_src);
12✔
1319
                  m_srcs.assign(fs.begin(), fs.end());
12✔
1320
                  if(m_srcs.empty()) {
12✔
1321
                     throw Test_Error("Error reading test data dir " + m_data_src);
×
1322
                  }
1323
               }
12✔
1324

1325
               m_first = false;
194✔
1326
            } else {
1327
               return "";  // done
194✔
1328
            }
1329
         }
1330

1331
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
374✔
1332
         m_cur_src_name = m_srcs[0];
284✔
1333

1334
#if defined(BOTAN_HAS_CPUID)
1335
         // Reinit cpuid on new file if needed
1336
         if(m_cpu_flags.empty() == false) {
284✔
1337
            m_cpu_flags.clear();
23✔
1338
            Botan::CPUID::initialize();
23✔
1339
         }
1340
#endif
1341

1342
         if(!m_cur->good()) {
284✔
1343
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
1344
         }
1345

1346
         m_srcs.pop_front();
284✔
1347
      }
1348

1349
      while(m_cur->good()) {
228,410✔
1350
         std::string line;
228,136✔
1351
         std::getline(*m_cur, line);
228,136✔
1352

1353
         if(line.empty()) {
228,136✔
1354
            continue;
55,404✔
1355
         }
1356

1357
         if(line[0] == '#') {
172,732✔
1358
            if(line.starts_with("#test ")) {
15,674✔
1359
               return line;
27✔
1360
            } else {
1361
               continue;
15,647✔
1362
            }
1363
         }
1364

1365
         return line;
157,058✔
1366
      }
228,136✔
1367
   }
1368
}
1369

1370
bool Text_Based_Test::Text_Based_Test_Data::known_key(const std::string& key) const {
156,221✔
1371
   return m_all_keys.contains(key);
156,221✔
1372
}
1373

1374
namespace {
1375

1376
// strips leading and trailing but not internal whitespace
1377
std::string strip_ws(const std::string& in) {
312,442✔
1378
   const char* whitespace = " ";
312,442✔
1379

1380
   const auto first_c = in.find_first_not_of(whitespace);
312,442✔
1381
   if(first_c == std::string::npos) {
312,442✔
1382
      return "";
1,084✔
1383
   }
1384

1385
   const auto last_c = in.find_last_not_of(whitespace);
311,358✔
1386

1387
   return in.substr(first_c, last_c - first_c + 1);
311,358✔
1388
}
1389

1390
std::vector<std::string> parse_cpuid_bits(const std::vector<std::string>& tok) {
27✔
1391
   std::vector<std::string> bits;
27✔
1392

1393
#if defined(BOTAN_HAS_CPUID)
1394
   for(size_t i = 1; i < tok.size(); ++i) {
129✔
1395
      if(auto bit = Botan::CPUID::bit_from_string(tok[i])) {
102✔
1396
         bits.push_back(bit->to_string());
124✔
1397
      }
1398
   }
1399
#else
1400
   BOTAN_UNUSED(tok);
1401
#endif
1402

1403
   return bits;
27✔
1404
}
×
1405

1406
}  // namespace
1407

1408
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) {
32,739✔
1409
   return false;
32,739✔
1410
}
1411

1412
std::vector<Test::Result> Text_Based_Test::run() {
194✔
1413
   std::vector<Test::Result> results;
194✔
1414

1415
   std::string header;
194✔
1416
   std::string header_or_name = m_data->initial_data_src_name();
194✔
1417
   VarMap vars;
194✔
1418
   size_t test_cnt = 0;
194✔
1419

1420
   while(true) {
157,279✔
1421
      const std::string line = m_data->get_next_line();
157,279✔
1422
      if(line.empty()) {
157,279✔
1423
         // EOF
1424
         break;
1425
      }
1426

1427
      if(line.starts_with("#test ")) {
157,085✔
1428
         std::vector<std::string> pragma_tokens = Botan::split_on(line.substr(6), ' ');
27✔
1429

1430
         if(pragma_tokens.empty()) {
27✔
1431
            throw Test_Error("Empty pragma found in " + m_data->current_source_name());
×
1432
         }
1433

1434
         if(pragma_tokens[0] != "cpuid") {
27✔
1435
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1436
         }
1437

1438
         if(!Test_Registry::instance().needs_serialization(this->test_name())) {
54✔
1439
            throw Test_Error(Botan::fmt("'{}' used cpuid control but is not serialized", this->test_name()));
×
1440
         }
1441

1442
         m_data->set_cpu_flags(parse_cpuid_bits(pragma_tokens));
54✔
1443

1444
         continue;
27✔
1445
      } else if(line[0] == '#') {
157,085✔
1446
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1447
      }
1448

1449
      if(line[0] == '[' && line[line.size() - 1] == ']') {
157,058✔
1450
         header = line.substr(1, line.size() - 2);
837✔
1451
         header_or_name = header;
837✔
1452
         test_cnt = 0;
837✔
1453
         vars.clear();
837✔
1454
         continue;
837✔
1455
      }
1456

1457
      const std::string test_id = "test " + std::to_string(test_cnt);
312,442✔
1458

1459
      auto equal_i = line.find_first_of('=');
156,221✔
1460

1461
      if(equal_i == std::string::npos) {
156,221✔
1462
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1463
         continue;
×
1464
      }
1465

1466
      const std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
312,442✔
1467
      const std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
312,442✔
1468

1469
      if(!m_data->known_key(key)) {
156,221✔
1470
         auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key));
×
1471
         results.push_back(r);
×
1472
      }
×
1473

1474
      vars.add(key, val);
156,221✔
1475

1476
      if(key == m_data->output_key()) {
156,221✔
1477
         try {
48,536✔
1478
            for(const auto& req_key : m_data->required_keys()) {
245,679✔
1479
               if(!vars.has_key(req_key)) {
197,143✔
1480
                  auto r =
×
1481
                     Test::Result::Failure(header_or_name, Botan::fmt("{} missing required key {}", test_id, req_key));
×
1482
                  results.push_back(r);
×
1483
               }
×
1484
            }
1485

1486
            if(skip_this_test(header, vars)) {
48,536✔
1487
               continue;
141✔
1488
            }
1489

1490
            ++test_cnt;
48,395✔
1491

1492
            const uint64_t start = Test::timestamp();
48,395✔
1493

1494
            Test::Result result = run_one_test(header, vars);
48,395✔
1495
#if defined(BOTAN_HAS_CPUID)
1496
            if(!m_data->cpu_flags().empty()) {
48,395✔
1497
               for(const auto& cpuid_str : m_data->cpu_flags()) {
34,682✔
1498
                  if(const auto bit = Botan::CPUID::Feature::from_string(cpuid_str)) {
23,851✔
1499
                     if(Botan::CPUID::has(*bit)) {
23,851✔
1500
                        Botan::CPUID::clear_cpuid_bit(*bit);
17,531✔
1501
                        // now re-run the test
1502
                        result.merge(run_one_test(header, vars));
17,531✔
1503
                     }
1504
                  }
1505
               }
1506
               Botan::CPUID::initialize();
10,831✔
1507
            }
1508
#endif
1509
            result.set_ns_consumed(Test::timestamp() - start);
48,395✔
1510

1511
            if(result.tests_failed() > 0) {
48,395✔
1512
               std::ostringstream oss;
×
1513
               oss << "Test # " << test_cnt << " ";
×
1514
               if(!header.empty()) {
×
1515
                  oss << header << " ";
×
1516
               }
1517
               oss << "failed ";
×
1518

1519
               for(const auto& k : m_data->required_keys()) {
×
1520
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1521
               }
1522

1523
               result.test_note(oss.str());
×
1524
            }
×
1525
            results.push_back(result);
48,395✔
1526
         } catch(std::exception& e) {
48,395✔
1527
            std::ostringstream oss;
×
1528
            oss << "Test # " << test_cnt << " ";
×
1529
            if(!header.empty()) {
×
1530
               oss << header << " ";
×
1531
            }
1532

1533
            for(const auto& k : m_data->required_keys()) {
×
1534
               oss << k << "=" << vars.get_req_str(k) << " ";
×
1535
            }
1536

1537
            oss << "failed with exception '" << e.what() << "'";
×
1538

1539
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1540
         }
×
1541

1542
         if(clear_between_callbacks()) {
48,395✔
1543
            vars.clear();
189,598✔
1544
         }
1545
      }
1546
   }
157,367✔
1547

1548
   if(results.empty()) {
194✔
1549
      return results;
1550
   }
1551

1552
   try {
194✔
1553
      std::vector<Test::Result> final_tests = run_final_tests();
194✔
1554
      results.insert(results.end(), final_tests.begin(), final_tests.end());
194✔
1555
   } catch(std::exception& e) {
194✔
1556
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1557
   }
×
1558

1559
   return results;
1560
}
194✔
1561

1562
}  // 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

© 2026 Coveralls, Inc