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

randombit / botan / 26323460081

23 May 2026 12:00AM UTC coverage: 89.383% (+0.03%) from 89.349%
26323460081

push

github

web-flow
Merge pull request #5621 from randombit/jack/cli-port-shift

Move the cli test TCP/UDP port range downward

109787 of 122827 relevant lines covered (89.38%)

11032030.9 hits per line

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

80.87
/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;
446✔
59

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

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

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

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

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

83
   m_timestamp = std::min(m_timestamp, other.m_timestamp);
128,502✔
84
   m_ns_taken += other.m_ns_taken;
128,502✔
85
   m_tests_passed += other.m_tests_passed;
128,502✔
86
   m_fail_log.insert(m_fail_log.end(), other.m_fail_log.begin(), other.m_fail_log.end());
128,502✔
87
   m_log.insert(m_log.end(), other.m_log.begin(), other.m_log.end());
128,502✔
88
}
128,502✔
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() {
117,031✔
132
   BOTAN_ASSERT_NOMSG(m_consumed);
117,031✔
133
}
227,671✔
134

135
void Test::Result::ThrowExpectations::assert_that_success_is_not_expected() const {
110,640✔
136
   BOTAN_ASSERT_NOMSG(!m_expect_success);
110,421✔
137
}
110,421✔
138

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

154
   try {
117,031✔
155
      m_fn();
117,031✔
156
      if(!m_expect_success) {
1,649✔
157
         return result.test_failure(Botan::fmt("{} failed to throw expected exception", test_name));
2✔
158
      }
159
   } catch(const std::exception& ex) {
115,382✔
160
      if(m_expect_success) {
115,380✔
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())) {
336,221✔
164
         return result.test_failure(Botan::fmt("{} threw unexpected exception: {}", test_name, ex.what()));
2✔
165
      }
166
      if(m_expected_message.has_value()) {
115,377✔
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(...) {
115,382✔
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();
117,024✔
184
}
185

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

198
bool Test::Result::test_success(std::string_view note) {
3,898,389✔
199
   if(Test::options().log_success()) {
3,898,373✔
200
      test_note(note);
×
201
   }
202
   ++m_tests_passed;
3,898,389✔
203
   return true;
117,024✔
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) {
344,059✔
238
   if(x.size() != y.size()) {
1,447✔
239
      return false;
240
   }
241
   if(x.empty()) {
344,058✔
242
      return true;
243
   }
244

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

248
}  // namespace
249

250
bool Test::Result::test_bin_ne(std::string_view what,
3,364✔
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,811✔
254
      return test_failure(Botan::fmt("{} {} produced matching bytes", who(), what));
1✔
255
   }
256
   return test_success();
3,363✔
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,
342,612✔
267
                               std::span<const uint8_t> produced,
268
                               std::span<const uint8_t> expected) {
269
   if(same_contents(produced, expected)) {
683,429✔
270
      return test_success();
342,611✔
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,371✔
303
   if(produced.empty()) {
39,371✔
304
      return test_failure(what, "was empty");
1✔
305
   } else {
306
      return test_success();
39,370✔
307
   }
308
}
309

310
bool Test::Result::test_str_eq(std::string_view what, std::string_view produced, std::string_view expected) {
78,297✔
311
   if(produced == expected) {
78,297✔
312
      return test_success();
78,297✔
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,462✔
343
   return test_sz_eq(what, produced, expected);
162,462✔
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,788✔
351
   return test_sz_eq(what, produced, expected);
66,788✔
352
}
353

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

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

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

366
bool Test::Result::test_u64_eq(std::string_view what, uint64_t produced, uint64_t expected) {
1,551✔
367
   if(produced == expected) {
1,551✔
368
      return test_success();
1,551✔
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,983✔
383
   if(produced == expected) {
310,983✔
384
      return test_success();
310,982✔
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,671✔
460
   if(produced == expected) {
252,671✔
461
      return test_success();
252,670✔
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,842✔
481
   if(produced == expected) {
432,842✔
482
      return test_success();
432,842✔
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,484✔
493
   return test_bool_eq(what, produced, true);
288,484✔
494
}
495

496
bool Test::Result::test_is_false(std::string_view what, bool produced) {
136,727✔
497
   return test_bool_eq(what, produced, false);
136,727✔
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) {
446✔
557
   m_test_name = std::move(test_name);
446✔
558
   m_registration_location = location;
446✔
559
}
446✔
560

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

566
   return *m_test_rng;
463,489✔
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,
97,316✔
595
                                      Botan::RandomNumberGenerator& rng,
596
                                      bool maybe_resize,
597
                                      size_t min_offset) {
598
   std::vector<uint8_t> r = v;
97,316✔
599

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

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

613
   return r;
97,316✔
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";
155✔
626
   } else {
627
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000.0 << " msec";
1,339✔
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 {
3,004✔
635
   const bool verbose = Test::options().verbose();
3,004✔
636

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

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

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

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

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

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

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

664
   for(size_t i = 0; i != m_fail_log.size(); ++i) {
3,008✔
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,984✔
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,984✔
679
}
2,984✔
680

681
namespace {
682

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

690
      void register_test(const std::string& category,
446✔
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)) {
446✔
696
            throw Test_Error("Duplicate registration of test '" + name + "'");
×
697
         }
698

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

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

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

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

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

719
      std::unique_ptr<Test> get_test(const std::string& test_name) const {
446✔
720
         auto i = m_tests.find(test_name);
446✔
721
         if(i != m_tests.end()) {
446✔
722
            return i->second();
446✔
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) {
447✔
751
            if(!Botan::value_exists(result, test_name) && !to_be_skipped_set.contains(test_name)) {
892✔
752
               result.push_back(test_name);
436✔
753
            }
754
         };
447✔
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) {
447✔
764
               insert_if_not_exists_and_not_skipped(test_name);
446✔
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 {
472✔
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,
446✔
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));
892✔
808
}
446✔
809

810
//static
811
uint64_t Test::timestamp() {
182,186✔
812
   auto now = std::chrono::system_clock::now().time_since_epoch();
182,186✔
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) {
446✔
839
   return Test_Registry::instance().get_test(test_name);
446✔
840
}
841

842
//static
843
bool Test::test_needs_serialization(const std::string& test_name) {
446✔
844
   return Test_Registry::instance().needs_serialization(test_name);
446✔
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,706✔
951

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

957
         for(auto& byte : output) {
73,638,847✔
958
            byte = mix();
63,364,017✔
959
         }
960
      }
10,274,830✔
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,426,703✔
973
         m_x ^= input;
63,426,703✔
974
         m_x *= 0xF2E16957;
63,426,703✔
975
         m_x += 0xE50B590F;
63,426,703✔
976
         return static_cast<uint8_t>(m_x >> 27);
63,426,703✔
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) {
1,076✔
1001
   return options().data_dir() + "/" + file;
2,152✔
1002
}
1003

1004
//static
1005
std::string Test::data_file(std::string_view subdir, std::string_view filename) {
4✔
1006
   if(subdir.empty() || filename.empty()) {
4✔
1007
      throw Test_Error("Empty subdir or filename in Test::data_file");
×
1008
   }
1009
   return Botan::fmt("{}/{}/{}", options().data_dir(), subdir, filename);
4✔
1010
}
1011

1012
//static
1013
std::string Test::data_dir(const std::string& subdir) {
1✔
1014
   return options().data_dir() + "/" + subdir;
2✔
1015
}
1016

1017
//static
1018
std::vector<std::string> Test::files_in_data_dir(const std::string& subdir) {
394✔
1019
   auto fs = Botan::get_files_recursive(options().data_dir() + "/" + subdir);
1,182✔
1020
   if(fs.empty()) {
394✔
1021
      throw Test_Error("Test::files_in_data_dir encountered empty subdir " + subdir);
×
1022
   }
1023
   return fs;
394✔
1024
}
×
1025

1026
//static
1027
std::string Test::data_file_as_temporary_copy(const std::string& what) {
1✔
1028
   auto tmp_basename = what;
1✔
1029
   std::replace(tmp_basename.begin(), tmp_basename.end(), '/', '_');
1✔
1030
   auto temp_file = temp_file_name("tmp-" + tmp_basename);
1✔
1031
   if(temp_file.empty()) {
1✔
1032
      return "";
×
1033
   }
1034
   if(!Test::copy_file(data_file(what), temp_file)) {
1✔
1035
      return "";
×
1036
   }
1037
   return temp_file;
1✔
1038
}
1✔
1039

1040
//static
1041
std::vector<std::string> Test::provider_filter(const std::vector<std::string>& providers) {
49,518✔
1042
   if(m_opts.provider().empty()) {
49,518✔
1043
      return providers;
49,518✔
1044
   }
1045
   for(auto&& provider : providers) {
×
1046
      if(provider == m_opts.provider()) {
×
1047
         return std::vector<std::string>{provider};
×
1048
      }
1049
   }
1050
   return std::vector<std::string>{};
×
1051
}
×
1052

1053
std::string Test::random_password(Botan::RandomNumberGenerator& rng) {
222✔
1054
   const size_t len = 1 + rng.next_byte() % 32;
222✔
1055
   return Botan::hex_encode(rng.random_vec(len));
444✔
1056
}
1057

1058
size_t Test::random_index(Botan::RandomNumberGenerator& rng, size_t max) {
8,062✔
1059
   return Botan::load_be(rng.random_array<8>()) % max;
8,062✔
1060
}
1061

1062
void VarMap::clear() {
34,136✔
1063
   m_vars.clear();
×
1064
}
×
1065

1066
namespace {
1067

1068
bool varmap_pair_lt(const std::pair<std::string, std::string>& kv, std::string_view k) {
1,688,369✔
1069
   return kv.first < k;
1,688,369✔
1070
}
1071

1072
}  // namespace
1073

1074
bool VarMap::has_key(std::string_view key) const {
213,176✔
1075
   return get_opt_var(key).has_value();
213,176✔
1076
}
1077

1078
void VarMap::add(std::string_view key, std::string_view value) {
155,815✔
1079
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
155,815✔
1080

1081
   if(i != m_vars.end() && i->first == key) {
163,006✔
1082
      i->second = value;
44,675✔
1083
   } else {
1084
      m_vars.emplace(i, key, value);
111,140✔
1085
   }
1086
}
155,815✔
1087

1088
std::optional<std::string> VarMap::get_opt_var(std::string_view key) const {
293,165✔
1089
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
293,165✔
1090

1091
   if(i != m_vars.end() && i->first == key) {
294,975✔
1092
      return i->second;
240,700✔
1093
   } else {
1094
      return {};
52,465✔
1095
   }
1096
}
1097

1098
const std::string& VarMap::get_req_var(std::string_view key) const {
261,147✔
1099
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
261,147✔
1100

1101
   if(i != m_vars.end() && i->first == key) {
261,147✔
1102
      return i->second;
261,147✔
1103
   } else {
1104
      throw Test_Error(Botan::fmt("Test missing variable '{}'", key));
×
1105
   }
1106
}
1107

1108
std::string VarMap::get_req_str(std::string_view key) const {
53,178✔
1109
   return std::string(get_req_var(key));
53,178✔
1110
}
1111

1112
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(std::string_view key) const {
12✔
1113
   const auto& var = get_req_var(key);
12✔
1114

1115
   std::vector<std::vector<uint8_t>> bin_list;
12✔
1116

1117
   for(auto&& part : Botan::split_on(var, ',')) {
62✔
1118
      try {
50✔
1119
         bin_list.push_back(Botan::hex_decode(part));
100✔
1120
      } catch(std::exception& e) {
×
1121
         std::ostringstream oss;
×
1122
         oss << "Bad input '" << part << "'"
×
1123
             << " in binary list key " << key << " - " << e.what();
×
1124
         throw Test_Error(oss.str());
×
1125
      }
×
1126
   }
12✔
1127

1128
   return bin_list;
12✔
1129
}
×
1130

1131
std::vector<uint8_t> VarMap::get_req_bin(std::string_view key) const {
164,682✔
1132
   const auto& var = get_req_var(key);
164,682✔
1133

1134
   try {
164,682✔
1135
      return Botan::hex_decode(var);
164,682✔
1136
   } catch(std::exception& e) {
×
1137
      throw Test_Error(Botan::fmt("Bad hex input '{}' for key '{}' err '{}'", var, key, e.what()));
×
1138
   }
×
1139
}
1140

1141
std::string VarMap::get_opt_str(std::string_view key, std::string_view def_value) const {
14,449✔
1142
   if(auto v = get_opt_var(key)) {
14,449✔
1143
      return *v;
14,520✔
1144
   } else {
1145
      return std::string(def_value);
28,756✔
1146
   }
14,449✔
1147
}
1148

1149
bool VarMap::get_req_bool(std::string_view key) const {
74✔
1150
   const auto& var = get_req_var(key);
74✔
1151

1152
   if(var == "true") {
74✔
1153
      return true;
1154
   } else if(var == "false") {
34✔
1155
      return false;
1156
   } else {
1157
      throw Test_Error(Botan::fmt("Invalid boolean '{}' for key '{}'", var, key));
×
1158
   }
1159
}
1160

1161
size_t VarMap::get_req_sz(std::string_view key) const {
4,628✔
1162
   return Botan::to_u32bit(get_req_var(key));
4,628✔
1163
}
1164

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

1173
uint32_t VarMap::get_req_u32(std::string_view key) const {
14✔
1174
   return static_cast<uint32_t>(get_req_sz(key));
14✔
1175
}
1176

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

1186
size_t VarMap::get_opt_sz(std::string_view key, const size_t def_value) const {
13,884✔
1187
   if(auto v = get_opt_var(key)) {
13,884✔
1188
      return Botan::to_u32bit(*v);
12,261✔
1189
   } else {
1190
      return def_value;
1191
   }
13,884✔
1192
}
1193

1194
uint64_t VarMap::get_opt_u64(std::string_view key, const uint64_t def_value) const {
4,360✔
1195
   if(auto v = get_opt_var(key)) {
4,360✔
1196
      try {
1,050✔
1197
         return std::stoull(*v);
4,360✔
1198
      } catch(std::exception&) {
×
1199
         throw Test_Error("Invalid u64 value '" + *v + "'");
×
1200
      }
×
1201
   } else {
1202
      return def_value;
1203
   }
4,360✔
1204
}
×
1205

1206
std::vector<uint8_t> VarMap::get_opt_bin(std::string_view key) const {
47,216✔
1207
   if(auto v = get_opt_var(key)) {
47,216✔
1208
      try {
17,832✔
1209
         return Botan::hex_decode(*v);
17,832✔
1210
      } catch(std::exception&) {
×
1211
         throw Test_Error(Botan::fmt("Invalid hex for key '{}' got '{}'", key, *v));
×
1212
      }
×
1213
   } else {
1214
      return {};
29,384✔
1215
   };
47,216✔
1216
}
1217

1218
#if defined(BOTAN_HAS_BIGINT)
1219
Botan::BigInt VarMap::get_req_bn(std::string_view key) const {
38,556✔
1220
   const auto& var = get_req_var(key);
38,556✔
1221

1222
   try {
38,556✔
1223
      return Botan::BigInt(var);
38,556✔
1224
   } catch(std::exception&) {
×
1225
      throw Test_Error(Botan::fmt("Invalid BigInt for key '{}' got '{}'", key, var));
×
1226
   }
×
1227
}
1228

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

1242
class Text_Based_Test::Text_Based_Test_Data {
1243
   public:
1244
      Text_Based_Test_Data(const std::string& data_src,
189✔
1245
                           const std::string& required_keys_str,
1246
                           const std::string& optional_keys_str) :
189✔
1247
            m_data_src(data_src) {
378✔
1248
         if(required_keys_str.empty()) {
189✔
1249
            throw Test_Error("Invalid test spec");
×
1250
         }
1251

1252
         m_required_keys = Botan::split_on(required_keys_str, ',');
189✔
1253
         std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
189✔
1254

1255
         m_all_keys.insert(m_required_keys.begin(), m_required_keys.end());
189✔
1256
         m_all_keys.insert(optional_keys.begin(), optional_keys.end());
189✔
1257
         m_output_key = m_required_keys.at(m_required_keys.size() - 1);
189✔
1258
      }
189✔
1259

1260
      std::string get_next_line();
1261

1262
      const std::string& current_source_name() const { return m_cur_src_name; }
×
1263

1264
      bool known_key(const std::string& key) const;
1265

1266
      const std::vector<std::string>& required_keys() const { return m_required_keys; }
48,334✔
1267

1268
      const std::string& output_key() const { return m_output_key; }
155,815✔
1269

1270
      const std::vector<std::string>& cpu_flags() const { return m_cpu_flags; }
48,193✔
1271

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

1274
      const std::string& initial_data_src_name() const { return m_data_src; }
189✔
1275

1276
   private:
1277
      std::string m_data_src;
1278
      std::vector<std::string> m_required_keys;
1279
      std::unordered_set<std::string> m_all_keys;
1280
      std::string m_output_key;
1281

1282
      bool m_first = true;
1283
      std::unique_ptr<std::istream> m_cur;
1284
      std::string m_cur_src_name;
1285
      std::deque<std::string> m_srcs;
1286
      std::vector<std::string> m_cpu_flags;
1287
};
1288

1289
Text_Based_Test::Text_Based_Test(const std::string& data_src,
189✔
1290
                                 const std::string& required_keys,
1291
                                 const std::string& optional_keys) :
189✔
1292
      m_data(std::make_unique<Text_Based_Test_Data>(data_src, required_keys, optional_keys)) {}
189✔
1293

1294
Text_Based_Test::~Text_Based_Test() = default;
189✔
1295

1296
std::string Text_Based_Test::Text_Based_Test_Data::get_next_line() {
156,851✔
1297
   while(true) {
157,118✔
1298
      if(m_cur == nullptr || m_cur->good() == false) {
157,118✔
1299
         if(m_srcs.empty()) {
467✔
1300
            if(m_first) {
378✔
1301
               if(m_data_src.ends_with(".vec")) {
189✔
1302
                  m_srcs.push_back(Test::data_file(m_data_src));
354✔
1303
               } else {
1304
                  const auto fs = Test::files_in_data_dir(m_data_src);
12✔
1305
                  m_srcs.assign(fs.begin(), fs.end());
12✔
1306
                  if(m_srcs.empty()) {
12✔
1307
                     throw Test_Error("Error reading test data dir " + m_data_src);
×
1308
                  }
1309
               }
12✔
1310

1311
               m_first = false;
189✔
1312
            } else {
1313
               return "";  // done
189✔
1314
            }
1315
         }
1316

1317
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
367✔
1318
         m_cur_src_name = m_srcs[0];
278✔
1319

1320
#if defined(BOTAN_HAS_CPUID)
1321
         // Reinit cpuid on new file if needed
1322
         if(m_cpu_flags.empty() == false) {
278✔
1323
            m_cpu_flags.clear();
22✔
1324
            Botan::CPUID::initialize();
22✔
1325
         }
1326
#endif
1327

1328
         if(!m_cur->good()) {
278✔
1329
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
1330
         }
1331

1332
         m_srcs.pop_front();
278✔
1333
      }
1334

1335
      while(m_cur->good()) {
227,696✔
1336
         std::string line;
227,429✔
1337
         std::getline(*m_cur, line);
227,429✔
1338

1339
         if(line.empty()) {
227,429✔
1340
            continue;
55,258✔
1341
         }
1342

1343
         if(line[0] == '#') {
172,171✔
1344
            if(line.starts_with("#test ")) {
15,535✔
1345
               return line;
26✔
1346
            } else {
1347
               continue;
15,509✔
1348
            }
1349
         }
1350

1351
         return line;
156,636✔
1352
      }
227,429✔
1353
   }
1354
}
1355

1356
bool Text_Based_Test::Text_Based_Test_Data::known_key(const std::string& key) const {
155,815✔
1357
   return m_all_keys.contains(key);
155,815✔
1358
}
1359

1360
namespace {
1361

1362
// strips leading and trailing but not internal whitespace
1363
std::string strip_ws(const std::string& in) {
311,630✔
1364
   const char* whitespace = " ";
311,630✔
1365

1366
   const auto first_c = in.find_first_not_of(whitespace);
311,630✔
1367
   if(first_c == std::string::npos) {
311,630✔
1368
      return "";
1,079✔
1369
   }
1370

1371
   const auto last_c = in.find_last_not_of(whitespace);
310,551✔
1372

1373
   return in.substr(first_c, last_c - first_c + 1);
310,551✔
1374
}
1375

1376
std::vector<std::string> parse_cpuid_bits(const std::vector<std::string>& tok) {
26✔
1377
   std::vector<std::string> bits;
26✔
1378

1379
#if defined(BOTAN_HAS_CPUID)
1380
   for(size_t i = 1; i < tok.size(); ++i) {
127✔
1381
      if(auto bit = Botan::CPUID::bit_from_string(tok[i])) {
101✔
1382
         bits.push_back(bit->to_string());
122✔
1383
      }
1384
   }
1385
#else
1386
   BOTAN_UNUSED(tok);
1387
#endif
1388

1389
   return bits;
26✔
1390
}
×
1391

1392
}  // namespace
1393

1394
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) {
32,537✔
1395
   return false;
32,537✔
1396
}
1397

1398
std::vector<Test::Result> Text_Based_Test::run() {
189✔
1399
   std::vector<Test::Result> results;
189✔
1400

1401
   std::string header;
189✔
1402
   std::string header_or_name = m_data->initial_data_src_name();
189✔
1403
   VarMap vars;
189✔
1404
   size_t test_cnt = 0;
189✔
1405

1406
   while(true) {
156,851✔
1407
      const std::string line = m_data->get_next_line();
156,851✔
1408
      if(line.empty()) {
156,851✔
1409
         // EOF
1410
         break;
1411
      }
1412

1413
      if(line.starts_with("#test ")) {
156,662✔
1414
         std::vector<std::string> pragma_tokens = Botan::split_on(line.substr(6), ' ');
26✔
1415

1416
         if(pragma_tokens.empty()) {
26✔
1417
            throw Test_Error("Empty pragma found in " + m_data->current_source_name());
×
1418
         }
1419

1420
         if(pragma_tokens[0] != "cpuid") {
26✔
1421
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1422
         }
1423

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

1428
         m_data->set_cpu_flags(parse_cpuid_bits(pragma_tokens));
52✔
1429

1430
         continue;
26✔
1431
      } else if(line[0] == '#') {
156,662✔
1432
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1433
      }
1434

1435
      if(line[0] == '[' && line[line.size() - 1] == ']') {
156,636✔
1436
         header = line.substr(1, line.size() - 2);
821✔
1437
         header_or_name = header;
821✔
1438
         test_cnt = 0;
821✔
1439
         vars.clear();
821✔
1440
         continue;
821✔
1441
      }
1442

1443
      const std::string test_id = "test " + std::to_string(test_cnt);
311,630✔
1444

1445
      auto equal_i = line.find_first_of('=');
155,815✔
1446

1447
      if(equal_i == std::string::npos) {
155,815✔
1448
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1449
         continue;
×
1450
      }
1451

1452
      const std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
311,630✔
1453
      const std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
311,630✔
1454

1455
      if(!m_data->known_key(key)) {
155,815✔
1456
         auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key));
×
1457
         results.push_back(r);
×
1458
      }
×
1459

1460
      vars.add(key, val);
155,815✔
1461

1462
      if(key == m_data->output_key()) {
155,815✔
1463
         try {
48,334✔
1464
            for(const auto& req_key : m_data->required_keys()) {
245,084✔
1465
               if(!vars.has_key(req_key)) {
196,750✔
1466
                  auto r =
×
1467
                     Test::Result::Failure(header_or_name, Botan::fmt("{} missing required key {}", test_id, req_key));
×
1468
                  results.push_back(r);
×
1469
               }
×
1470
            }
1471

1472
            if(skip_this_test(header, vars)) {
48,334✔
1473
               continue;
141✔
1474
            }
1475

1476
            ++test_cnt;
48,193✔
1477

1478
            const uint64_t start = Test::timestamp();
48,193✔
1479

1480
            Test::Result result = run_one_test(header, vars);
48,193✔
1481
#if defined(BOTAN_HAS_CPUID)
1482
            if(!m_data->cpu_flags().empty()) {
48,193✔
1483
               for(const auto& cpuid_str : m_data->cpu_flags()) {
34,037✔
1484
                  if(const auto bit = Botan::CPUID::Feature::from_string(cpuid_str)) {
23,509✔
1485
                     if(Botan::CPUID::has(*bit)) {
23,509✔
1486
                        Botan::CPUID::clear_cpuid_bit(*bit);
17,492✔
1487
                        // now re-run the test
1488
                        result.merge(run_one_test(header, vars));
17,492✔
1489
                     }
1490
                  }
1491
               }
1492
               Botan::CPUID::initialize();
10,528✔
1493
            }
1494
#endif
1495
            result.set_ns_consumed(Test::timestamp() - start);
48,193✔
1496

1497
            if(result.tests_failed() > 0) {
48,193✔
1498
               std::ostringstream oss;
×
1499
               oss << "Test # " << test_cnt << " ";
×
1500
               if(!header.empty()) {
×
1501
                  oss << header << " ";
×
1502
               }
1503
               oss << "failed ";
×
1504

1505
               for(const auto& k : m_data->required_keys()) {
×
1506
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1507
               }
1508

1509
               result.test_note(oss.str());
×
1510
            }
×
1511
            results.push_back(result);
48,193✔
1512
         } catch(std::exception& e) {
48,193✔
1513
            std::ostringstream oss;
×
1514
            oss << "Test # " << test_cnt << " ";
×
1515
            if(!header.empty()) {
×
1516
               oss << header << " ";
×
1517
            }
1518

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

1523
            oss << "failed with exception '" << e.what() << "'";
×
1524

1525
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1526
         }
×
1527

1528
         if(clear_between_callbacks()) {
48,193✔
1529
            vars.clear();
188,989✔
1530
         }
1531
      }
1532
   }
156,944✔
1533

1534
   if(results.empty()) {
189✔
1535
      return results;
1536
   }
1537

1538
   try {
189✔
1539
      std::vector<Test::Result> final_tests = run_final_tests();
189✔
1540
      results.insert(results.end(), final_tests.begin(), final_tests.end());
189✔
1541
   } catch(std::exception& e) {
189✔
1542
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1543
   }
×
1544

1545
   return results;
1546
}
189✔
1547

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