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

randombit / botan / 22138370263

18 Feb 2026 11:44AM UTC coverage: 90.024% (-1.6%) from 91.672%
22138370263

Pull #5357

github

web-flow
Merge fd2eb3fac into 90b10f415
Pull Request #5357: Improve Test::Result::test_note

102337 of 113677 relevant lines covered (90.02%)

11513611.6 hits per line

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

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

7
#include "tests.h"
8

9
#include <botan/hex.h>
10
#include <botan/rng.h>
11
#include <botan/symkey.h>
12
#include <botan/internal/filesystem.h>
13
#include <botan/internal/fmt.h>
14
#include <botan/internal/loadstor.h>
15
#include <botan/internal/parsing.h>
16
#include <botan/internal/stl_util.h>
17
#include <botan/internal/target_info.h>
18
#include <chrono>
19
#include <deque>
20
#include <fstream>
21
#include <iomanip>
22
#include <set>
23
#include <sstream>
24
#include <unordered_set>
25

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

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

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

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

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

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

54
namespace Botan_Tests {
55

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

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

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

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

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

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

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

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

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

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

103
void Test::Result::test_note(std::string_view note, std::span<const uint8_t> context) {
12✔
104
   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) {
620✔
112
   m_log.emplace_back(Botan::fmt("{} {}", who(), note));
620✔
113
}
620✔
114

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

118
   const std::string whatever(whatever_sv);
275✔
119
   if(!s_already_seen.contains(whatever)) {
275✔
120
      test_note(Botan::fmt("Skipping tests due to missing {}", whatever));
5✔
121
      s_already_seen.insert(whatever);
275✔
122
   }
123
}
275✔
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() {
67,783✔
132
   BOTAN_ASSERT_NOMSG(m_consumed);
67,783✔
133
}
130,020✔
134

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

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

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

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

154
   try {
67,783✔
155
      m_fn();
67,783✔
156
      if(!m_expect_success) {
1,646✔
157
         return result.test_failure(Botan::fmt("{} failed to throw expected exception", test_name));
2✔
158
      }
159
   } catch(const std::exception& ex) {
66,137✔
160
      if(m_expect_success) {
66,135✔
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())) {
190,230✔
164
         return result.test_failure(Botan::fmt("{} threw unexpected exception: {}", test_name, ex.what()));
2✔
165
      }
166
      if(m_expected_message.has_value() && m_expected_message.value() != ex.what()) {
66,132✔
167
         return result.test_failure(Botan::fmt("{} threw exception with unexpected message (expected {} got {})",
1✔
168
                                               test_name,
169
                                               m_expected_message.value(),
1✔
170
                                               ex.what()));
2✔
171
      }
172
   } catch(...) {
66,137✔
173
      if(m_expect_success || m_expected_exception_check_fn || m_expected_message.has_value()) {
2✔
174
         return result.test_failure(Botan::fmt("{} threw unexpected unknown exception", test_name));
1✔
175
      }
176
   }
2✔
177

178
   return result.test_success();
67,776✔
179
}
180

181
bool Test::Result::test_throws(std::string_view what, std::function<void()> fn) {
3,916✔
182
   return ThrowExpectations(std::move(fn)).check(what, *this);
11,748✔
183
}
184

185
bool Test::Result::test_throws(std::string_view what, std::string_view expected, std::function<void()> fn) {
174✔
186
   return ThrowExpectations(std::move(fn)).expect_message(expected).check(what, *this);
522✔
187
}
188

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

193
bool Test::Result::test_success(std::string_view note) {
3,620,885✔
194
   if(Test::options().log_success()) {
3,620,869✔
195
      test_note(note);
×
196
   }
197
   ++m_tests_passed;
3,620,885✔
198
   return true;
67,776✔
199
}
200

201
bool Test::Result::test_failure(std::string_view what, std::string_view error) {
2✔
202
   return test_failure(Botan::fmt("{} {} with error {}", who(), what, error));
2✔
203
}
204

205
void Test::Result::test_failure(std::string_view what, const uint8_t buf[], size_t buf_len) {
×
206
   return test_failure(what, {buf, buf_len});
×
207
}
208

209
void Test::Result::test_failure(std::string_view what, std::span<const uint8_t> context) {
1✔
210
   test_failure(Botan::fmt("{} {} with value {}", who(), what, Botan::hex_encode(context)));
2✔
211
}
1✔
212

213
bool Test::Result::test_failure(const char* err) {
×
214
   return test_failure(std::string_view(err));
×
215
}
216

217
bool Test::Result::test_failure(std::string_view err) {
1✔
218
   return test_failure(std::string(err));
1✔
219
}
220

221
bool Test::Result::test_failure(std::string err) {
24✔
222
   m_fail_log.push_back(std::move(err));
24✔
223

224
   if(Test::options().abort_on_first_fail() && m_who != "Failing Test") {
24✔
225
      std::abort();
×
226
   }
227
   return false;
24✔
228
}
229

230
namespace {
231

232
bool same_contents(std::span<const uint8_t> x, std::span<const uint8_t> y) {
302,695✔
233
   if(x.size() != y.size()) {
1,450✔
234
      return false;
235
   }
236
   if(x.empty()) {
302,694✔
237
      return true;
238
   }
239

240
   return std::memcmp(x.data(), y.data(), x.size()) == 0;
301,262✔
241
}
242

243
}  // namespace
244

245
bool Test::Result::test_bin_ne(std::string_view what,
3,405✔
246
                               std::span<const uint8_t> produced,
247
                               std::span<const uint8_t> expected) {
248
   if(produced.size() == expected.size() && same_contents(produced, expected)) {
4,855✔
249
      return test_failure(Botan::fmt("{} {} produced matching bytes", who(), what));
1✔
250
   }
251
   return test_success();
3,404✔
252
}
253

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

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

268
   std::ostringstream err;
1✔
269

270
   err << who();
1✔
271

272
   err << " unexpected result for " << what;
1✔
273

274
   if(produced.size() != expected.size()) {
1✔
275
      err << " produced " << produced.size() << " bytes expected " << expected.size();
1✔
276
   }
277

278
   std::vector<uint8_t> xor_diff(std::min(produced.size(), expected.size()));
2✔
279
   size_t bytes_different = 0;
1✔
280

281
   for(size_t i = 0; i != xor_diff.size(); ++i) {
4✔
282
      xor_diff[i] = produced[i] ^ expected[i];
3✔
283
      if(xor_diff[i] > 0) {
3✔
284
         bytes_different++;
3✔
285
      }
286
   }
287

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

290
   if(bytes_different > 0) {
1✔
291
      err << "\nXOR Diff: " << Botan::hex_encode(xor_diff);
1✔
292
   }
293

294
   return test_failure(err.str());
1✔
295
}
1✔
296

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

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

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

321
bool Test::Result::test_i16_eq(std::string_view what, int16_t produced, int16_t expected) {
1,025✔
322
   return test_i32_eq(what, produced, expected);
1,025✔
323
}
324

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

333
bool Test::Result::test_u8_eq(uint8_t produced, uint8_t expected) {
214✔
334
   return test_sz_eq("comparison", produced, expected);
214✔
335
}
336

337
bool Test::Result::test_u8_eq(std::string_view what, uint8_t produced, uint8_t expected) {
49,385✔
338
   return test_sz_eq(what, produced, expected);
49,385✔
339
}
340

341
bool Test::Result::test_u16_eq(uint16_t produced, uint16_t expected) {
40✔
342
   return test_sz_eq("comparison", produced, expected);
40✔
343
}
344

345
bool Test::Result::test_u16_eq(std::string_view what, uint16_t produced, uint16_t expected) {
66,792✔
346
   return test_sz_eq(what, produced, expected);
66,792✔
347
}
348

349
bool Test::Result::test_u32_eq(uint32_t produced, uint32_t expected) {
16✔
350
   return test_sz_eq("comparison", produced, expected);
16✔
351
}
352

353
bool Test::Result::test_u32_eq(std::string_view what, uint32_t produced, uint32_t expected) {
4,198✔
354
   return test_sz_eq(what, produced, expected);
4,198✔
355
}
356

357
bool Test::Result::test_u64_eq(uint64_t produced, uint64_t expected) {
13✔
358
   return test_u64_eq("comparison", produced, expected);
13✔
359
}
360

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

369
bool Test::Result::test_sz_eq(std::string_view what, size_t produced, size_t expected) {
197,641✔
370
   if(produced == expected) {
197,641✔
371
      return test_success();
197,640✔
372
   } else {
373
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} == {}", who(), what, produced, expected));
1✔
374
   }
375
}
376

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

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

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

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

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

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

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

445
#if defined(BOTAN_HAS_BIGINT)
446
bool Test::Result::test_bn_eq(std::string_view what, const BigInt& produced, const BigInt& expected) {
252,636✔
447
   if(produced == expected) {
252,636✔
448
      return test_success();
252,635✔
449
   } else {
450
      std::ostringstream err;
1✔
451
      err << who() << " " << what << " produced " << produced << " != expected value " << expected;
1✔
452
      return test_failure(err.str());
1✔
453
   }
1✔
454
}
455

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

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

479
bool Test::Result::test_is_true(std::string_view what, bool produced) {
228,017✔
480
   return test_bool_eq(what, produced, true);
228,017✔
481
}
482

483
bool Test::Result::test_is_false(std::string_view what, bool produced) {
126,006✔
484
   return test_bool_eq(what, produced, false);
126,006✔
485
}
486

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

494
   return test_success();
2,814✔
495
}
496

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

504
   return test_success();
25✔
505
}
506

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

515
      // -40 is BOTAN_FFI_ERROR_NOT_IMPLEMENTED
516
      if(rc == -40) {
×
517
         msg << " returned not implemented";
×
518
      } else {
519
         msg << " unexpectedly failed with error code " << rc;
×
520
      }
521

522
      if(rc == -40) {
×
523
         this->test_note(msg.str());
×
524
      } else {
525
         this->test_failure(msg.str());
×
526
      }
527
      return false;
×
528
   }
×
529
}
530

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

540
   return test_success();
420✔
541
}
542

543
void Test::initialize(std::string test_name, CodeLocation location) {
420✔
544
   m_test_name = std::move(test_name);
420✔
545
   m_registration_location = location;
420✔
546
}
420✔
547

548
Botan::RandomNumberGenerator& Test::rng() const {
460,015✔
549
   if(!m_test_rng) {
460,015✔
550
      m_test_rng = Test::new_rng(m_test_name);
146✔
551
   }
552

553
   return *m_test_rng;
460,015✔
554
}
555

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

569
   for(const auto& group : preferred_groups) {
151✔
570
      if(Botan::EC_Group::supports_named_group(group)) {
151✔
571
         return group;
151✔
572
      }
573
   }
574
#else
575
   BOTAN_UNUSED(preferred_groups);
576
#endif
577

578
   return std::nullopt;
×
579
}
298✔
580

581
std::vector<uint8_t> Test::mutate_vec(const std::vector<uint8_t>& v,
96,742✔
582
                                      Botan::RandomNumberGenerator& rng,
583
                                      bool maybe_resize,
584
                                      size_t min_offset) {
585
   std::vector<uint8_t> r = v;
96,742✔
586

587
   if(maybe_resize && (r.empty() || rng.next_byte() < 32)) {
110,321✔
588
      // TODO: occasionally truncate, insert at random index
589
      const size_t add = 1 + (rng.next_byte() % 16);
2,122✔
590
      r.resize(r.size() + add);
2,122✔
591
      rng.randomize(&r[r.size() - add], add);
2,122✔
592
   }
593

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

600
   return r;
96,742✔
601
}
×
602

603
std::vector<std::string> Test::possible_providers(const std::string& /*alg*/) {
×
604
   return Test::provider_filter({"base"});
×
605
}
606

607
//static
608
std::string Test::format_time(uint64_t nanoseconds) {
1,470✔
609
   std::ostringstream o;
1,470✔
610

611
   if(nanoseconds > 1000000000) {
1,470✔
612
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000000.0 << " sec";
157✔
613
   } else {
614
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000.0 << " msec";
1,313✔
615
   }
616

617
   return o.str();
2,940✔
618
}
1,470✔
619

620
// TODO: this should move to `StdoutReporter`
621
std::string Test::Result::result_string() const {
2,556✔
622
   const bool verbose = Test::options().verbose();
2,556✔
623

624
   if(tests_run() == 0 && !verbose) {
2,556✔
625
      return "";
20✔
626
   }
627

628
   std::ostringstream report;
2,536✔
629

630
   report << who() << " ran ";
2,536✔
631

632
   if(tests_run() == 0) {
2,536✔
633
      report << "ZERO";
×
634
   } else {
635
      report << tests_run();
2,536✔
636
   }
637
   report << " tests";
2,536✔
638

639
   if(m_ns_taken > 0) {
2,536✔
640
      report << " in " << format_time(m_ns_taken);
2,938✔
641
   }
642

643
   if(tests_failed() > 0) {
2,536✔
644
      report << " " << tests_failed() << " FAILED";
24✔
645
   } else {
646
      report << " all ok";
2,512✔
647
   }
648

649
   report << "\n";
2,536✔
650

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

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

665
   return report.str();
2,536✔
666
}
2,536✔
667

668
namespace {
669

670
class Test_Registry {
671
   public:
672
      static Test_Registry& instance() {
1,282✔
673
         static Test_Registry registry;
1,283✔
674
         return registry;
1,282✔
675
      }
676

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

686
         if(m_tests.contains(category)) {
420✔
687
            throw Test_Error("'" + category + "' cannot be used as category, test exists");
×
688
         }
689

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

694
         if(smoke_test) {
420✔
695
            m_smoke_tests.push_back(name);
10✔
696
         }
697

698
         if(needs_serialization) {
420✔
699
            m_mutexed_tests.push_back(name);
21✔
700
         }
701

702
         m_tests.emplace(name, std::move(maker_fn));
420✔
703
         m_categories.emplace(category, name);
420✔
704
      }
420✔
705

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

714
      std::vector<std::string> registered_tests() const {
×
715
         std::vector<std::string> s;
×
716
         s.reserve(m_tests.size());
×
717
         for(auto&& i : m_tests) {
×
718
            s.push_back(i.first);
×
719
         }
720
         return s;
×
721
      }
×
722

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

731
      std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
1✔
732
                                                       const std::vector<std::string>& to_be_skipped) {
733
         std::vector<std::string> result;
1✔
734

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

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

767
         return result;
1✔
768
      }
1✔
769

770
      bool needs_serialization(const std::string& test_name) const {
441✔
771
         return Botan::value_exists(m_mutexed_tests, test_name);
21✔
772
      }
773

774
   private:
775
      Test_Registry() = default;
1✔
776

777
   private:
778
      std::map<std::string, std::function<std::unique_ptr<Test>()>> m_tests;
779
      std::multimap<std::string, std::string> m_categories;
780
      std::vector<std::string> m_smoke_tests;
781
      std::vector<std::string> m_mutexed_tests;
782
};
783

784
}  // namespace
785

786
// static Test:: functions
787

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

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

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

814
//static
815
std::vector<std::string> Test::registered_tests() {
×
816
   return Test_Registry::instance().registered_tests();
×
817
}
818

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

824
//static
825
std::unique_ptr<Test> Test::get_test(const std::string& test_name) {
420✔
826
   return Test_Registry::instance().get_test(test_name);
420✔
827
}
828

829
//static
830
bool Test::test_needs_serialization(const std::string& test_name) {
420✔
831
   return Test_Registry::instance().needs_serialization(test_name);
420✔
832
}
833

834
//static
835
std::vector<std::string> Test::filter_registered_tests(const std::vector<std::string>& requested,
1✔
836
                                                       const std::vector<std::string>& to_be_skipped) {
837
   return Test_Registry::instance().filter_registered_tests(requested, to_be_skipped);
1✔
838
}
839

840
//static
841
std::string Test::temp_file_name(const std::string& basename) {
21✔
842
   // TODO add a --tmp-dir option to the tests to specify where these files go
843

844
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
845

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

849
   const int fd = ::mkstemp(mkstemp_basename.data());
21✔
850

851
   // error
852
   if(fd < 0) {
21✔
853
      return "";
×
854
   }
855

856
   ::close(fd);
21✔
857

858
   return mkstemp_basename;
21✔
859
#else
860
   // For now just create the temp in the current working directory
861
   return basename;
862
#endif
863
}
21✔
864

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

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

884
   return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
76✔
885
}
38✔
886

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

894
   std::vector<uint8_t> contents;
34✔
895

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

901
      if(got == 0 && file.eof()) {
40✔
902
         break;
903
      }
904

905
      contents.insert(contents.end(), buf.data(), buf.data() + got);
40✔
906
   }
40✔
907

908
   return contents;
68✔
909
}
34✔
910

911
// static member variables of Test
912

913
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
914
Test_Options Test::m_opts;
915
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
916
std::string Test::m_test_rng_seed;
917

918
//static
919
void Test::set_test_options(const Test_Options& opts) {
1✔
920
   m_opts = opts;
1✔
921
}
1✔
922

923
namespace {
924

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

933
      void clear() override { m_x = 0; }
×
934

935
      bool accepts_input() const override { return true; }
×
936

937
      bool is_seeded() const override { return true; }
276,946✔
938

939
      void fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) override {
10,269,818✔
940
         for(const auto byte : input) {
10,269,818✔
941
            mix(byte);
×
942
         }
943

944
         for(auto& byte : output) {
73,283,950✔
945
            byte = mix();
63,014,132✔
946
         }
947
      }
10,269,818✔
948

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

958
   private:
959
      uint8_t mix(uint8_t input = 0) {
63,027,475✔
960
         m_x ^= input;
63,027,475✔
961
         m_x *= 0xF2E16957;
63,027,475✔
962
         m_x += 0xE50B590F;
63,027,475✔
963
         return static_cast<uint8_t>(m_x >> 27);
63,027,475✔
964
      }
965

966
      uint64_t m_x;
967
};
968

969
}  // namespace
970

971
//static
972
void Test::set_test_rng_seed(std::span<const uint8_t> seed, size_t epoch) {
1✔
973
   m_test_rng_seed = Botan::fmt("seed={} epoch={}", Botan::hex_encode(seed), epoch);
1✔
974
}
1✔
975

976
//static
977
std::unique_ptr<Botan::RandomNumberGenerator> Test::new_rng(std::string_view test_name) {
269✔
978
   return std::make_unique<Testsuite_RNG>(m_test_rng_seed, test_name);
269✔
979
}
980

981
//static
982
std::shared_ptr<Botan::RandomNumberGenerator> Test::new_shared_rng(std::string_view test_name) {
8✔
983
   return std::make_shared<Testsuite_RNG>(m_test_rng_seed, test_name);
8✔
984
}
985

986
//static
987
std::string Test::data_file(const std::string& file) {
773✔
988
   return options().data_dir() + "/" + file;
1,546✔
989
}
990

991
//static
992
std::string Test::data_dir(const std::string& subdir) {
1✔
993
   return options().data_dir() + "/" + subdir;
2✔
994
}
995

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

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

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

1032
std::string Test::random_password(Botan::RandomNumberGenerator& rng) {
222✔
1033
   const size_t len = 1 + rng.next_byte() % 32;
222✔
1034
   return Botan::hex_encode(rng.random_vec(len));
444✔
1035
}
1036

1037
size_t Test::random_index(Botan::RandomNumberGenerator& rng, size_t max) {
8,062✔
1038
   return Botan::load_be(rng.random_array<8>()) % max;
8,062✔
1039
}
1040

1041
void VarMap::clear() {
34,297✔
1042
   m_vars.clear();
×
1043
}
×
1044

1045
namespace {
1046

1047
bool varmap_pair_lt(const std::pair<std::string, std::string>& kv, std::string_view k) {
1,713,996✔
1048
   return kv.first < k;
1,713,996✔
1049
}
1050

1051
}  // namespace
1052

1053
bool VarMap::has_key(std::string_view key) const {
213,622✔
1054
   return get_opt_var(key).has_value();
213,622✔
1055
}
1056

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

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

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

1070
   if(i != m_vars.end() && i->first == key) {
310,716✔
1071
      return i->second;
239,010✔
1072
   } else {
1073
      return {};
69,905✔
1074
   }
1075
}
1076

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

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

1087
std::string VarMap::get_req_str(std::string_view key) const {
52,801✔
1088
   return std::string(get_req_var(key));
52,801✔
1089
}
1090

1091
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(std::string_view key) const {
12✔
1092
   const auto& var = get_req_var(key);
12✔
1093

1094
   std::vector<std::vector<uint8_t>> bin_list;
12✔
1095

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

1107
   return bin_list;
12✔
1108
}
×
1109

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

1113
   try {
163,786✔
1114
      return Botan::hex_decode(var);
163,786✔
1115
   } catch(std::exception& e) {
×
1116
      throw Test_Error(Botan::fmt("Bad hex input '{}' for key '{}' err '{}'", var, key, e.what()));
×
1117
   }
×
1118
}
1119

1120
std::string VarMap::get_opt_str(std::string_view key, std::string_view def_value) const {
14,378✔
1121
   if(auto v = get_opt_var(key)) {
14,378✔
1122
      return *v;
14,435✔
1123
   } else {
1124
      return std::string(def_value);
28,642✔
1125
   }
14,378✔
1126
}
1127

1128
bool VarMap::get_req_bool(std::string_view key) const {
39✔
1129
   const auto& var = get_req_var(key);
39✔
1130

1131
   if(var == "true") {
39✔
1132
      return true;
1133
   } else if(var == "false") {
23✔
1134
      return false;
1135
   } else {
1136
      throw Test_Error(Botan::fmt("Invalid boolean '{}' for key '{}'", var, key));
×
1137
   }
1138
}
1139

1140
size_t VarMap::get_req_sz(std::string_view key) const {
4,547✔
1141
   return Botan::to_u32bit(get_req_var(key));
4,547✔
1142
}
1143

1144
uint8_t VarMap::get_req_u8(std::string_view key) const {
17✔
1145
   const size_t s = this->get_req_sz(key);
17✔
1146
   if(s > 256) {
17✔
1147
      throw Test_Error(Botan::fmt("Invalid value for '{}' expected uint8_t but got '{}'", key, s));
×
1148
   }
1149
   return static_cast<uint8_t>(s);
17✔
1150
}
1151

1152
uint32_t VarMap::get_req_u32(std::string_view key) const {
14✔
1153
   return static_cast<uint32_t>(get_req_sz(key));
14✔
1154
}
1155

1156
uint64_t VarMap::get_req_u64(std::string_view key) const {
17✔
1157
   const auto& var = get_req_var(key);
17✔
1158
   try {
17✔
1159
      return std::stoull(var);
17✔
1160
   } catch(std::exception&) {
×
1161
      throw Test_Error("Invalid u64 value '" + var + "'");
×
1162
   }
×
1163
}
1164

1165
size_t VarMap::get_opt_sz(std::string_view key, const size_t def_value) const {
31,404✔
1166
   if(auto v = get_opt_var(key)) {
31,404✔
1167
      return Botan::to_u32bit(*v);
12,244✔
1168
   } else {
1169
      return def_value;
1170
   }
31,404✔
1171
}
1172

1173
uint64_t VarMap::get_opt_u64(std::string_view key, const uint64_t def_value) const {
3,538✔
1174
   if(auto v = get_opt_var(key)) {
3,538✔
1175
      try {
641✔
1176
         return std::stoull(*v);
3,538✔
1177
      } catch(std::exception&) {
×
1178
         throw Test_Error("Invalid u64 value '" + *v + "'");
×
1179
      }
×
1180
   } else {
1181
      return def_value;
1182
   }
3,538✔
1183
}
×
1184

1185
std::vector<uint8_t> VarMap::get_opt_bin(std::string_view key) const {
45,893✔
1186
   if(auto v = get_opt_var(key)) {
45,893✔
1187
      try {
16,134✔
1188
         return Botan::hex_decode(*v);
16,134✔
1189
      } catch(std::exception&) {
×
1190
         throw Test_Error(Botan::fmt("Invalid hex for key '{}' got '{}'", key, *v));
×
1191
      }
×
1192
   } else {
1193
      return {};
29,759✔
1194
   };
45,893✔
1195
}
1196

1197
#if defined(BOTAN_HAS_BIGINT)
1198
Botan::BigInt VarMap::get_req_bn(std::string_view key) const {
38,502✔
1199
   const auto& var = get_req_var(key);
38,502✔
1200

1201
   try {
38,502✔
1202
      return Botan::BigInt(var);
38,502✔
1203
   } catch(std::exception&) {
×
1204
      throw Test_Error(Botan::fmt("Invalid BigInt for key '{}' got '{}'", key, var));
×
1205
   }
×
1206
}
1207

1208
Botan::BigInt VarMap::get_opt_bn(std::string_view key, const Botan::BigInt& def_value) const {
80✔
1209
   if(auto v = get_opt_var(key)) {
80✔
1210
      try {
56✔
1211
         return Botan::BigInt(*v);
56✔
1212
      } catch(std::exception&) {
×
1213
         throw Test_Error(Botan::fmt("Invalid BigInt for key '{}' got '{}'", key, *v));
×
1214
      }
×
1215
   } else {
1216
      return def_value;
24✔
1217
   }
80✔
1218
}
1219
#endif
1220

1221
class Text_Based_Test::Text_Based_Test_Data {
1222
   public:
1223
      Text_Based_Test_Data(const std::string& data_src,
181✔
1224
                           const std::string& required_keys_str,
1225
                           const std::string& optional_keys_str) :
181✔
1226
            m_data_src(data_src) {
362✔
1227
         if(required_keys_str.empty()) {
181✔
1228
            throw Test_Error("Invalid test spec");
×
1229
         }
1230

1231
         m_required_keys = Botan::split_on(required_keys_str, ',');
181✔
1232
         std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
181✔
1233

1234
         m_all_keys.insert(m_required_keys.begin(), m_required_keys.end());
181✔
1235
         m_all_keys.insert(optional_keys.begin(), optional_keys.end());
181✔
1236
         m_output_key = m_required_keys.at(m_required_keys.size() - 1);
181✔
1237
      }
181✔
1238

1239
      std::string get_next_line();
1240

1241
      const std::string& current_source_name() const { return m_cur_src_name; }
×
1242

1243
      bool known_key(const std::string& key) const;
1244

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

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

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

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

1253
      const std::string& initial_data_src_name() const { return m_data_src; }
181✔
1254

1255
   private:
1256
      std::string m_data_src;
1257
      std::vector<std::string> m_required_keys;
1258
      std::unordered_set<std::string> m_all_keys;
1259
      std::string m_output_key;
1260

1261
      bool m_first = true;
1262
      std::unique_ptr<std::istream> m_cur;
1263
      std::string m_cur_src_name;
1264
      std::deque<std::string> m_srcs;
1265
      std::vector<std::string> m_cpu_flags;
1266
};
1267

1268
Text_Based_Test::Text_Based_Test(const std::string& data_src,
181✔
1269
                                 const std::string& required_keys,
1270
                                 const std::string& optional_keys) :
181✔
1271
      m_data(std::make_unique<Text_Based_Test_Data>(data_src, required_keys, optional_keys)) {}
181✔
1272

1273
Text_Based_Test::~Text_Based_Test() = default;
181✔
1274

1275
std::string Text_Based_Test::Text_Based_Test_Data::get_next_line() {
157,290✔
1276
   while(true) {
157,548✔
1277
      if(m_cur == nullptr || m_cur->good() == false) {
157,548✔
1278
         if(m_srcs.empty()) {
450✔
1279
            if(m_first) {
362✔
1280
               if(m_data_src.ends_with(".vec")) {
181✔
1281
                  m_srcs.push_back(Test::data_file(m_data_src));
338✔
1282
               } else {
1283
                  const auto fs = Test::files_in_data_dir(m_data_src);
12✔
1284
                  m_srcs.assign(fs.begin(), fs.end());
12✔
1285
                  if(m_srcs.empty()) {
12✔
1286
                     throw Test_Error("Error reading test data dir " + m_data_src);
×
1287
                  }
1288
               }
12✔
1289

1290
               m_first = false;
181✔
1291
            } else {
1292
               return "";  // done
181✔
1293
            }
1294
         }
1295

1296
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
357✔
1297
         m_cur_src_name = m_srcs[0];
269✔
1298

1299
#if defined(BOTAN_HAS_CPUID)
1300
         // Reinit cpuid on new file if needed
1301
         if(m_cpu_flags.empty() == false) {
269✔
1302
            m_cpu_flags.clear();
19✔
1303
            Botan::CPUID::initialize();
19✔
1304
         }
1305
#endif
1306

1307
         if(!m_cur->good()) {
269✔
1308
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
1309
         }
1310

1311
         m_srcs.pop_front();
269✔
1312
      }
1313

1314
      while(m_cur->good()) {
227,971✔
1315
         std::string line;
227,713✔
1316
         std::getline(*m_cur, line);
227,713✔
1317

1318
         if(line.empty()) {
227,713✔
1319
            continue;
55,323✔
1320
         }
1321

1322
         if(line[0] == '#') {
172,390✔
1323
            if(line.starts_with("#test ")) {
15,302✔
1324
               return line;
21✔
1325
            } else {
1326
               continue;
15,281✔
1327
            }
1328
         }
1329

1330
         return line;
157,088✔
1331
      }
227,713✔
1332
   }
1333
}
1334

1335
bool Text_Based_Test::Text_Based_Test_Data::known_key(const std::string& key) const {
156,283✔
1336
   return m_all_keys.contains(key);
156,283✔
1337
}
1338

1339
namespace {
1340

1341
// strips leading and trailing but not internal whitespace
1342
std::string strip_ws(const std::string& in) {
312,566✔
1343
   const char* whitespace = " ";
312,566✔
1344

1345
   const auto first_c = in.find_first_not_of(whitespace);
312,566✔
1346
   if(first_c == std::string::npos) {
312,566✔
1347
      return "";
1,034✔
1348
   }
1349

1350
   const auto last_c = in.find_last_not_of(whitespace);
311,532✔
1351

1352
   return in.substr(first_c, last_c - first_c + 1);
311,532✔
1353
}
1354

1355
std::vector<std::string> parse_cpuid_bits(const std::vector<std::string>& tok) {
21✔
1356
   std::vector<std::string> bits;
21✔
1357

1358
#if defined(BOTAN_HAS_CPUID)
1359
   for(size_t i = 1; i < tok.size(); ++i) {
106✔
1360
      if(auto bit = Botan::CPUID::bit_from_string(tok[i])) {
85✔
1361
         bits.push_back(bit->to_string());
98✔
1362
      }
1363
   }
1364
#else
1365
   BOTAN_UNUSED(tok);
1366
#endif
1367

1368
   return bits;
21✔
1369
}
×
1370

1371
}  // namespace
1372

1373
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) {
32,625✔
1374
   return false;
32,625✔
1375
}
1376

1377
std::vector<Test::Result> Text_Based_Test::run() {
181✔
1378
   std::vector<Test::Result> results;
181✔
1379

1380
   std::string header;
181✔
1381
   std::string header_or_name = m_data->initial_data_src_name();
181✔
1382
   VarMap vars;
181✔
1383
   size_t test_cnt = 0;
181✔
1384

1385
   while(true) {
157,290✔
1386
      const std::string line = m_data->get_next_line();
157,290✔
1387
      if(line.empty()) {
157,290✔
1388
         // EOF
1389
         break;
1390
      }
1391

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

1395
         if(pragma_tokens.empty()) {
21✔
1396
            throw Test_Error("Empty pragma found in " + m_data->current_source_name());
×
1397
         }
1398

1399
         if(pragma_tokens[0] != "cpuid") {
21✔
1400
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1401
         }
1402

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

1407
         m_data->set_cpu_flags(parse_cpuid_bits(pragma_tokens));
42✔
1408

1409
         continue;
21✔
1410
      } else if(line[0] == '#') {
157,109✔
1411
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1412
      }
1413

1414
      if(line[0] == '[' && line[line.size() - 1] == ']') {
157,088✔
1415
         header = line.substr(1, line.size() - 2);
805✔
1416
         header_or_name = header;
805✔
1417
         test_cnt = 0;
805✔
1418
         vars.clear();
805✔
1419
         continue;
805✔
1420
      }
1421

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

1424
      auto equal_i = line.find_first_of('=');
156,283✔
1425

1426
      if(equal_i == std::string::npos) {
156,283✔
1427
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1428
         continue;
×
1429
      }
1430

1431
      const std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
312,566✔
1432
      const std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
312,566✔
1433

1434
      if(!m_data->known_key(key)) {
156,283✔
1435
         auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key));
×
1436
         results.push_back(r);
×
1437
      }
×
1438

1439
      vars.add(key, val);
156,283✔
1440

1441
      if(key == m_data->output_key()) {
156,283✔
1442
         try {
48,404✔
1443
            for(const auto& req_key : m_data->required_keys()) {
245,618✔
1444
               if(!vars.has_key(req_key)) {
197,214✔
1445
                  auto r =
×
1446
                     Test::Result::Failure(header_or_name, Botan::fmt("{} missing required key {}", test_id, req_key));
×
1447
                  results.push_back(r);
×
1448
               }
×
1449
            }
1450

1451
            if(skip_this_test(header, vars)) {
48,404✔
1452
               continue;
139✔
1453
            }
1454

1455
            ++test_cnt;
48,265✔
1456

1457
            const uint64_t start = Test::timestamp();
48,265✔
1458

1459
            Test::Result result = run_one_test(header, vars);
48,265✔
1460
#if defined(BOTAN_HAS_CPUID)
1461
            if(!m_data->cpu_flags().empty()) {
48,265✔
1462
               for(const auto& cpuid_str : m_data->cpu_flags()) {
30,651✔
1463
                  if(const auto bit = Botan::CPUID::Feature::from_string(cpuid_str)) {
21,698✔
1464
                     if(Botan::CPUID::has(*bit)) {
21,698✔
1465
                        Botan::CPUID::clear_cpuid_bit(*bit);
16,586✔
1466
                        // now re-run the test
1467
                        result.merge(run_one_test(header, vars));
16,586✔
1468
                     }
1469
                  }
1470
               }
1471
               Botan::CPUID::initialize();
8,953✔
1472
            }
1473
#endif
1474
            result.set_ns_consumed(Test::timestamp() - start);
48,265✔
1475

1476
            if(result.tests_failed() > 0) {
48,265✔
1477
               std::ostringstream oss;
×
1478
               oss << "Test # " << test_cnt << " ";
×
1479
               if(!header.empty()) {
×
1480
                  oss << header << " ";
×
1481
               }
1482
               oss << "failed ";
×
1483

1484
               for(const auto& k : m_data->required_keys()) {
×
1485
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1486
               }
1487

1488
               result.test_note(oss.str());
×
1489
            }
×
1490
            results.push_back(result);
48,265✔
1491
         } catch(std::exception& e) {
48,265✔
1492
            std::ostringstream oss;
×
1493
            oss << "Test # " << test_cnt << " ";
×
1494
            if(!header.empty()) {
×
1495
               oss << header << " ";
×
1496
            }
1497

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

1502
            oss << "failed with exception '" << e.what() << "'";
×
1503

1504
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1505
         }
×
1506

1507
         if(clear_between_callbacks()) {
48,265✔
1508
            vars.clear();
189,636✔
1509
         }
1510
      }
1511
   }
157,387✔
1512

1513
   if(results.empty()) {
181✔
1514
      return results;
1515
   }
1516

1517
   try {
181✔
1518
      std::vector<Test::Result> final_tests = run_final_tests();
181✔
1519
      results.insert(results.end(), final_tests.begin(), final_tests.end());
181✔
1520
   } catch(std::exception& e) {
181✔
1521
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1522
   }
×
1523

1524
   return results;
1525
}
181✔
1526

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