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

randombit / botan / 22090616258

17 Feb 2026 08:07AM UTC coverage: 90.026% (-0.002%) from 90.028%
22090616258

Pull #5352

github

web-flow
Merge 27083c141 into 7b1bee298
Pull Request #5352: Change VarMap to avoid copies internally

102334 of 113671 relevant lines covered (90.03%)

11388428.89 hits per line

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

80.02
/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;
420✔
59

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

62
Test::Result::Result(std::string_view who) : m_who(who), m_timestamp(Test::timestamp()) {}
81,198✔
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) {
126,834✔
71
   if(who() != other.who()) {
126,834✔
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;
126,761✔
81
   }
82

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

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

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

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

108
void Test::Result::test_note(std::string_view note, const char* extra) {
2,767✔
109
   if(!note.empty()) {
2,767✔
110
      std::ostringstream out;
2,767✔
111
      out << who() << " " << note;
2,767✔
112
      if(extra != nullptr) {
2,767✔
113
         out << ": " << extra;
12✔
114
      }
115
      m_log.push_back(out.str());
2,767✔
116
   }
2,767✔
117
}
2,767✔
118

119
void Test::Result::note_missing(std::string_view whatever_sv) {
275✔
120
   static std::set<std::string> s_already_seen;
275✔
121

122
   const std::string whatever(whatever_sv);
275✔
123
   if(!s_already_seen.contains(whatever)) {
275✔
124
      test_note(Botan::fmt("Skipping tests due to missing {}", whatever));
5✔
125
      s_already_seen.insert(whatever);
275✔
126
   }
127
}
275✔
128

129
void Test::Result::require(std::string_view what, bool expr) {
322✔
130
   if(!test_is_true(what, expr)) {
322✔
131
      throw Test_Aborted(Botan::fmt("Test aborted, because required condition was not met: {}", what));
×
132
   }
133
}
322✔
134

135
Test::Result::ThrowExpectations::~ThrowExpectations() {
67,783✔
136
   BOTAN_ASSERT_NOMSG(m_consumed);
67,783✔
137
}
130,020✔
138

139
void Test::Result::ThrowExpectations::assert_that_success_is_not_expected() const {
62,237✔
140
   BOTAN_ASSERT_NOMSG(!m_expect_success);
62,048✔
141
}
62,048✔
142

143
Test::Result::ThrowExpectations& Test::Result::ThrowExpectations::expect_success() {
1,645✔
144
   BOTAN_ASSERT_NOMSG(!m_expected_message && !m_expected_exception_check_fn);
1,645✔
145
   m_expect_success = true;
1,645✔
146
   return *this;
1,645✔
147
}
148

149
Test::Result::ThrowExpectations& Test::Result::ThrowExpectations::expect_message(std::string_view message) {
189✔
150
   assert_that_success_is_not_expected();
189✔
151
   m_expected_message = message;
189✔
152
   return *this;
189✔
153
}
154

155
bool Test::Result::ThrowExpectations::check(std::string_view test_name, Test::Result& result) {
67,783✔
156
   m_consumed = true;
67,783✔
157

158
   try {
67,783✔
159
      m_fn();
67,783✔
160
      if(!m_expect_success) {
1,646✔
161
         return result.test_failure(Botan::fmt("{} failed to throw expected exception", test_name));
2✔
162
      }
163
   } catch(const std::exception& ex) {
66,137✔
164
      if(m_expect_success) {
66,135✔
165
         return result.test_failure(Botan::fmt("{} threw unexpected exception: {}", test_name, ex.what()));
1✔
166
      }
167
      if(m_expected_exception_check_fn && !m_expected_exception_check_fn(std::current_exception())) {
190,230✔
168
         return result.test_failure(Botan::fmt("{} threw unexpected exception: {}", test_name, ex.what()));
2✔
169
      }
170
      if(m_expected_message.has_value() && m_expected_message.value() != ex.what()) {
66,132✔
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.what()));
2✔
175
      }
176
   } catch(...) {
66,137✔
177
      if(m_expect_success || m_expected_exception_check_fn || m_expected_message.has_value()) {
2✔
178
         return result.test_failure(Botan::fmt("{} threw unexpected unknown exception", test_name));
1✔
179
      }
180
   }
2✔
181

182
   return result.test_success();
67,776✔
183
}
184

185
bool Test::Result::test_throws(std::string_view what, std::function<void()> fn) {
3,916✔
186
   return ThrowExpectations(std::move(fn)).check(what, *this);
11,748✔
187
}
188

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

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

197
bool Test::Result::test_success(std::string_view note) {
3,620,844✔
198
   if(Test::options().log_success()) {
3,620,828✔
199
      test_note(note);
×
200
   }
201
   ++m_tests_passed;
3,620,844✔
202
   return true;
67,776✔
203
}
204

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

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

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

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

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

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

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

234
namespace {
235

236
bool same_contents(std::span<const uint8_t> x, std::span<const uint8_t> y) {
302,667✔
237
   if(x.size() != y.size()) {
1,422✔
238
      return false;
239
   }
240
   if(x.empty()) {
302,666✔
241
      return true;
242
   }
243

244
   return std::memcmp(x.data(), y.data(), x.size()) == 0;
301,234✔
245
}
246

247
}  // namespace
248

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

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

265
bool Test::Result::test_bin_eq(std::string_view what,
301,245✔
266
                               std::span<const uint8_t> produced,
267
                               std::span<const uint8_t> expected) {
268
   if(same_contents(produced, expected)) {
601,057✔
269
      return test_success();
301,244✔
270
   }
271

272
   std::ostringstream err;
1✔
273

274
   err << who();
1✔
275

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

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

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

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

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

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

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

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

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

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

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

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

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

341
bool Test::Result::test_u8_eq(std::string_view what, uint8_t produced, uint8_t expected) {
49,385✔
342
   return test_sz_eq(what, produced, expected);
49,385✔
343
}
344

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

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

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

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

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

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

373
bool Test::Result::test_sz_eq(std::string_view what, size_t produced, size_t expected) {
197,637✔
374
   if(produced == expected) {
197,637✔
375
      return test_success();
197,636✔
376
   } else {
377
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} == {}", who(), what, produced, expected));
1✔
378
   }
379
}
380

381
bool Test::Result::test_sz_ne(std::string_view what, size_t produced, size_t expected) {
119✔
382
   if(produced != expected) {
119✔
383
      return test_success();
118✔
384
   } else {
385
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} != {}", who(), what, produced, expected));
1✔
386
   }
387
}
388

389
bool Test::Result::test_sz_lt(std::string_view what, size_t produced, size_t expected) {
5,639✔
390
   if(produced < expected) {
5,639✔
391
      return test_success();
5,638✔
392
   } else {
393
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} < {}", who(), what, produced, expected));
1✔
394
   }
395
}
396

397
bool Test::Result::test_sz_lte(std::string_view what, size_t produced, size_t expected) {
1,021,636✔
398
   if(produced <= expected) {
1,021,636✔
399
      return test_success();
1,021,635✔
400
   } else {
401
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} <= {}", who(), what, produced, expected));
1✔
402
   }
403
}
404

405
bool Test::Result::test_sz_gt(std::string_view what, size_t produced, size_t expected) {
29,981✔
406
   if(produced > expected) {
29,981✔
407
      return test_success();
29,981✔
408
   } else {
409
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} > {}", who(), what, produced, expected));
×
410
   }
411
}
412

413
bool Test::Result::test_sz_gte(std::string_view what, size_t produced, size_t expected) {
1,142,521✔
414
   if(produced >= expected) {
1,142,521✔
415
      return test_success();
1,142,520✔
416
   } else {
417
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} >= {}", who(), what, produced, expected));
1✔
418
   }
419
}
420

421
bool Test::Result::test_opt_u8_eq(std::string_view what,
1,215✔
422
                                  std::optional<uint8_t> produced,
423
                                  std::optional<uint8_t> expected) {
424
   if(produced.has_value() and !expected.has_value()) {
1,215✔
425
      return test_failure(Botan::fmt("Assertion {} produced value {} but nullopt was expected", what, *produced));
×
426
   } else if(!produced.has_value() && expected.has_value()) {
1,215✔
427
      return test_failure(Botan::fmt("Assertion {} produced nullopt but {} was expected", what, *expected));
×
428
   } else if(produced.has_value() && expected.has_value()) {
1,215✔
429
      return test_u8_eq(what, *produced, *expected);
10✔
430
   } else {
431
      return test_success();
1,205✔
432
   }
433
}
434

435
bool Test::Result::test_opt_u64_eq(std::string_view what,
9✔
436
                                   std::optional<uint64_t> produced,
437
                                   std::optional<uint64_t> expected) {
438
   if(produced.has_value() and !expected.has_value()) {
9✔
439
      return test_failure(Botan::fmt("Assertion {} produced value {} but nullopt was expected", what, *produced));
×
440
   } else if(!produced.has_value() && expected.has_value()) {
9✔
441
      return test_failure(Botan::fmt("Assertion {} produced nullopt but {} was expected", what, *expected));
×
442
   } else if(produced.has_value() && expected.has_value()) {
9✔
443
      return test_u64_eq(what, *produced, *expected);
9✔
444
   } else {
445
      return test_success();
×
446
   }
447
}
448

449
#if defined(BOTAN_HAS_BIGINT)
450
bool Test::Result::test_bn_eq(std::string_view what, const BigInt& produced, const BigInt& expected) {
252,633✔
451
   if(produced == expected) {
252,633✔
452
      return test_success();
252,632✔
453
   } else {
454
      std::ostringstream err;
1✔
455
      err << who() << " " << what << " produced " << produced << " != expected value " << expected;
1✔
456
      return test_failure(err.str());
1✔
457
   }
1✔
458
}
459

460
bool Test::Result::test_bn_ne(std::string_view what, const BigInt& produced, const BigInt& expected) {
97✔
461
   if(produced != expected) {
97✔
462
      return test_success();
96✔
463
   } else {
464
      std::ostringstream err;
1✔
465
      err << who() << " " << what << " produced " << produced << " prohibited value";
1✔
466
      return test_failure(err.str());
1✔
467
   }
1✔
468
}
469
#endif
470

471
bool Test::Result::test_bool_eq(std::string_view what, bool produced, bool expected) {
361,567✔
472
   if(produced == expected) {
361,567✔
473
      return test_success();
361,567✔
474
   } else {
475
      if(expected == true) {
×
476
         return test_failure(Botan::fmt("Assertion failure in {}, {} was unexpectedly false", who(), what));
×
477
      } else {
478
         return test_failure(Botan::fmt("Assertion failure in {}, {} was unexpectedly true", who(), what));
×
479
      }
480
   }
481
}
482

483
bool Test::Result::test_is_true(std::string_view what, bool produced) {
227,990✔
484
   return test_bool_eq(what, produced, true);
227,990✔
485
}
486

487
bool Test::Result::test_is_false(std::string_view what, bool produced) {
126,006✔
488
   return test_bool_eq(what, produced, false);
126,006✔
489
}
490

491
bool Test::Result::test_rc_ok(std::string_view func, int rc) {
2,815✔
492
   if(rc != 0) {
2,815✔
493
      std::ostringstream err;
1✔
494
      err << m_who << " " << func << " unexpectedly failed with error code " << rc;
1✔
495
      return test_failure(err.str());
1✔
496
   }
1✔
497

498
   return test_success();
2,814✔
499
}
500

501
bool Test::Result::test_rc_fail(std::string_view func, std::string_view why, int rc) {
26✔
502
   if(rc == 0) {
26✔
503
      std::ostringstream err;
1✔
504
      err << m_who << " call to " << func << " unexpectedly succeeded expecting failure because " << why;
1✔
505
      return test_failure(err.str());
1✔
506
   }
1✔
507

508
   return test_success();
25✔
509
}
510

511
bool Test::Result::test_rc_init(std::string_view func, int rc) {
117✔
512
   if(rc == 0) {
117✔
513
      return test_success();
117✔
514
   } else {
515
      std::ostringstream msg;
×
516
      msg << m_who;
×
517
      msg << " " << func;
×
518

519
      // -40 is BOTAN_FFI_ERROR_NOT_IMPLEMENTED
520
      if(rc == -40) {
×
521
         msg << " returned not implemented";
×
522
      } else {
523
         msg << " unexpectedly failed with error code " << rc;
×
524
      }
525

526
      if(rc == -40) {
×
527
         this->test_note(msg.str());
×
528
      } else {
529
         this->test_failure(msg.str());
×
530
      }
531
      return false;
×
532
   }
×
533
}
534

535
bool Test::Result::test_rc(std::string_view func, int rc, int expected) {
421✔
536
   if(expected != rc) {
421✔
537
      std::ostringstream err;
1✔
538
      err << m_who;
1✔
539
      err << " call to " << func << " unexpectedly returned " << rc;
1✔
540
      err << " but expecting " << expected;
1✔
541
      return test_failure(err.str());
1✔
542
   }
1✔
543

544
   return test_success();
420✔
545
}
546

547
void Test::initialize(std::string test_name, CodeLocation location) {
420✔
548
   m_test_name = std::move(test_name);
420✔
549
   m_registration_location = location;
420✔
550
}
420✔
551

552
Botan::RandomNumberGenerator& Test::rng() const {
460,315✔
553
   if(!m_test_rng) {
460,315✔
554
      m_test_rng = Test::new_rng(m_test_name);
146✔
555
   }
556

557
   return *m_test_rng;
460,315✔
558
}
559

560
std::optional<std::string> Test::supported_ec_group_name(std::vector<std::string> preferred_groups) {
151✔
561
#if defined(BOTAN_HAS_ECC_GROUP)
562
   if(preferred_groups.empty()) {
151✔
563
      preferred_groups = {
149✔
564
         "secp256r1",
565
         "brainpool256r1",
566
         "secp384r1",
567
         "brainpool384r1",
568
         "secp521r1",
569
         "brainpool512r1",
570
      };
1,192✔
571
   }
572

573
   for(const auto& group : preferred_groups) {
151✔
574
      if(Botan::EC_Group::supports_named_group(group)) {
151✔
575
         return group;
151✔
576
      }
577
   }
578
#else
579
   BOTAN_UNUSED(preferred_groups);
580
#endif
581

582
   return std::nullopt;
×
583
}
298✔
584

585
std::vector<uint8_t> Test::mutate_vec(const std::vector<uint8_t>& v,
96,742✔
586
                                      Botan::RandomNumberGenerator& rng,
587
                                      bool maybe_resize,
588
                                      size_t min_offset) {
589
   std::vector<uint8_t> r = v;
96,742✔
590

591
   if(maybe_resize && (r.empty() || rng.next_byte() < 32)) {
110,315✔
592
      // TODO: occasionally truncate, insert at random index
593
      const size_t add = 1 + (rng.next_byte() % 16);
2,245✔
594
      r.resize(r.size() + add);
2,245✔
595
      rng.randomize(&r[r.size() - add], add);
2,245✔
596
   }
597

598
   if(r.size() > min_offset) {
96,742✔
599
      const size_t offset = std::max<size_t>(min_offset, rng.next_byte() % r.size());
95,204✔
600
      const uint8_t perturb = rng.next_nonzero_byte();
95,204✔
601
      r[offset] ^= perturb;
95,204✔
602
   }
603

604
   return r;
96,742✔
605
}
×
606

607
std::vector<std::string> Test::possible_providers(const std::string& /*alg*/) {
×
608
   return Test::provider_filter({"base"});
×
609
}
610

611
//static
612
std::string Test::format_time(uint64_t nanoseconds) {
1,470✔
613
   std::ostringstream o;
1,470✔
614

615
   if(nanoseconds > 1000000000) {
1,470✔
616
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000000.0 << " sec";
155✔
617
   } else {
618
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000.0 << " msec";
1,315✔
619
   }
620

621
   return o.str();
2,940✔
622
}
1,470✔
623

624
// TODO: this should move to `StdoutReporter`
625
std::string Test::Result::result_string() const {
2,556✔
626
   const bool verbose = Test::options().verbose();
2,556✔
627

628
   if(tests_run() == 0 && !verbose) {
2,556✔
629
      return "";
20✔
630
   }
631

632
   std::ostringstream report;
2,536✔
633

634
   report << who() << " ran ";
2,536✔
635

636
   if(tests_run() == 0) {
2,536✔
637
      report << "ZERO";
×
638
   } else {
639
      report << tests_run();
2,536✔
640
   }
641
   report << " tests";
2,536✔
642

643
   if(m_ns_taken > 0) {
2,536✔
644
      report << " in " << format_time(m_ns_taken);
2,938✔
645
   }
646

647
   if(tests_failed() > 0) {
2,536✔
648
      report << " " << tests_failed() << " FAILED";
24✔
649
   } else {
650
      report << " all ok";
2,512✔
651
   }
652

653
   report << "\n";
2,536✔
654

655
   for(size_t i = 0; i != m_fail_log.size(); ++i) {
2,560✔
656
      report << "Failure " << (i + 1) << ": " << m_fail_log[i];
24✔
657
      if(m_where) {
24✔
658
         report << " (at " << m_where->path << ":" << m_where->line << ")";
×
659
      }
660
      report << "\n";
24✔
661
   }
662

663
   if(!m_fail_log.empty() || tests_run() == 0 || verbose) {
2,536✔
664
      for(size_t i = 0; i != m_log.size(); ++i) {
24✔
665
         report << "Note " << (i + 1) << ": " << m_log[i] << "\n";
×
666
      }
667
   }
668

669
   return report.str();
2,536✔
670
}
2,536✔
671

672
namespace {
673

674
class Test_Registry {
675
   public:
676
      static Test_Registry& instance() {
1,282✔
677
         static Test_Registry registry;
1,283✔
678
         return registry;
1,282✔
679
      }
680

681
      void register_test(const std::string& category,
420✔
682
                         const std::string& name,
683
                         bool smoke_test,
684
                         bool needs_serialization,
685
                         std::function<std::unique_ptr<Test>()> maker_fn) {
686
         if(m_tests.contains(name)) {
420✔
687
            throw Test_Error("Duplicate registration of test '" + name + "'");
×
688
         }
689

690
         if(m_tests.contains(category)) {
420✔
691
            throw Test_Error("'" + category + "' cannot be used as category, test exists");
×
692
         }
693

694
         if(m_categories.contains(name)) {
420✔
695
            throw Test_Error("'" + name + "' cannot be used as test name, category exists");
×
696
         }
697

698
         if(smoke_test) {
420✔
699
            m_smoke_tests.push_back(name);
10✔
700
         }
701

702
         if(needs_serialization) {
420✔
703
            m_mutexed_tests.push_back(name);
21✔
704
         }
705

706
         m_tests.emplace(name, std::move(maker_fn));
420✔
707
         m_categories.emplace(category, name);
420✔
708
      }
420✔
709

710
      std::unique_ptr<Test> get_test(const std::string& test_name) const {
420✔
711
         auto i = m_tests.find(test_name);
420✔
712
         if(i != m_tests.end()) {
420✔
713
            return i->second();
420✔
714
         }
715
         return nullptr;
×
716
      }
717

718
      std::vector<std::string> registered_tests() const {
×
719
         std::vector<std::string> s;
×
720
         s.reserve(m_tests.size());
×
721
         for(auto&& i : m_tests) {
×
722
            s.push_back(i.first);
×
723
         }
724
         return s;
×
725
      }
×
726

727
      std::vector<std::string> registered_test_categories() const {
×
728
         std::set<std::string> s;
×
729
         for(auto&& i : m_categories) {
×
730
            s.insert(i.first);
×
731
         }
732
         return std::vector<std::string>(s.begin(), s.end());
×
733
      }
×
734

735
      std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
1✔
736
                                                       const std::vector<std::string>& to_be_skipped) {
737
         std::vector<std::string> result;
1✔
738

739
         std::set<std::string> to_be_skipped_set(to_be_skipped.begin(), to_be_skipped.end());
1✔
740
         // TODO: this is O(n^2), but we have a relatively small number of tests.
741
         auto insert_if_not_exists_and_not_skipped = [&](const std::string& test_name) {
421✔
742
            if(!Botan::value_exists(result, test_name) && !to_be_skipped_set.contains(test_name)) {
840✔
743
               result.push_back(test_name);
410✔
744
            }
745
         };
421✔
746

747
         if(requested.empty()) {
1✔
748
            /*
749
            If nothing was requested on the command line, run everything. First
750
            run the "essentials" to smoke test, then everything else in
751
            alphabetical order.
752
            */
753
            result = m_smoke_tests;
1✔
754
            for(const auto& [test_name, _] : m_tests) {
421✔
755
               insert_if_not_exists_and_not_skipped(test_name);
420✔
756
            }
757
         } else {
758
            for(const auto& r : requested) {
×
759
               if(m_tests.contains(r)) {
×
760
                  insert_if_not_exists_and_not_skipped(r);
×
761
               } else if(auto elems = m_categories.equal_range(r); elems.first != m_categories.end()) {
×
762
                  for(; elems.first != elems.second; ++elems.first) {
×
763
                     insert_if_not_exists_and_not_skipped(elems.first->second);
×
764
                  }
765
               } else {
766
                  throw Test_Error("Unknown test suite or category: " + r);
×
767
               }
768
            }
769
         }
770

771
         return result;
1✔
772
      }
1✔
773

774
      bool needs_serialization(const std::string& test_name) const {
441✔
775
         return Botan::value_exists(m_mutexed_tests, test_name);
21✔
776
      }
777

778
   private:
779
      Test_Registry() = default;
1✔
780

781
   private:
782
      std::map<std::string, std::function<std::unique_ptr<Test>()>> m_tests;
783
      std::multimap<std::string, std::string> m_categories;
784
      std::vector<std::string> m_smoke_tests;
785
      std::vector<std::string> m_mutexed_tests;
786
};
787

788
}  // namespace
789

790
// static Test:: functions
791

792
//static
793
void Test::register_test(const std::string& category,
420✔
794
                         const std::string& name,
795
                         bool smoke_test,
796
                         bool needs_serialization,
797
                         std::function<std::unique_ptr<Test>()> maker_fn) {
798
   Test_Registry::instance().register_test(category, name, smoke_test, needs_serialization, std::move(maker_fn));
840✔
799
}
420✔
800

801
//static
802
uint64_t Test::timestamp() {
180,117✔
803
   auto now = std::chrono::system_clock::now().time_since_epoch();
180,117✔
804
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
2,383✔
805
}
806

807
//static
808
std::vector<Test::Result> Test::flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists) {
4✔
809
   std::vector<Test::Result> results;
4✔
810
   for(auto& result_list : result_lists) {
26✔
811
      for(auto& result : result_list) {
71✔
812
         results.emplace_back(std::move(result));
49✔
813
      }
814
   }
815
   return results;
4✔
816
}
×
817

818
//static
819
std::vector<std::string> Test::registered_tests() {
×
820
   return Test_Registry::instance().registered_tests();
×
821
}
822

823
//static
824
std::vector<std::string> Test::registered_test_categories() {
×
825
   return Test_Registry::instance().registered_test_categories();
×
826
}
827

828
//static
829
std::unique_ptr<Test> Test::get_test(const std::string& test_name) {
420✔
830
   return Test_Registry::instance().get_test(test_name);
420✔
831
}
832

833
//static
834
bool Test::test_needs_serialization(const std::string& test_name) {
420✔
835
   return Test_Registry::instance().needs_serialization(test_name);
420✔
836
}
837

838
//static
839
std::vector<std::string> Test::filter_registered_tests(const std::vector<std::string>& requested,
1✔
840
                                                       const std::vector<std::string>& to_be_skipped) {
841
   return Test_Registry::instance().filter_registered_tests(requested, to_be_skipped);
1✔
842
}
843

844
//static
845
std::string Test::temp_file_name(const std::string& basename) {
21✔
846
   // TODO add a --tmp-dir option to the tests to specify where these files go
847

848
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
849

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

853
   const int fd = ::mkstemp(mkstemp_basename.data());
21✔
854

855
   // error
856
   if(fd < 0) {
21✔
857
      return "";
×
858
   }
859

860
   ::close(fd);
21✔
861

862
   return mkstemp_basename;
21✔
863
#else
864
   // For now just create the temp in the current working directory
865
   return basename;
866
#endif
867
}
21✔
868

869
bool Test::copy_file(const std::string& from, const std::string& to) {
1✔
870
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(__cpp_lib_filesystem)
871
   std::error_code ec;  // don't throw, just return false on error
1✔
872
   return std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
1✔
873
#else
874
   // TODO: implement fallbacks to POSIX or WIN32
875
   // ... but then again: it's 2023 and we're using C++20 :o)
876
   BOTAN_UNUSED(from, to);
877
   throw Botan::No_Filesystem_Access();
878
#endif
879
}
880

881
std::string Test::read_data_file(const std::string& path) {
38✔
882
   const std::string fsname = Test::data_file(path);
38✔
883
   std::ifstream file(fsname.c_str());
38✔
884
   if(!file.good()) {
38✔
885
      throw Test_Error("Error reading from " + fsname);
×
886
   }
887

888
   return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
76✔
889
}
38✔
890

891
std::vector<uint8_t> Test::read_binary_data_file(const std::string& path) {
34✔
892
   const std::string fsname = Test::data_file(path);
34✔
893
   std::ifstream file(fsname.c_str(), std::ios::binary);
34✔
894
   if(!file.good()) {
34✔
895
      throw Test_Error("Error reading from " + fsname);
×
896
   }
897

898
   std::vector<uint8_t> contents;
34✔
899

900
   while(file.good()) {
74✔
901
      std::vector<uint8_t> buf(4096);
40✔
902
      file.read(reinterpret_cast<char*>(buf.data()), buf.size());
40✔
903
      const size_t got = static_cast<size_t>(file.gcount());
40✔
904

905
      if(got == 0 && file.eof()) {
40✔
906
         break;
907
      }
908

909
      contents.insert(contents.end(), buf.data(), buf.data() + got);
40✔
910
   }
40✔
911

912
   return contents;
68✔
913
}
34✔
914

915
// static member variables of Test
916

917
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
918
Test_Options Test::m_opts;
919
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
920
std::string Test::m_test_rng_seed;
921

922
//static
923
void Test::set_test_options(const Test_Options& opts) {
1✔
924
   m_opts = opts;
1✔
925
}
1✔
926

927
namespace {
928

929
/*
930
* This is a fast, simple, deterministic PRNG that's used for running
931
* the tests. It is not intended to be cryptographically secure.
932
*/
933
class Testsuite_RNG final : public Botan::RandomNumberGenerator {
8✔
934
   public:
935
      std::string name() const override { return "Testsuite_RNG"; }
×
936

937
      void clear() override { m_x = 0; }
×
938

939
      bool accepts_input() const override { return true; }
×
940

941
      bool is_seeded() const override { return true; }
276,934✔
942

943
      void fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) override {
10,266,969✔
944
         for(const auto byte : input) {
10,266,969✔
945
            mix(byte);
×
946
         }
947

948
         for(auto& byte : output) {
73,540,935✔
949
            byte = mix();
63,273,966✔
950
         }
951
      }
10,266,969✔
952

953
      Testsuite_RNG(std::string_view seed, std::string_view test_name) : m_x(0) {
277✔
954
         for(const char c : seed) {
8,310✔
955
            this->mix(static_cast<uint8_t>(c));
8,033✔
956
         }
957
         for(const char c : test_name) {
5,587✔
958
            this->mix(static_cast<uint8_t>(c));
5,310✔
959
         }
960
      }
277✔
961

962
   private:
963
      uint8_t mix(uint8_t input = 0) {
63,287,309✔
964
         m_x ^= input;
63,287,309✔
965
         m_x *= 0xF2E16957;
63,287,309✔
966
         m_x += 0xE50B590F;
63,287,309✔
967
         return static_cast<uint8_t>(m_x >> 27);
63,287,309✔
968
      }
969

970
      uint64_t m_x;
971
};
972

973
}  // namespace
974

975
//static
976
void Test::set_test_rng_seed(std::span<const uint8_t> seed, size_t epoch) {
1✔
977
   m_test_rng_seed = Botan::fmt("seed={} epoch={}", Botan::hex_encode(seed), epoch);
1✔
978
}
1✔
979

980
//static
981
std::unique_ptr<Botan::RandomNumberGenerator> Test::new_rng(std::string_view test_name) {
269✔
982
   return std::make_unique<Testsuite_RNG>(m_test_rng_seed, test_name);
269✔
983
}
984

985
//static
986
std::shared_ptr<Botan::RandomNumberGenerator> Test::new_shared_rng(std::string_view test_name) {
8✔
987
   return std::make_shared<Testsuite_RNG>(m_test_rng_seed, test_name);
8✔
988
}
989

990
//static
991
std::string Test::data_file(const std::string& file) {
773✔
992
   return options().data_dir() + "/" + file;
1,546✔
993
}
994

995
//static
996
std::string Test::data_dir(const std::string& subdir) {
1✔
997
   return options().data_dir() + "/" + subdir;
2✔
998
}
999

1000
//static
1001
std::vector<std::string> Test::files_in_data_dir(const std::string& subdir) {
393✔
1002
   auto fs = Botan::get_files_recursive(options().data_dir() + "/" + subdir);
1,179✔
1003
   if(fs.empty()) {
393✔
1004
      throw Test_Error("Test::files_in_data_dir encountered empty subdir " + subdir);
×
1005
   }
1006
   return fs;
393✔
1007
}
×
1008

1009
//static
1010
std::string Test::data_file_as_temporary_copy(const std::string& what) {
1✔
1011
   auto tmp_basename = what;
1✔
1012
   std::replace(tmp_basename.begin(), tmp_basename.end(), '/', '_');
1✔
1013
   auto temp_file = temp_file_name("tmp-" + tmp_basename);
1✔
1014
   if(temp_file.empty()) {
1✔
1015
      return "";
×
1016
   }
1017
   if(!Test::copy_file(data_file(what), temp_file)) {
1✔
1018
      return "";
×
1019
   }
1020
   return temp_file;
1✔
1021
}
1✔
1022

1023
//static
1024
std::vector<std::string> Test::provider_filter(const std::vector<std::string>& providers) {
49,047✔
1025
   if(m_opts.provider().empty()) {
49,047✔
1026
      return providers;
49,047✔
1027
   }
1028
   for(auto&& provider : providers) {
×
1029
      if(provider == m_opts.provider()) {
×
1030
         return std::vector<std::string>{provider};
×
1031
      }
1032
   }
1033
   return std::vector<std::string>{};
×
1034
}
×
1035

1036
std::string Test::random_password(Botan::RandomNumberGenerator& rng) {
222✔
1037
   const size_t len = 1 + rng.next_byte() % 32;
222✔
1038
   return Botan::hex_encode(rng.random_vec(len));
444✔
1039
}
1040

1041
size_t Test::random_index(Botan::RandomNumberGenerator& rng, size_t max) {
8,062✔
1042
   return Botan::load_be(rng.random_array<8>()) % max;
8,062✔
1043
}
1044

1045
void VarMap::clear() {
34,297✔
1046
   m_vars.clear();
×
1047
}
×
1048

1049
namespace {
1050

1051
bool varmap_pair_lt(const std::pair<std::string, std::string>& kv, std::string_view k) {
1,713,996✔
1052
   return kv.first < k;
1,713,996✔
1053
}
1054

1055
}  // namespace
1056

1057
bool VarMap::has_key(std::string_view key) const {
213,622✔
1058
   return get_opt_var(key).has_value();
213,622✔
1059
}
1060

1061
void VarMap::add(std::string_view key, std::string_view value) {
156,283✔
1062
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
156,283✔
1063

1064
   if(i != m_vars.end() && i->first == key) {
163,439✔
1065
      i->second = value;
44,405✔
1066
   } else {
1067
      m_vars.emplace(i, key, value);
111,878✔
1068
   }
1069
}
156,283✔
1070

1071
std::optional<std::string> VarMap::get_opt_var(std::string_view key) const {
308,915✔
1072
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
308,915✔
1073

1074
   if(i != m_vars.end() && i->first == key) {
310,716✔
1075
      return i->second;
239,010✔
1076
   } else {
1077
      return {};
69,905✔
1078
   }
1079
}
1080

1081
const std::string& VarMap::get_req_var(std::string_view key) const {
259,704✔
1082
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
259,704✔
1083

1084
   if(i != m_vars.end() && i->first == key) {
259,704✔
1085
      return i->second;
259,704✔
1086
   } else {
1087
      throw Test_Error(Botan::fmt("Test missing variable '{}'", key));
×
1088
   }
1089
}
1090

1091
std::string VarMap::get_req_str(std::string_view key) const {
52,801✔
1092
   return std::string(get_req_var(key));
52,801✔
1093
}
1094

1095
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(std::string_view key) const {
12✔
1096
   const auto& var = get_req_var(key);
12✔
1097

1098
   std::vector<std::vector<uint8_t>> bin_list;
12✔
1099

1100
   for(auto&& part : Botan::split_on(var, ',')) {
62✔
1101
      try {
50✔
1102
         bin_list.push_back(Botan::hex_decode(part));
100✔
1103
      } catch(std::exception& e) {
×
1104
         std::ostringstream oss;
×
1105
         oss << "Bad input '" << part << "'"
×
1106
             << " in binary list key " << key << " - " << e.what();
×
1107
         throw Test_Error(oss.str());
×
1108
      }
×
1109
   }
12✔
1110

1111
   return bin_list;
12✔
1112
}
×
1113

1114
std::vector<uint8_t> VarMap::get_req_bin(std::string_view key) const {
163,786✔
1115
   const auto& var = get_req_var(key);
163,786✔
1116

1117
   try {
163,786✔
1118
      if(var.starts_with("0x")) {
163,786✔
1119
         if(var.size() % 2 == 0) {
×
1120
            return Botan::hex_decode(var.substr(2));
×
1121
         } else {
1122
            std::string z = var;
×
1123
            std::swap(z[0], z[1]);  // swap 0x to x0 then remove x
×
1124
            return Botan::hex_decode(z.substr(1));
×
1125
         }
×
1126
      } else {
1127
         return Botan::hex_decode(var);
163,786✔
1128
      }
1129
   } catch(std::exception& e) {
×
1130
      std::ostringstream oss;
×
1131
      oss << "Bad input '" << var << "'"
×
1132
          << " for key " << key << " - " << e.what();
×
1133
      throw Test_Error(oss.str());
×
1134
   }
×
1135
}
×
1136

1137
std::string VarMap::get_opt_str(std::string_view key, std::string_view def_value) const {
14,378✔
1138
   if(auto v = get_opt_var(key)) {
14,378✔
1139
      return *v;
14,435✔
1140
   } else {
1141
      return std::string(def_value);
28,642✔
1142
   }
14,378✔
1143
}
1144

1145
bool VarMap::get_req_bool(std::string_view key) const {
39✔
1146
   const auto& var = get_req_var(key);
39✔
1147

1148
   if(var == "true") {
39✔
1149
      return true;
1150
   } else if(var == "false") {
23✔
1151
      return false;
1152
   } else {
1153
      throw Test_Error(Botan::fmt("Invalid boolean '{}' for key '{}'", var, key));
×
1154
   }
1155
}
1156

1157
size_t VarMap::get_req_sz(std::string_view key) const {
4,547✔
1158
   return Botan::to_u32bit(get_req_var(key));
4,547✔
1159
}
1160

1161
uint8_t VarMap::get_req_u8(std::string_view key) const {
17✔
1162
   const size_t s = this->get_req_sz(key);
17✔
1163
   if(s > 256) {
17✔
1164
      throw Test_Error(Botan::fmt("Invalid value for '{}' expected uint8_t but got '{}'", key, s));
×
1165
   }
1166
   return static_cast<uint8_t>(s);
17✔
1167
}
1168

1169
uint32_t VarMap::get_req_u32(std::string_view key) const {
14✔
1170
   return static_cast<uint32_t>(get_req_sz(key));
14✔
1171
}
1172

1173
uint64_t VarMap::get_req_u64(std::string_view key) const {
17✔
1174
   const auto& var = get_req_var(key);
17✔
1175
   try {
17✔
1176
      return std::stoull(var);
17✔
1177
   } catch(std::exception&) {
×
1178
      throw Test_Error("Invalid u64 value '" + var + "'");
×
1179
   }
×
1180
}
1181

1182
size_t VarMap::get_opt_sz(std::string_view key, const size_t def_value) const {
31,404✔
1183
   if(auto v = get_opt_var(key)) {
31,404✔
1184
      return Botan::to_u32bit(*v);
12,244✔
1185
   } else {
1186
      return def_value;
1187
   }
31,404✔
1188
}
1189

1190
uint64_t VarMap::get_opt_u64(std::string_view key, const uint64_t def_value) const {
3,538✔
1191
   if(auto v = get_opt_var(key)) {
3,538✔
1192
      try {
641✔
1193
         return std::stoull(*v);
3,538✔
1194
      } catch(std::exception&) {
×
1195
         throw Test_Error("Invalid u64 value '" + *v + "'");
×
1196
      }
×
1197
   } else {
1198
      return def_value;
1199
   }
3,538✔
1200
}
×
1201

1202
std::vector<uint8_t> VarMap::get_opt_bin(std::string_view key) const {
45,893✔
1203
   if(auto v = get_opt_var(key)) {
45,893✔
1204
      try {
16,134✔
1205
         return Botan::hex_decode(*v);
16,134✔
1206
      } catch(std::exception&) {
×
1207
         throw Test_Error(Botan::fmt("Invalid hex for key '{}' got '{}'", key, *v));
×
1208
      }
×
1209
   } else {
1210
      return {};
29,759✔
1211
   };
45,893✔
1212
}
1213

1214
#if defined(BOTAN_HAS_BIGINT)
1215
Botan::BigInt VarMap::get_req_bn(std::string_view key) const {
38,502✔
1216
   const auto& var = get_req_var(key);
38,502✔
1217

1218
   try {
38,502✔
1219
      return Botan::BigInt(var);
38,502✔
1220
   } catch(std::exception&) {
×
1221
      throw Test_Error(Botan::fmt("Invalid BigInt for key '{}' got '{}'", key, var));
×
1222
   }
×
1223
}
1224

1225
Botan::BigInt VarMap::get_opt_bn(std::string_view key, const Botan::BigInt& def_value) const {
80✔
1226
   if(auto v = get_opt_var(key)) {
80✔
1227
      try {
56✔
1228
         return Botan::BigInt(*v);
56✔
1229
      } catch(std::exception&) {
×
1230
         throw Test_Error(Botan::fmt("Invalid BigInt for key '{}' got '{}'", key, *v));
×
1231
      }
×
1232
   } else {
1233
      return def_value;
24✔
1234
   }
80✔
1235
}
1236
#endif
1237

1238
class Text_Based_Test::Text_Based_Test_Data {
1239
   public:
1240
      Text_Based_Test_Data(const std::string& data_src,
181✔
1241
                           const std::string& required_keys_str,
1242
                           const std::string& optional_keys_str) :
181✔
1243
            m_data_src(data_src) {
362✔
1244
         if(required_keys_str.empty()) {
181✔
1245
            throw Test_Error("Invalid test spec");
×
1246
         }
1247

1248
         m_required_keys = Botan::split_on(required_keys_str, ',');
181✔
1249
         std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
181✔
1250

1251
         m_all_keys.insert(m_required_keys.begin(), m_required_keys.end());
181✔
1252
         m_all_keys.insert(optional_keys.begin(), optional_keys.end());
181✔
1253
         m_output_key = m_required_keys.at(m_required_keys.size() - 1);
181✔
1254
      }
181✔
1255

1256
      std::string get_next_line();
1257

1258
      const std::string& current_source_name() const { return m_cur_src_name; }
×
1259

1260
      bool known_key(const std::string& key) const;
1261

1262
      const std::vector<std::string>& required_keys() const { return m_required_keys; }
48,404✔
1263

1264
      const std::string& output_key() const { return m_output_key; }
156,283✔
1265

1266
      const std::vector<std::string>& cpu_flags() const { return m_cpu_flags; }
48,265✔
1267

1268
      void set_cpu_flags(std::vector<std::string> flags) { m_cpu_flags = std::move(flags); }
21✔
1269

1270
      const std::string& initial_data_src_name() const { return m_data_src; }
181✔
1271

1272
   private:
1273
      std::string m_data_src;
1274
      std::vector<std::string> m_required_keys;
1275
      std::unordered_set<std::string> m_all_keys;
1276
      std::string m_output_key;
1277

1278
      bool m_first = true;
1279
      std::unique_ptr<std::istream> m_cur;
1280
      std::string m_cur_src_name;
1281
      std::deque<std::string> m_srcs;
1282
      std::vector<std::string> m_cpu_flags;
1283
};
1284

1285
Text_Based_Test::Text_Based_Test(const std::string& data_src,
181✔
1286
                                 const std::string& required_keys,
1287
                                 const std::string& optional_keys) :
181✔
1288
      m_data(std::make_unique<Text_Based_Test_Data>(data_src, required_keys, optional_keys)) {}
181✔
1289

1290
Text_Based_Test::~Text_Based_Test() = default;
181✔
1291

1292
std::string Text_Based_Test::Text_Based_Test_Data::get_next_line() {
157,290✔
1293
   while(true) {
157,548✔
1294
      if(m_cur == nullptr || m_cur->good() == false) {
157,548✔
1295
         if(m_srcs.empty()) {
450✔
1296
            if(m_first) {
362✔
1297
               if(m_data_src.ends_with(".vec")) {
181✔
1298
                  m_srcs.push_back(Test::data_file(m_data_src));
338✔
1299
               } else {
1300
                  const auto fs = Test::files_in_data_dir(m_data_src);
12✔
1301
                  m_srcs.assign(fs.begin(), fs.end());
12✔
1302
                  if(m_srcs.empty()) {
12✔
1303
                     throw Test_Error("Error reading test data dir " + m_data_src);
×
1304
                  }
1305
               }
12✔
1306

1307
               m_first = false;
181✔
1308
            } else {
1309
               return "";  // done
181✔
1310
            }
1311
         }
1312

1313
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
357✔
1314
         m_cur_src_name = m_srcs[0];
269✔
1315

1316
#if defined(BOTAN_HAS_CPUID)
1317
         // Reinit cpuid on new file if needed
1318
         if(m_cpu_flags.empty() == false) {
269✔
1319
            m_cpu_flags.clear();
19✔
1320
            Botan::CPUID::initialize();
19✔
1321
         }
1322
#endif
1323

1324
         if(!m_cur->good()) {
269✔
1325
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
1326
         }
1327

1328
         m_srcs.pop_front();
269✔
1329
      }
1330

1331
      while(m_cur->good()) {
227,971✔
1332
         std::string line;
227,713✔
1333
         std::getline(*m_cur, line);
227,713✔
1334

1335
         if(line.empty()) {
227,713✔
1336
            continue;
55,323✔
1337
         }
1338

1339
         if(line[0] == '#') {
172,390✔
1340
            if(line.starts_with("#test ")) {
15,302✔
1341
               return line;
21✔
1342
            } else {
1343
               continue;
15,281✔
1344
            }
1345
         }
1346

1347
         return line;
157,088✔
1348
      }
227,713✔
1349
   }
1350
}
1351

1352
bool Text_Based_Test::Text_Based_Test_Data::known_key(const std::string& key) const {
156,283✔
1353
   return m_all_keys.contains(key);
156,283✔
1354
}
1355

1356
namespace {
1357

1358
// strips leading and trailing but not internal whitespace
1359
std::string strip_ws(const std::string& in) {
312,566✔
1360
   const char* whitespace = " ";
312,566✔
1361

1362
   const auto first_c = in.find_first_not_of(whitespace);
312,566✔
1363
   if(first_c == std::string::npos) {
312,566✔
1364
      return "";
1,034✔
1365
   }
1366

1367
   const auto last_c = in.find_last_not_of(whitespace);
311,532✔
1368

1369
   return in.substr(first_c, last_c - first_c + 1);
311,532✔
1370
}
1371

1372
std::vector<std::string> parse_cpuid_bits(const std::vector<std::string>& tok) {
21✔
1373
   std::vector<std::string> bits;
21✔
1374

1375
#if defined(BOTAN_HAS_CPUID)
1376
   for(size_t i = 1; i < tok.size(); ++i) {
106✔
1377
      if(auto bit = Botan::CPUID::bit_from_string(tok[i])) {
85✔
1378
         bits.push_back(bit->to_string());
98✔
1379
      }
1380
   }
1381
#else
1382
   BOTAN_UNUSED(tok);
1383
#endif
1384

1385
   return bits;
21✔
1386
}
×
1387

1388
}  // namespace
1389

1390
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) {
32,625✔
1391
   return false;
32,625✔
1392
}
1393

1394
std::vector<Test::Result> Text_Based_Test::run() {
181✔
1395
   std::vector<Test::Result> results;
181✔
1396

1397
   std::string header;
181✔
1398
   std::string header_or_name = m_data->initial_data_src_name();
181✔
1399
   VarMap vars;
181✔
1400
   size_t test_cnt = 0;
181✔
1401

1402
   while(true) {
157,290✔
1403
      const std::string line = m_data->get_next_line();
157,290✔
1404
      if(line.empty()) {
157,290✔
1405
         // EOF
1406
         break;
1407
      }
1408

1409
      if(line.starts_with("#test ")) {
157,109✔
1410
         std::vector<std::string> pragma_tokens = Botan::split_on(line.substr(6), ' ');
21✔
1411

1412
         if(pragma_tokens.empty()) {
21✔
1413
            throw Test_Error("Empty pragma found in " + m_data->current_source_name());
×
1414
         }
1415

1416
         if(pragma_tokens[0] != "cpuid") {
21✔
1417
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1418
         }
1419

1420
         if(!Test_Registry::instance().needs_serialization(this->test_name())) {
42✔
1421
            throw Test_Error(Botan::fmt("'{}' used cpuid control but is not serialized", this->test_name()));
×
1422
         }
1423

1424
         m_data->set_cpu_flags(parse_cpuid_bits(pragma_tokens));
42✔
1425

1426
         continue;
21✔
1427
      } else if(line[0] == '#') {
157,109✔
1428
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1429
      }
1430

1431
      if(line[0] == '[' && line[line.size() - 1] == ']') {
157,088✔
1432
         header = line.substr(1, line.size() - 2);
805✔
1433
         header_or_name = header;
805✔
1434
         test_cnt = 0;
805✔
1435
         vars.clear();
805✔
1436
         continue;
805✔
1437
      }
1438

1439
      const std::string test_id = "test " + std::to_string(test_cnt);
312,566✔
1440

1441
      auto equal_i = line.find_first_of('=');
156,283✔
1442

1443
      if(equal_i == std::string::npos) {
156,283✔
1444
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1445
         continue;
×
1446
      }
1447

1448
      const std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
312,566✔
1449
      const std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
312,566✔
1450

1451
      if(!m_data->known_key(key)) {
156,283✔
1452
         auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key));
×
1453
         results.push_back(r);
×
1454
      }
×
1455

1456
      vars.add(key, val);
156,283✔
1457

1458
      if(key == m_data->output_key()) {
156,283✔
1459
         try {
48,404✔
1460
            for(const auto& req_key : m_data->required_keys()) {
245,618✔
1461
               if(!vars.has_key(req_key)) {
197,214✔
1462
                  auto r =
×
1463
                     Test::Result::Failure(header_or_name, Botan::fmt("{} missing required key {}", test_id, req_key));
×
1464
                  results.push_back(r);
×
1465
               }
×
1466
            }
1467

1468
            if(skip_this_test(header, vars)) {
48,404✔
1469
               continue;
139✔
1470
            }
1471

1472
            ++test_cnt;
48,265✔
1473

1474
            const uint64_t start = Test::timestamp();
48,265✔
1475

1476
            Test::Result result = run_one_test(header, vars);
48,265✔
1477
#if defined(BOTAN_HAS_CPUID)
1478
            if(!m_data->cpu_flags().empty()) {
48,265✔
1479
               for(const auto& cpuid_str : m_data->cpu_flags()) {
30,651✔
1480
                  if(const auto bit = Botan::CPUID::Feature::from_string(cpuid_str)) {
21,698✔
1481
                     if(Botan::CPUID::has(*bit)) {
21,698✔
1482
                        Botan::CPUID::clear_cpuid_bit(*bit);
16,586✔
1483
                        // now re-run the test
1484
                        result.merge(run_one_test(header, vars));
16,586✔
1485
                     }
1486
                  }
1487
               }
1488
               Botan::CPUID::initialize();
8,953✔
1489
            }
1490
#endif
1491
            result.set_ns_consumed(Test::timestamp() - start);
48,265✔
1492

1493
            if(result.tests_failed() > 0) {
48,265✔
1494
               std::ostringstream oss;
×
1495
               oss << "Test # " << test_cnt << " ";
×
1496
               if(!header.empty()) {
×
1497
                  oss << header << " ";
×
1498
               }
1499
               oss << "failed ";
×
1500

1501
               for(const auto& k : m_data->required_keys()) {
×
1502
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1503
               }
1504

1505
               result.test_note(oss.str());
×
1506
            }
×
1507
            results.push_back(result);
48,265✔
1508
         } catch(std::exception& e) {
48,265✔
1509
            std::ostringstream oss;
×
1510
            oss << "Test # " << test_cnt << " ";
×
1511
            if(!header.empty()) {
×
1512
               oss << header << " ";
×
1513
            }
1514

1515
            for(const auto& k : m_data->required_keys()) {
×
1516
               oss << k << "=" << vars.get_req_str(k) << " ";
×
1517
            }
1518

1519
            oss << "failed with exception '" << e.what() << "'";
×
1520

1521
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1522
         }
×
1523

1524
         if(clear_between_callbacks()) {
48,265✔
1525
            vars.clear();
189,636✔
1526
         }
1527
      }
1528
   }
157,387✔
1529

1530
   if(results.empty()) {
181✔
1531
      return results;
1532
   }
1533

1534
   try {
181✔
1535
      std::vector<Test::Result> final_tests = run_final_tests();
181✔
1536
      results.insert(results.end(), final_tests.begin(), final_tests.end());
181✔
1537
   } catch(std::exception& e) {
181✔
1538
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1539
   }
×
1540

1541
   return results;
1542
}
181✔
1543

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