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

randombit / botan / 25619874939

09 May 2026 05:34PM UTC coverage: 89.328% (-0.002%) from 89.33%
25619874939

push

github

web-flow
Merge pull request #5591 from randombit/jack/gha-cache-cleanup

In GH Actions clean up branch caches after the PRs are merged

107641 of 120501 relevant lines covered (89.33%)

11279629.67 hits per line

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

80.9
/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;
438✔
59

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

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

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

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

96
void Test::Result::end_timer() {
1,305✔
97
   if(m_started > 0) {
1,305✔
98
      m_ns_taken += Test::timestamp() - m_started;
2,384✔
99
      m_started = 0;
1,192✔
100
   }
101
}
1,305✔
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) {
624✔
112
   m_log.emplace_back(Botan::fmt("{} {}", who(), note));
624✔
113
}
624✔
114

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

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

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

131
Test::Result::ThrowExpectations::~ThrowExpectations() {
69,132✔
132
   BOTAN_ASSERT_NOMSG(m_consumed);
69,132✔
133
}
131,862✔
134

135
void Test::Result::ThrowExpectations::assert_that_success_is_not_expected() const {
62,730✔
136
   BOTAN_ASSERT_NOMSG(!m_expect_success);
62,511✔
137
}
62,511✔
138

139
Test::Result::ThrowExpectations& Test::Result::ThrowExpectations::expect_success() {
1,647✔
140
   BOTAN_ASSERT_NOMSG(!m_expected_message && !m_expected_exception_check_fn);
1,647✔
141
   m_expect_success = true;
1,647✔
142
   return *this;
1,647✔
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) {
69,132✔
152
   m_consumed = true;
69,132✔
153

154
   try {
69,132✔
155
      m_fn();
69,132✔
156
      if(!m_expect_success) {
1,648✔
157
         return result.test_failure(Botan::fmt("{} failed to throw expected exception", test_name));
2✔
158
      }
159
   } catch(const std::exception& ex) {
67,484✔
160
      if(m_expect_success) {
67,482✔
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())) {
192,503✔
164
         return result.test_failure(Botan::fmt("{} threw unexpected exception: {}", test_name, ex.what()));
2✔
165
      }
166
      if(m_expected_message.has_value()) {
67,479✔
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(...) {
67,484✔
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();
69,125✔
184
}
185

186
bool Test::Result::test_throws(std::string_view what, std::function<void()> fn) {
4,770✔
187
   return ThrowExpectations(std::move(fn)).check(what, *this);
14,310✔
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,647✔
195
   return ThrowExpectations(std::move(fn)).expect_success().check(what, *this);
4,941✔
196
}
197

198
bool Test::Result::test_success(std::string_view note) {
3,815,640✔
199
   if(Test::options().log_success()) {
3,815,624✔
200
      test_note(note);
×
201
   }
202
   ++m_tests_passed;
3,815,640✔
203
   return true;
69,125✔
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) {
310,044✔
238
   if(x.size() != y.size()) {
1,440✔
239
      return false;
240
   }
241
   if(x.empty()) {
310,043✔
242
      return true;
243
   }
244

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

248
}  // namespace
249

250
bool Test::Result::test_bin_ne(std::string_view what,
3,408✔
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,848✔
254
      return test_failure(Botan::fmt("{} {} produced matching bytes", who(), what));
1✔
255
   }
256
   return test_success();
3,407✔
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,
308,604✔
267
                               std::span<const uint8_t> produced,
268
                               std::span<const uint8_t> expected) {
269
   if(same_contents(produced, expected)) {
615,764✔
270
      return test_success();
308,603✔
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,363✔
303
   if(produced.empty()) {
39,363✔
304
      return test_failure(what, "was empty");
1✔
305
   } else {
306
      return test_success();
39,362✔
307
   }
308
}
309

310
bool Test::Result::test_str_eq(std::string_view what, std::string_view produced, std::string_view expected) {
77,928✔
311
   if(produced == expected) {
77,928✔
312
      return test_success();
77,928✔
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) {
162,500✔
343
   return test_sz_eq(what, produced, expected);
162,500✔
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,792✔
351
   return test_sz_eq(what, produced, expected);
66,792✔
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,201✔
359
   return test_sz_eq(what, produced, expected);
4,201✔
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,550✔
367
   if(produced == expected) {
1,550✔
368
      return test_success();
1,550✔
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,973✔
383
   if(produced == expected) {
310,973✔
384
      return test_success();
310,972✔
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,
9✔
445
                                   std::optional<uint64_t> produced,
446
                                   std::optional<uint64_t> expected) {
447
   if(produced.has_value() and !expected.has_value()) {
9✔
448
      return test_failure(Botan::fmt("Assertion {} produced value {} but nullopt was expected", what, *produced));
×
449
   } else if(!produced.has_value() && expected.has_value()) {
9✔
450
      return test_failure(Botan::fmt("Assertion {} produced nullopt but {} was expected", what, *expected));
×
451
   } else if(produced.has_value() && expected.has_value()) {
9✔
452
      return test_u64_eq(what, *produced, *expected);
9✔
453
   } else {
454
      return test_success();
×
455
   }
456
}
457

458
#if defined(BOTAN_HAS_BIGINT)
459
bool Test::Result::test_bn_eq(std::string_view what, const BigInt& produced, const BigInt& expected) {
252,674✔
460
   if(produced == expected) {
252,674✔
461
      return test_success();
252,673✔
462
   } else {
463
      std::ostringstream err;
1✔
464
      err << who() << " " << what << " produced " << produced << " != expected value " << expected;
1✔
465
      return test_failure(err.str());
1✔
466
   }
1✔
467
}
468

469
bool Test::Result::test_bn_ne(std::string_view what, const BigInt& produced, const BigInt& expected) {
97✔
470
   if(produced != expected) {
97✔
471
      return test_success();
96✔
472
   } else {
473
      std::ostringstream err;
1✔
474
      err << who() << " " << what << " produced " << produced << " prohibited value";
1✔
475
      return test_failure(err.str());
1✔
476
   }
1✔
477
}
478
#endif
479

480
bool Test::Result::test_bool_eq(std::string_view what, bool produced, bool expected) {
432,351✔
481
   if(produced == expected) {
432,351✔
482
      return test_success();
432,351✔
483
   } else {
484
      if(expected == true) {
×
485
         return test_failure(Botan::fmt("Assertion failure in {}, {} was unexpectedly false", who(), what));
×
486
      } else {
487
         return test_failure(Botan::fmt("Assertion failure in {}, {} was unexpectedly true", who(), what));
×
488
      }
489
   }
490
}
491

492
bool Test::Result::test_is_true(std::string_view what, bool produced) {
288,228✔
493
   return test_bool_eq(what, produced, true);
288,228✔
494
}
495

496
bool Test::Result::test_is_false(std::string_view what, bool produced) {
136,507✔
497
   return test_bool_eq(what, produced, false);
136,507✔
498
}
499

500
bool Test::Result::test_rc_ok(std::string_view func, int rc) {
2,912✔
501
   if(rc != 0) {
2,912✔
502
      std::ostringstream err;
1✔
503
      err << m_who << " " << func << " unexpectedly failed with error code " << rc;
1✔
504
      return test_failure(err.str());
1✔
505
   }
1✔
506

507
   return test_success();
2,911✔
508
}
509

510
bool Test::Result::test_rc_fail(std::string_view func, std::string_view why, int rc) {
26✔
511
   if(rc == 0) {
26✔
512
      std::ostringstream err;
1✔
513
      err << m_who << " call to " << func << " unexpectedly succeeded expecting failure because " << why;
1✔
514
      return test_failure(err.str());
1✔
515
   }
1✔
516

517
   return test_success();
25✔
518
}
519

520
bool Test::Result::test_rc_init(std::string_view func, int rc) {
121✔
521
   if(rc == 0) {
121✔
522
      return test_success();
121✔
523
   } else {
524
      std::ostringstream msg;
×
525
      msg << m_who;
×
526
      msg << " " << func;
×
527

528
      // -40 is BOTAN_FFI_ERROR_NOT_IMPLEMENTED
529
      if(rc == -40) {
×
530
         msg << " returned not implemented";
×
531
      } else {
532
         msg << " unexpectedly failed with error code " << rc;
×
533
      }
534

535
      if(rc == -40) {
×
536
         this->test_note(msg.str());
×
537
      } else {
538
         this->test_failure(msg.str());
×
539
      }
540
      return false;
×
541
   }
×
542
}
543

544
bool Test::Result::test_rc(std::string_view func, int rc, int expected) {
451✔
545
   if(expected != rc) {
451✔
546
      std::ostringstream err;
1✔
547
      err << m_who;
1✔
548
      err << " call to " << func << " unexpectedly returned " << rc;
1✔
549
      err << " but expecting " << expected;
1✔
550
      return test_failure(err.str());
1✔
551
   }
1✔
552

553
   return test_success();
450✔
554
}
555

556
void Test::initialize(std::string test_name, CodeLocation location) {
438✔
557
   m_test_name = std::move(test_name);
438✔
558
   m_registration_location = location;
438✔
559
}
438✔
560

561
Botan::RandomNumberGenerator& Test::rng() const {
463,510✔
562
   if(!m_test_rng) {
463,510✔
563
      m_test_rng = Test::new_rng(m_test_name);
147✔
564
   }
565

566
   return *m_test_rng;
463,510✔
567
}
568

569
std::optional<std::string> Test::supported_ec_group_name(std::vector<std::string> preferred_groups) {
151✔
570
#if defined(BOTAN_HAS_ECC_GROUP)
571
   if(preferred_groups.empty()) {
151✔
572
      preferred_groups = {
149✔
573
         "secp256r1",
574
         "brainpool256r1",
575
         "secp384r1",
576
         "brainpool384r1",
577
         "secp521r1",
578
         "brainpool512r1",
579
      };
1,192✔
580
   }
581

582
   for(const auto& group : preferred_groups) {
151✔
583
      if(Botan::EC_Group::supports_named_group(group)) {
151✔
584
         return group;
151✔
585
      }
586
   }
587
#else
588
   BOTAN_UNUSED(preferred_groups);
589
#endif
590

591
   return std::nullopt;
×
592
}
298✔
593

594
std::vector<uint8_t> Test::mutate_vec(const std::vector<uint8_t>& v,
94,828✔
595
                                      Botan::RandomNumberGenerator& rng,
596
                                      bool maybe_resize,
597
                                      size_t min_offset) {
598
   std::vector<uint8_t> r = v;
94,828✔
599

600
   if(maybe_resize && (r.empty() || rng.next_byte() < 32)) {
108,462✔
601
      // TODO: occasionally truncate, insert at random index
602
      const size_t add = 1 + (rng.next_byte() % 16);
2,147✔
603
      r.resize(r.size() + add);
2,147✔
604
      rng.randomize(&r[r.size() - add], add);
2,147✔
605
   }
606

607
   if(r.size() > min_offset) {
94,828✔
608
      const size_t offset = std::max<size_t>(min_offset, rng.next_byte() % r.size());
93,290✔
609
      const uint8_t perturb = rng.next_nonzero_byte();
93,290✔
610
      r[offset] ^= perturb;
93,290✔
611
   }
612

613
   return r;
94,828✔
614
}
×
615

616
std::vector<std::string> Test::possible_providers(const std::string& /*alg*/) {
×
617
   return Test::provider_filter({"base"});
×
618
}
619

620
//static
621
std::string Test::format_time(uint64_t nanoseconds) {
1,494✔
622
   std::ostringstream o;
1,494✔
623

624
   if(nanoseconds > 1000000000) {
1,494✔
625
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000000.0 << " sec";
157✔
626
   } else {
627
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000.0 << " msec";
1,337✔
628
   }
629

630
   return o.str();
2,988✔
631
}
1,494✔
632

633
// TODO: this should move to `StdoutReporter`
634
std::string Test::Result::result_string() const {
2,690✔
635
   const bool verbose = Test::options().verbose();
2,690✔
636

637
   if(tests_run() == 0 && !verbose) {
2,690✔
638
      return "";
20✔
639
   }
640

641
   std::ostringstream report;
2,670✔
642

643
   report << who() << " ran ";
2,670✔
644

645
   if(tests_run() == 0) {
2,670✔
646
      report << "ZERO";
×
647
   } else {
648
      report << tests_run();
2,670✔
649
   }
650
   report << " tests";
2,670✔
651

652
   if(m_ns_taken > 0) {
2,670✔
653
      report << " in " << format_time(m_ns_taken);
2,986✔
654
   }
655

656
   if(tests_failed() > 0) {
2,670✔
657
      report << " " << tests_failed() << " FAILED";
24✔
658
   } else {
659
      report << " all ok";
2,646✔
660
   }
661

662
   report << "\n";
2,670✔
663

664
   for(size_t i = 0; i != m_fail_log.size(); ++i) {
2,694✔
665
      report << "Failure " << (i + 1) << ": " << m_fail_log[i];
24✔
666
      if(m_where) {
24✔
667
         report << " (at " << m_where->path << ":" << m_where->line << ")";
×
668
      }
669
      report << "\n";
24✔
670
   }
671

672
   if(!m_fail_log.empty() || tests_run() == 0 || verbose) {
2,670✔
673
      for(size_t i = 0; i != m_log.size(); ++i) {
24✔
674
         report << "Note " << (i + 1) << ": " << m_log[i] << "\n";
×
675
      }
676
   }
677

678
   return report.str();
2,670✔
679
}
2,670✔
680

681
namespace {
682

683
class Test_Registry {
684
   public:
685
      static Test_Registry& instance() {
1,341✔
686
         static Test_Registry registry;
1,342✔
687
         return registry;
1,341✔
688
      }
689

690
      void register_test(const std::string& category,
438✔
691
                         const std::string& name,
692
                         bool smoke_test,
693
                         bool needs_serialization,
694
                         std::function<std::unique_ptr<Test>()> maker_fn) {
695
         if(m_tests.contains(name)) {
438✔
696
            throw Test_Error("Duplicate registration of test '" + name + "'");
×
697
         }
698

699
         if(m_tests.contains(category)) {
438✔
700
            throw Test_Error("'" + category + "' cannot be used as category, test exists");
×
701
         }
702

703
         if(m_categories.contains(name)) {
438✔
704
            throw Test_Error("'" + name + "' cannot be used as test name, category exists");
×
705
         }
706

707
         if(smoke_test) {
438✔
708
            m_smoke_tests.push_back(name);
10✔
709
         }
710

711
         if(needs_serialization) {
438✔
712
            m_mutexed_tests.push_back(name);
22✔
713
         }
714

715
         m_tests.emplace(name, std::move(maker_fn));
438✔
716
         m_categories.emplace(category, name);
438✔
717
      }
438✔
718

719
      std::unique_ptr<Test> get_test(const std::string& test_name) const {
438✔
720
         auto i = m_tests.find(test_name);
438✔
721
         if(i != m_tests.end()) {
438✔
722
            return i->second();
438✔
723
         }
724
         return nullptr;
×
725
      }
726

727
      std::vector<std::string> registered_tests() const {
×
728
         std::vector<std::string> s;
×
729
         s.reserve(m_tests.size());
×
730
         for(auto&& i : m_tests) {
×
731
            s.push_back(i.first);
×
732
         }
733
         return s;
×
734
      }
×
735

736
      std::vector<std::string> registered_test_categories() const {
×
737
         std::set<std::string> s;
×
738
         for(auto&& i : m_categories) {
×
739
            s.insert(i.first);
×
740
         }
741
         return std::vector<std::string>(s.begin(), s.end());
×
742
      }
×
743

744
      std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
1✔
745
                                                       const std::vector<std::string>& to_be_skipped) {
746
         std::vector<std::string> result;
1✔
747

748
         std::set<std::string> to_be_skipped_set(to_be_skipped.begin(), to_be_skipped.end());
1✔
749
         // TODO: this is O(n^2), but we have a relatively small number of tests.
750
         auto insert_if_not_exists_and_not_skipped = [&](const std::string& test_name) {
439✔
751
            if(!Botan::value_exists(result, test_name) && !to_be_skipped_set.contains(test_name)) {
876✔
752
               result.push_back(test_name);
428✔
753
            }
754
         };
439✔
755

756
         if(requested.empty()) {
1✔
757
            /*
758
            If nothing was requested on the command line, run everything. First
759
            run the "essentials" to smoke test, then everything else in
760
            alphabetical order.
761
            */
762
            result = m_smoke_tests;
1✔
763
            for(const auto& [test_name, _] : m_tests) {
439✔
764
               insert_if_not_exists_and_not_skipped(test_name);
438✔
765
            }
766
         } else {
767
            for(const auto& r : requested) {
×
768
               if(m_tests.contains(r)) {
×
769
                  insert_if_not_exists_and_not_skipped(r);
×
770
               } else if(auto elems = m_categories.equal_range(r); elems.first != m_categories.end()) {
×
771
                  for(; elems.first != elems.second; ++elems.first) {
×
772
                     insert_if_not_exists_and_not_skipped(elems.first->second);
×
773
                  }
774
               } else {
775
                  throw Test_Error("Unknown test suite or category: " + r);
×
776
               }
777
            }
778
         }
779

780
         return result;
1✔
781
      }
1✔
782

783
      bool needs_serialization(const std::string& test_name) const {
464✔
784
         return Botan::value_exists(m_mutexed_tests, test_name);
26✔
785
      }
786

787
   private:
788
      Test_Registry() = default;
1✔
789

790
   private:
791
      std::map<std::string, std::function<std::unique_ptr<Test>()>> m_tests;
792
      std::multimap<std::string, std::string> m_categories;
793
      std::vector<std::string> m_smoke_tests;
794
      std::vector<std::string> m_mutexed_tests;
795
};
796

797
}  // namespace
798

799
// static Test:: functions
800

801
//static
802
void Test::register_test(const std::string& category,
438✔
803
                         const std::string& name,
804
                         bool smoke_test,
805
                         bool needs_serialization,
806
                         std::function<std::unique_ptr<Test>()> maker_fn) {
807
   Test_Registry::instance().register_test(category, name, smoke_test, needs_serialization, std::move(maker_fn));
876✔
808
}
438✔
809

810
//static
811
uint64_t Test::timestamp() {
181,193✔
812
   auto now = std::chrono::system_clock::now().time_since_epoch();
181,193✔
813
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
2,385✔
814
}
815

816
//static
817
std::vector<Test::Result> Test::flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists) {
4✔
818
   std::vector<Test::Result> results;
4✔
819
   for(auto& result_list : result_lists) {
26✔
820
      for(auto& result : result_list) {
71✔
821
         results.emplace_back(std::move(result));
49✔
822
      }
823
   }
824
   return results;
4✔
825
}
×
826

827
//static
828
std::vector<std::string> Test::registered_tests() {
×
829
   return Test_Registry::instance().registered_tests();
×
830
}
831

832
//static
833
std::vector<std::string> Test::registered_test_categories() {
×
834
   return Test_Registry::instance().registered_test_categories();
×
835
}
836

837
//static
838
std::unique_ptr<Test> Test::get_test(const std::string& test_name) {
438✔
839
   return Test_Registry::instance().get_test(test_name);
438✔
840
}
841

842
//static
843
bool Test::test_needs_serialization(const std::string& test_name) {
438✔
844
   return Test_Registry::instance().needs_serialization(test_name);
438✔
845
}
846

847
//static
848
std::vector<std::string> Test::filter_registered_tests(const std::vector<std::string>& requested,
1✔
849
                                                       const std::vector<std::string>& to_be_skipped) {
850
   return Test_Registry::instance().filter_registered_tests(requested, to_be_skipped);
1✔
851
}
852

853
//static
854
std::string Test::temp_file_name(const std::string& basename) {
21✔
855
   // TODO add a --tmp-dir option to the tests to specify where these files go
856

857
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
858

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

862
   const int fd = ::mkstemp(mkstemp_basename.data());
21✔
863

864
   // error
865
   if(fd < 0) {
21✔
866
      return "";
×
867
   }
868

869
   ::close(fd);
21✔
870

871
   return mkstemp_basename;
21✔
872
#else
873
   // For now just create the temp in the current working directory
874
   return basename;
875
#endif
876
}
21✔
877

878
bool Test::copy_file(const std::string& from, const std::string& to) {
1✔
879
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(__cpp_lib_filesystem)
880
   std::error_code ec;  // don't throw, just return false on error
1✔
881
   return std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
1✔
882
#else
883
   // TODO: implement fallbacks to POSIX or WIN32
884
   // ... but then again: it's 2023 and we're using C++20 :o)
885
   BOTAN_UNUSED(from, to);
886
   throw Botan::No_Filesystem_Access();
887
#endif
888
}
889

890
std::string Test::read_data_file(const std::string& path) {
38✔
891
   const std::string fsname = Test::data_file(path);
38✔
892
   std::ifstream file(fsname.c_str());
38✔
893
   if(!file.good()) {
38✔
894
      throw Test_Error("Error reading from " + fsname);
×
895
   }
896

897
   return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
76✔
898
}
38✔
899

900
std::vector<uint8_t> Test::read_binary_data_file(const std::string& path) {
39✔
901
   const std::string fsname = Test::data_file(path);
39✔
902
   std::ifstream file(fsname.c_str(), std::ios::binary);
39✔
903
   if(!file.good()) {
39✔
904
      throw Test_Error("Error reading from " + fsname);
×
905
   }
906

907
   std::vector<uint8_t> contents;
39✔
908

909
   while(file.good()) {
84✔
910
      std::vector<uint8_t> buf(4096);
45✔
911
      file.read(reinterpret_cast<char*>(buf.data()), buf.size());
45✔
912
      const size_t got = static_cast<size_t>(file.gcount());
45✔
913

914
      if(got == 0 && file.eof()) {
45✔
915
         break;
916
      }
917

918
      contents.insert(contents.end(), buf.data(), buf.data() + got);
45✔
919
   }
45✔
920

921
   return contents;
78✔
922
}
39✔
923

924
// static member variables of Test
925

926
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
927
Test_Options Test::m_opts;
928
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
929
std::string Test::m_test_rng_seed;
930

931
//static
932
void Test::set_test_options(const Test_Options& opts) {
1✔
933
   m_opts = opts;
1✔
934
}
1✔
935

936
namespace {
937

938
/*
939
* This is a fast, simple, deterministic PRNG that's used for running
940
* the tests. It is not intended to be cryptographically secure.
941
*/
942
class Testsuite_RNG final : public Botan::RandomNumberGenerator {
9✔
943
   public:
944
      std::string name() const override { return "Testsuite_RNG"; }
×
945

946
      void clear() override { m_x = 0; }
×
947

948
      bool accepts_input() const override { return true; }
×
949

950
      bool is_seeded() const override { return true; }
278,101✔
951

952
      void fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) override {
10,250,776✔
953
         for(const auto byte : input) {
10,250,776✔
954
            mix(byte);
×
955
         }
956

957
         for(auto& byte : output) {
73,382,055✔
958
            byte = mix();
63,131,279✔
959
         }
960
      }
10,250,776✔
961

962
      Testsuite_RNG(std::string_view seed, std::string_view test_name) : m_x(0) {
901✔
963
         for(const char c : seed) {
27,030✔
964
            this->mix(static_cast<uint8_t>(c));
26,129✔
965
         }
966
         for(const char c : test_name) {
37,458✔
967
            this->mix(static_cast<uint8_t>(c));
36,557✔
968
         }
969
      }
901✔
970

971
   private:
972
      uint8_t mix(uint8_t input = 0) {
63,193,965✔
973
         m_x ^= input;
63,193,965✔
974
         m_x *= 0xF2E16957;
63,193,965✔
975
         m_x += 0xE50B590F;
63,193,965✔
976
         return static_cast<uint8_t>(m_x >> 27);
63,193,965✔
977
      }
978

979
      uint64_t m_x;
980
};
981

982
}  // namespace
983

984
//static
985
void Test::set_test_rng_seed(std::span<const uint8_t> seed, size_t epoch) {
1✔
986
   m_test_rng_seed = Botan::fmt("seed={} epoch={}", Botan::hex_encode(seed), epoch);
1✔
987
}
1✔
988

989
//static
990
std::unique_ptr<Botan::RandomNumberGenerator> Test::new_rng(std::string_view test_name) {
892✔
991
   return std::make_unique<Testsuite_RNG>(m_test_rng_seed, test_name);
892✔
992
}
993

994
//static
995
std::shared_ptr<Botan::RandomNumberGenerator> Test::new_shared_rng(std::string_view test_name) {
9✔
996
   return std::make_shared<Testsuite_RNG>(m_test_rng_seed, test_name);
9✔
997
}
998

999
//static
1000
std::string Test::data_file(const std::string& file) {
862✔
1001
   return options().data_dir() + "/" + file;
1,724✔
1002
}
1003

1004
//static
1005
std::string Test::data_dir(const std::string& subdir) {
1✔
1006
   return options().data_dir() + "/" + subdir;
2✔
1007
}
1008

1009
//static
1010
std::vector<std::string> Test::files_in_data_dir(const std::string& subdir) {
394✔
1011
   auto fs = Botan::get_files_recursive(options().data_dir() + "/" + subdir);
1,182✔
1012
   if(fs.empty()) {
394✔
1013
      throw Test_Error("Test::files_in_data_dir encountered empty subdir " + subdir);
×
1014
   }
1015
   return fs;
394✔
1016
}
×
1017

1018
//static
1019
std::string Test::data_file_as_temporary_copy(const std::string& what) {
1✔
1020
   auto tmp_basename = what;
1✔
1021
   std::replace(tmp_basename.begin(), tmp_basename.end(), '/', '_');
1✔
1022
   auto temp_file = temp_file_name("tmp-" + tmp_basename);
1✔
1023
   if(temp_file.empty()) {
1✔
1024
      return "";
×
1025
   }
1026
   if(!Test::copy_file(data_file(what), temp_file)) {
1✔
1027
      return "";
×
1028
   }
1029
   return temp_file;
1✔
1030
}
1✔
1031

1032
//static
1033
std::vector<std::string> Test::provider_filter(const std::vector<std::string>& providers) {
49,510✔
1034
   if(m_opts.provider().empty()) {
49,510✔
1035
      return providers;
49,510✔
1036
   }
1037
   for(auto&& provider : providers) {
×
1038
      if(provider == m_opts.provider()) {
×
1039
         return std::vector<std::string>{provider};
×
1040
      }
1041
   }
1042
   return std::vector<std::string>{};
×
1043
}
×
1044

1045
std::string Test::random_password(Botan::RandomNumberGenerator& rng) {
222✔
1046
   const size_t len = 1 + rng.next_byte() % 32;
222✔
1047
   return Botan::hex_encode(rng.random_vec(len));
444✔
1048
}
1049

1050
size_t Test::random_index(Botan::RandomNumberGenerator& rng, size_t max) {
8,062✔
1051
   return Botan::load_be(rng.random_array<8>()) % max;
8,062✔
1052
}
1053

1054
void VarMap::clear() {
34,118✔
1055
   m_vars.clear();
×
1056
}
×
1057

1058
namespace {
1059

1060
bool varmap_pair_lt(const std::pair<std::string, std::string>& kv, std::string_view k) {
1,688,194✔
1061
   return kv.first < k;
1,688,194✔
1062
}
1063

1064
}  // namespace
1065

1066
bool VarMap::has_key(std::string_view key) const {
213,139✔
1067
   return get_opt_var(key).has_value();
213,139✔
1068
}
1069

1070
void VarMap::add(std::string_view key, std::string_view value) {
155,778✔
1071
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
155,778✔
1072

1073
   if(i != m_vars.end() && i->first == key) {
162,969✔
1074
      i->second = value;
44,675✔
1075
   } else {
1076
      m_vars.emplace(i, key, value);
111,103✔
1077
   }
1078
}
155,778✔
1079

1080
std::optional<std::string> VarMap::get_opt_var(std::string_view key) const {
293,120✔
1081
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
293,120✔
1082

1083
   if(i != m_vars.end() && i->first == key) {
294,922✔
1084
      return i->second;
240,663✔
1085
   } else {
1086
      return {};
52,457✔
1087
   }
1088
}
1089

1090
const std::string& VarMap::get_req_var(std::string_view key) const {
261,110✔
1091
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
261,110✔
1092

1093
   if(i != m_vars.end() && i->first == key) {
261,110✔
1094
      return i->second;
261,110✔
1095
   } else {
1096
      throw Test_Error(Botan::fmt("Test missing variable '{}'", key));
×
1097
   }
1098
}
1099

1100
std::string VarMap::get_req_str(std::string_view key) const {
53,171✔
1101
   return std::string(get_req_var(key));
53,171✔
1102
}
1103

1104
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(std::string_view key) const {
12✔
1105
   const auto& var = get_req_var(key);
12✔
1106

1107
   std::vector<std::vector<uint8_t>> bin_list;
12✔
1108

1109
   for(auto&& part : Botan::split_on(var, ',')) {
62✔
1110
      try {
50✔
1111
         bin_list.push_back(Botan::hex_decode(part));
100✔
1112
      } catch(std::exception& e) {
×
1113
         std::ostringstream oss;
×
1114
         oss << "Bad input '" << part << "'"
×
1115
             << " in binary list key " << key << " - " << e.what();
×
1116
         throw Test_Error(oss.str());
×
1117
      }
×
1118
   }
12✔
1119

1120
   return bin_list;
12✔
1121
}
×
1122

1123
std::vector<uint8_t> VarMap::get_req_bin(std::string_view key) const {
164,656✔
1124
   const auto& var = get_req_var(key);
164,656✔
1125

1126
   try {
164,656✔
1127
      return Botan::hex_decode(var);
164,656✔
1128
   } catch(std::exception& e) {
×
1129
      throw Test_Error(Botan::fmt("Bad hex input '{}' for key '{}' err '{}'", var, key, e.what()));
×
1130
   }
×
1131
}
1132

1133
std::string VarMap::get_opt_str(std::string_view key, std::string_view def_value) const {
14,449✔
1134
   if(auto v = get_opt_var(key)) {
14,449✔
1135
      return *v;
14,520✔
1136
   } else {
1137
      return std::string(def_value);
28,756✔
1138
   }
14,449✔
1139
}
1140

1141
bool VarMap::get_req_bool(std::string_view key) const {
74✔
1142
   const auto& var = get_req_var(key);
74✔
1143

1144
   if(var == "true") {
74✔
1145
      return true;
1146
   } else if(var == "false") {
34✔
1147
      return false;
1148
   } else {
1149
      throw Test_Error(Botan::fmt("Invalid boolean '{}' for key '{}'", var, key));
×
1150
   }
1151
}
1152

1153
size_t VarMap::get_req_sz(std::string_view key) const {
4,628✔
1154
   return Botan::to_u32bit(get_req_var(key));
4,628✔
1155
}
1156

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

1165
uint32_t VarMap::get_req_u32(std::string_view key) const {
14✔
1166
   return static_cast<uint32_t>(get_req_sz(key));
14✔
1167
}
1168

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

1178
size_t VarMap::get_opt_sz(std::string_view key, const size_t def_value) const {
13,884✔
1179
   if(auto v = get_opt_var(key)) {
13,884✔
1180
      return Botan::to_u32bit(*v);
12,261✔
1181
   } else {
1182
      return def_value;
1183
   }
13,884✔
1184
}
1185

1186
uint64_t VarMap::get_opt_u64(std::string_view key, const uint64_t def_value) const {
4,360✔
1187
   if(auto v = get_opt_var(key)) {
4,360✔
1188
      try {
1,050✔
1189
         return std::stoull(*v);
4,360✔
1190
      } catch(std::exception&) {
×
1191
         throw Test_Error("Invalid u64 value '" + *v + "'");
×
1192
      }
×
1193
   } else {
1194
      return def_value;
1195
   }
4,360✔
1196
}
×
1197

1198
std::vector<uint8_t> VarMap::get_opt_bin(std::string_view key) const {
47,208✔
1199
   if(auto v = get_opt_var(key)) {
47,208✔
1200
      try {
17,832✔
1201
         return Botan::hex_decode(*v);
17,832✔
1202
      } catch(std::exception&) {
×
1203
         throw Test_Error(Botan::fmt("Invalid hex for key '{}' got '{}'", key, *v));
×
1204
      }
×
1205
   } else {
1206
      return {};
29,376✔
1207
   };
47,208✔
1208
}
1209

1210
#if defined(BOTAN_HAS_BIGINT)
1211
Botan::BigInt VarMap::get_req_bn(std::string_view key) const {
38,552✔
1212
   const auto& var = get_req_var(key);
38,552✔
1213

1214
   try {
38,552✔
1215
      return Botan::BigInt(var);
38,552✔
1216
   } catch(std::exception&) {
×
1217
      throw Test_Error(Botan::fmt("Invalid BigInt for key '{}' got '{}'", key, var));
×
1218
   }
×
1219
}
1220

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

1234
class Text_Based_Test::Text_Based_Test_Data {
1235
   public:
1236
      Text_Based_Test_Data(const std::string& data_src,
189✔
1237
                           const std::string& required_keys_str,
1238
                           const std::string& optional_keys_str) :
189✔
1239
            m_data_src(data_src) {
378✔
1240
         if(required_keys_str.empty()) {
189✔
1241
            throw Test_Error("Invalid test spec");
×
1242
         }
1243

1244
         m_required_keys = Botan::split_on(required_keys_str, ',');
189✔
1245
         std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
189✔
1246

1247
         m_all_keys.insert(m_required_keys.begin(), m_required_keys.end());
189✔
1248
         m_all_keys.insert(optional_keys.begin(), optional_keys.end());
189✔
1249
         m_output_key = m_required_keys.at(m_required_keys.size() - 1);
189✔
1250
      }
189✔
1251

1252
      std::string get_next_line();
1253

1254
      const std::string& current_source_name() const { return m_cur_src_name; }
×
1255

1256
      bool known_key(const std::string& key) const;
1257

1258
      const std::vector<std::string>& required_keys() const { return m_required_keys; }
48,317✔
1259

1260
      const std::string& output_key() const { return m_output_key; }
155,778✔
1261

1262
      const std::vector<std::string>& cpu_flags() const { return m_cpu_flags; }
48,176✔
1263

1264
      void set_cpu_flags(std::vector<std::string> flags) { m_cpu_flags = std::move(flags); }
26✔
1265

1266
      const std::string& initial_data_src_name() const { return m_data_src; }
189✔
1267

1268
   private:
1269
      std::string m_data_src;
1270
      std::vector<std::string> m_required_keys;
1271
      std::unordered_set<std::string> m_all_keys;
1272
      std::string m_output_key;
1273

1274
      bool m_first = true;
1275
      std::unique_ptr<std::istream> m_cur;
1276
      std::string m_cur_src_name;
1277
      std::deque<std::string> m_srcs;
1278
      std::vector<std::string> m_cpu_flags;
1279
};
1280

1281
Text_Based_Test::Text_Based_Test(const std::string& data_src,
189✔
1282
                                 const std::string& required_keys,
1283
                                 const std::string& optional_keys) :
189✔
1284
      m_data(std::make_unique<Text_Based_Test_Data>(data_src, required_keys, optional_keys)) {}
189✔
1285

1286
Text_Based_Test::~Text_Based_Test() = default;
189✔
1287

1288
std::string Text_Based_Test::Text_Based_Test_Data::get_next_line() {
156,813✔
1289
   while(true) {
157,080✔
1290
      if(m_cur == nullptr || m_cur->good() == false) {
157,080✔
1291
         if(m_srcs.empty()) {
467✔
1292
            if(m_first) {
378✔
1293
               if(m_data_src.ends_with(".vec")) {
189✔
1294
                  m_srcs.push_back(Test::data_file(m_data_src));
354✔
1295
               } else {
1296
                  const auto fs = Test::files_in_data_dir(m_data_src);
12✔
1297
                  m_srcs.assign(fs.begin(), fs.end());
12✔
1298
                  if(m_srcs.empty()) {
12✔
1299
                     throw Test_Error("Error reading test data dir " + m_data_src);
×
1300
                  }
1301
               }
12✔
1302

1303
               m_first = false;
189✔
1304
            } else {
1305
               return "";  // done
189✔
1306
            }
1307
         }
1308

1309
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
367✔
1310
         m_cur_src_name = m_srcs[0];
278✔
1311

1312
#if defined(BOTAN_HAS_CPUID)
1313
         // Reinit cpuid on new file if needed
1314
         if(m_cpu_flags.empty() == false) {
278✔
1315
            m_cpu_flags.clear();
22✔
1316
            Botan::CPUID::initialize();
22✔
1317
         }
1318
#endif
1319

1320
         if(!m_cur->good()) {
278✔
1321
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
1322
         }
1323

1324
         m_srcs.pop_front();
278✔
1325
      }
1326

1327
      while(m_cur->good()) {
227,628✔
1328
         std::string line;
227,361✔
1329
         std::getline(*m_cur, line);
227,361✔
1330

1331
         if(line.empty()) {
227,361✔
1332
            continue;
55,245✔
1333
         }
1334

1335
         if(line[0] == '#') {
172,116✔
1336
            if(line.starts_with("#test ")) {
15,518✔
1337
               return line;
26✔
1338
            } else {
1339
               continue;
15,492✔
1340
            }
1341
         }
1342

1343
         return line;
156,598✔
1344
      }
227,361✔
1345
   }
1346
}
1347

1348
bool Text_Based_Test::Text_Based_Test_Data::known_key(const std::string& key) const {
155,778✔
1349
   return m_all_keys.contains(key);
155,778✔
1350
}
1351

1352
namespace {
1353

1354
// strips leading and trailing but not internal whitespace
1355
std::string strip_ws(const std::string& in) {
311,556✔
1356
   const char* whitespace = " ";
311,556✔
1357

1358
   const auto first_c = in.find_first_not_of(whitespace);
311,556✔
1359
   if(first_c == std::string::npos) {
311,556✔
1360
      return "";
1,077✔
1361
   }
1362

1363
   const auto last_c = in.find_last_not_of(whitespace);
310,479✔
1364

1365
   return in.substr(first_c, last_c - first_c + 1);
310,479✔
1366
}
1367

1368
std::vector<std::string> parse_cpuid_bits(const std::vector<std::string>& tok) {
26✔
1369
   std::vector<std::string> bits;
26✔
1370

1371
#if defined(BOTAN_HAS_CPUID)
1372
   for(size_t i = 1; i < tok.size(); ++i) {
127✔
1373
      if(auto bit = Botan::CPUID::bit_from_string(tok[i])) {
101✔
1374
         bits.push_back(bit->to_string());
122✔
1375
      }
1376
   }
1377
#else
1378
   BOTAN_UNUSED(tok);
1379
#endif
1380

1381
   return bits;
26✔
1382
}
×
1383

1384
}  // namespace
1385

1386
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) {
32,520✔
1387
   return false;
32,520✔
1388
}
1389

1390
std::vector<Test::Result> Text_Based_Test::run() {
189✔
1391
   std::vector<Test::Result> results;
189✔
1392

1393
   std::string header;
189✔
1394
   std::string header_or_name = m_data->initial_data_src_name();
189✔
1395
   VarMap vars;
189✔
1396
   size_t test_cnt = 0;
189✔
1397

1398
   while(true) {
156,813✔
1399
      const std::string line = m_data->get_next_line();
156,813✔
1400
      if(line.empty()) {
156,813✔
1401
         // EOF
1402
         break;
1403
      }
1404

1405
      if(line.starts_with("#test ")) {
156,624✔
1406
         std::vector<std::string> pragma_tokens = Botan::split_on(line.substr(6), ' ');
26✔
1407

1408
         if(pragma_tokens.empty()) {
26✔
1409
            throw Test_Error("Empty pragma found in " + m_data->current_source_name());
×
1410
         }
1411

1412
         if(pragma_tokens[0] != "cpuid") {
26✔
1413
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1414
         }
1415

1416
         if(!Test_Registry::instance().needs_serialization(this->test_name())) {
52✔
1417
            throw Test_Error(Botan::fmt("'{}' used cpuid control but is not serialized", this->test_name()));
×
1418
         }
1419

1420
         m_data->set_cpu_flags(parse_cpuid_bits(pragma_tokens));
52✔
1421

1422
         continue;
26✔
1423
      } else if(line[0] == '#') {
156,624✔
1424
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1425
      }
1426

1427
      if(line[0] == '[' && line[line.size() - 1] == ']') {
156,598✔
1428
         header = line.substr(1, line.size() - 2);
820✔
1429
         header_or_name = header;
820✔
1430
         test_cnt = 0;
820✔
1431
         vars.clear();
820✔
1432
         continue;
820✔
1433
      }
1434

1435
      const std::string test_id = "test " + std::to_string(test_cnt);
311,556✔
1436

1437
      auto equal_i = line.find_first_of('=');
155,778✔
1438

1439
      if(equal_i == std::string::npos) {
155,778✔
1440
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1441
         continue;
×
1442
      }
1443

1444
      const std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
311,556✔
1445
      const std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
311,556✔
1446

1447
      if(!m_data->known_key(key)) {
155,778✔
1448
         auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key));
×
1449
         results.push_back(r);
×
1450
      }
×
1451

1452
      vars.add(key, val);
155,778✔
1453

1454
      if(key == m_data->output_key()) {
155,778✔
1455
         try {
48,317✔
1456
            for(const auto& req_key : m_data->required_keys()) {
245,030✔
1457
               if(!vars.has_key(req_key)) {
196,713✔
1458
                  auto r =
×
1459
                     Test::Result::Failure(header_or_name, Botan::fmt("{} missing required key {}", test_id, req_key));
×
1460
                  results.push_back(r);
×
1461
               }
×
1462
            }
1463

1464
            if(skip_this_test(header, vars)) {
48,317✔
1465
               continue;
141✔
1466
            }
1467

1468
            ++test_cnt;
48,176✔
1469

1470
            const uint64_t start = Test::timestamp();
48,176✔
1471

1472
            Test::Result result = run_one_test(header, vars);
48,176✔
1473
#if defined(BOTAN_HAS_CPUID)
1474
            if(!m_data->cpu_flags().empty()) {
48,176✔
1475
               for(const auto& cpuid_str : m_data->cpu_flags()) {
34,037✔
1476
                  if(const auto bit = Botan::CPUID::Feature::from_string(cpuid_str)) {
23,509✔
1477
                     if(Botan::CPUID::has(*bit)) {
23,509✔
1478
                        Botan::CPUID::clear_cpuid_bit(*bit);
17,492✔
1479
                        // now re-run the test
1480
                        result.merge(run_one_test(header, vars));
17,492✔
1481
                     }
1482
                  }
1483
               }
1484
               Botan::CPUID::initialize();
10,528✔
1485
            }
1486
#endif
1487
            result.set_ns_consumed(Test::timestamp() - start);
48,176✔
1488

1489
            if(result.tests_failed() > 0) {
48,176✔
1490
               std::ostringstream oss;
×
1491
               oss << "Test # " << test_cnt << " ";
×
1492
               if(!header.empty()) {
×
1493
                  oss << header << " ";
×
1494
               }
1495
               oss << "failed ";
×
1496

1497
               for(const auto& k : m_data->required_keys()) {
×
1498
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1499
               }
1500

1501
               result.test_note(oss.str());
×
1502
            }
×
1503
            results.push_back(result);
48,176✔
1504
         } catch(std::exception& e) {
48,176✔
1505
            std::ostringstream oss;
×
1506
            oss << "Test # " << test_cnt << " ";
×
1507
            if(!header.empty()) {
×
1508
               oss << header << " ";
×
1509
            }
1510

1511
            for(const auto& k : m_data->required_keys()) {
×
1512
               oss << k << "=" << vars.get_req_str(k) << " ";
×
1513
            }
1514

1515
            oss << "failed with exception '" << e.what() << "'";
×
1516

1517
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1518
         }
×
1519

1520
         if(clear_between_callbacks()) {
48,176✔
1521
            vars.clear();
188,935✔
1522
         }
1523
      }
1524
   }
156,906✔
1525

1526
   if(results.empty()) {
189✔
1527
      return results;
1528
   }
1529

1530
   try {
189✔
1531
      std::vector<Test::Result> final_tests = run_final_tests();
189✔
1532
      results.insert(results.end(), final_tests.begin(), final_tests.end());
189✔
1533
   } catch(std::exception& e) {
189✔
1534
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1535
   }
×
1536

1537
   return results;
1538
}
189✔
1539

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