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

randombit / botan / 22010728410

13 Feb 2026 11:47PM UTC coverage: 90.064% (-0.001%) from 90.065%
22010728410

push

github

web-flow
Merge pull request #5327 from randombit/jack/test-h-cleanups

Various cleanups for tests.h

102223 of 113501 relevant lines covered (90.06%)

11484792.55 hits per line

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

79.3
/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;
419✔
59

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

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

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

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

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

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

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

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

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

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

135
bool Test::Result::ThrowExpectations::check(std::string_view test_name, Test::Result& result) {
67,783✔
136
   m_consumed = true;
67,783✔
137

138
   try {
67,783✔
139
      m_fn();
67,783✔
140
      if(!m_expect_success) {
1,646✔
141
         return result.test_failure(Botan::fmt("{} failed to throw expected exception", test_name));
2✔
142
      }
143
   } catch(const std::exception& ex) {
66,137✔
144
      if(m_expect_success) {
66,135✔
145
         return result.test_failure(Botan::fmt("{} threw unexpected exception: {}", test_name, ex.what()));
1✔
146
      }
147
      if(m_expected_exception_check_fn && !m_expected_exception_check_fn(std::current_exception())) {
190,230✔
148
         return result.test_failure(Botan::fmt("{} threw unexpected exception: {}", test_name, ex.what()));
2✔
149
      }
150
      if(m_expected_message.has_value() && m_expected_message.value() != ex.what()) {
66,132✔
151
         return result.test_failure(Botan::fmt("{} threw exception with unexpected message (expected {} got {})",
1✔
152
                                               test_name,
153
                                               m_expected_message.value(),
1✔
154
                                               ex.what()));
2✔
155
      }
156
   } catch(...) {
66,137✔
157
      if(m_expect_success || m_expected_exception_check_fn || m_expected_message.has_value()) {
2✔
158
         return result.test_failure(Botan::fmt("{} threw unexpected unknown exception", test_name));
1✔
159
      }
160
   }
2✔
161

162
   return result.test_success();
67,776✔
163
}
164

165
bool Test::Result::test_throws(std::string_view what, const std::function<void()>& fn) {
3,916✔
166
   return ThrowExpectations(fn).check(what, *this);
7,832✔
167
}
168

169
bool Test::Result::test_throws(std::string_view what, std::string_view expected, const std::function<void()>& fn) {
174✔
170
   return ThrowExpectations(fn).expect_message(expected).check(what, *this);
348✔
171
}
172

173
bool Test::Result::test_no_throw(std::string_view what, const std::function<void()>& fn) {
1,645✔
174
   return ThrowExpectations(fn).expect_success().check(what, *this);
3,290✔
175
}
176

177
bool Test::Result::test_success(std::string_view note) {
3,620,245✔
178
   if(Test::options().log_success()) {
3,620,220✔
179
      test_note(note);
×
180
   }
181
   ++m_tests_passed;
3,620,245✔
182
   return true;
775,693✔
183
}
184

185
bool Test::Result::test_failure(std::string_view what, std::string_view error) {
2✔
186
   return test_failure(Botan::fmt("{} {} with error {}", who(), what, error));
2✔
187
}
188

189
void Test::Result::test_failure(std::string_view what, const uint8_t buf[], size_t buf_len) {
×
190
   return test_failure(what, {buf, buf_len});
×
191
}
192

193
void Test::Result::test_failure(std::string_view what, std::span<const uint8_t> context) {
1✔
194
   test_failure(Botan::fmt("{} {} with value {}", who(), what, Botan::hex_encode(context)));
2✔
195
}
1✔
196

197
bool Test::Result::test_failure(std::string_view err) {
25✔
198
   m_fail_log.push_back(std::string(err));
25✔
199

200
   if(Test::options().abort_on_first_fail() && m_who != "Failing Test") {
25✔
201
      std::abort();
×
202
   }
203
   return false;
25✔
204
}
205

206
namespace {
207

208
bool same_contents(const uint8_t x[], const uint8_t y[], size_t len) {
292,388✔
209
   return (len == 0) ? true : std::memcmp(x, y, len) == 0;
290,957✔
210
}
211

212
}  // namespace
213

214
bool Test::Result::test_ne(std::string_view what,
3,405✔
215
                           const uint8_t produced[],
216
                           size_t produced_len,
217
                           const uint8_t expected[],
218
                           size_t expected_len) {
219
   if(produced_len == expected_len && same_contents(produced, expected, expected_len)) {
3,405✔
220
      return test_failure(Botan::fmt("{} {} produced matching bytes", who(), what));
2✔
221
   }
222
   return test_success();
3,403✔
223
}
224

225
bool Test::Result::test_eq(std::string_view what, std::span<const uint8_t> produced, const char* expected_hex) {
471✔
226
   const std::vector<uint8_t> expected = Botan::hex_decode(expected_hex);
471✔
227
   return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
471✔
228
}
471✔
229

230
bool Test::Result::test_eq(const char* producer,
290,963✔
231
                           std::string_view what,
232
                           const uint8_t produced[],
233
                           size_t produced_size,
234
                           const uint8_t expected[],
235
                           size_t expected_size) {
236
   if(produced_size == expected_size && same_contents(produced, expected, expected_size)) {
290,963✔
237
      return test_success();
290,962✔
238
   }
239

240
   std::ostringstream err;
1✔
241

242
   err << who();
1✔
243

244
   if(producer != nullptr) {
1✔
245
      err << " producer '" << producer << "'";
×
246
   }
247

248
   err << " unexpected result for " << what;
1✔
249

250
   if(produced_size != expected_size) {
1✔
251
      err << " produced " << produced_size << " bytes expected " << expected_size;
1✔
252
   }
253

254
   std::vector<uint8_t> xor_diff(std::min(produced_size, expected_size));
2✔
255
   size_t bytes_different = 0;
1✔
256

257
   for(size_t i = 0; i != xor_diff.size(); ++i) {
4✔
258
      xor_diff[i] = produced[i] ^ expected[i];
3✔
259
      if(xor_diff[i] > 0) {
3✔
260
         bytes_different++;
3✔
261
      }
262
   }
263

264
   err << "\nProduced: " << Botan::hex_encode(produced, produced_size)
1✔
265
       << "\nExpected: " << Botan::hex_encode(expected, expected_size);
3✔
266

267
   if(bytes_different > 0) {
1✔
268
      err << "\nXOR Diff: " << Botan::hex_encode(xor_diff);
1✔
269
   }
270

271
   return test_failure(err.str());
1✔
272
}
1✔
273

274
bool Test::Result::test_is_nonempty(std::string_view what_is_it, std::string_view to_examine) {
38,829✔
275
   if(to_examine.empty()) {
38,829✔
276
      return test_failure(what_is_it, "was empty");
1✔
277
   }
278
   return test_success();
38,828✔
279
}
280

281
bool Test::Result::test_eq(std::string_view what, std::string_view produced, std::string_view expected) {
76,783✔
282
   return test_is_eq(what, produced, expected);
76,783✔
283
}
284

285
bool Test::Result::test_eq(std::string_view what, const char* produced, const char* expected) {
29✔
286
   return test_is_eq(what, std::string(produced), std::string(expected));
29✔
287
}
288

289
bool Test::Result::test_eq(std::string_view what, size_t produced, size_t expected) {
146,709✔
290
   return test_is_eq(what, produced, expected);
146,709✔
291
}
292

293
bool Test::Result::test_eq_sz(std::string_view what, size_t produced, size_t expected) {
45,789✔
294
   return test_is_eq(what, produced, expected);
45,789✔
295
}
296

297
bool Test::Result::test_lt(std::string_view what, size_t produced, size_t expected) {
5,639✔
298
   if(produced >= expected) {
5,639✔
299
      std::ostringstream err;
1✔
300
      err << m_who << " " << what;
1✔
301
      err << " unexpected result " << produced << " >= " << expected;
1✔
302
      return test_failure(err.str());
1✔
303
   }
1✔
304

305
   return test_success();
5,638✔
306
}
307

308
bool Test::Result::test_lte(std::string_view what, size_t produced, size_t expected) {
1,021,636✔
309
   if(produced > expected) {
1,021,636✔
310
      std::ostringstream err;
1✔
311
      err << m_who << " " << what << " unexpected result " << produced << " > " << expected;
1✔
312
      return test_failure(err.str());
1✔
313
   }
1✔
314

315
   return test_success();
1,021,635✔
316
}
317

318
bool Test::Result::test_gte(std::string_view what, size_t produced, size_t expected) {
1,142,430✔
319
   if(produced < expected) {
1,142,430✔
320
      std::ostringstream err;
1✔
321
      err << m_who;
1✔
322
      err << " " << what;
1✔
323
      err << " unexpected result " << produced << " < " << expected;
1✔
324
      return test_failure(err.str());
1✔
325
   }
1✔
326

327
   return test_success();
1,142,429✔
328
}
329

330
bool Test::Result::test_gt(std::string_view what, size_t produced, size_t expected) {
22,373✔
331
   if(produced <= expected) {
22,373✔
332
      std::ostringstream err;
×
333
      err << m_who;
×
334
      err << " " << what;
×
335
      err << " unexpected result " << produced << " <= " << expected;
×
336
      return test_failure(err.str());
×
337
   }
×
338

339
   return test_success();
22,373✔
340
}
341

342
bool Test::Result::test_ne(std::string_view what, std::string_view str1, std::string_view str2) {
26✔
343
   if(str1 != str2) {
26✔
344
      return test_success(Botan::fmt("{} != {}", str1, str2));
25✔
345
   } else {
346
      return test_failure(Botan::fmt("{} {} unexpectedly produced matching strings {}", who(), what, str1));
1✔
347
   }
348
}
349

350
bool Test::Result::test_ne(std::string_view what, size_t produced, size_t expected) {
119✔
351
   if(produced != expected) {
119✔
352
      return test_success();
118✔
353
   }
354

355
   std::ostringstream err;
1✔
356
   err << who() << " " << what << " produced " << produced << " unexpected value";
1✔
357
   return test_failure(err.str());
1✔
358
}
1✔
359

360
#if defined(BOTAN_HAS_BIGINT)
361
bool Test::Result::test_eq(std::string_view what, const BigInt& produced, const BigInt& expected) {
252,643✔
362
   return test_is_eq(what, produced, expected);
252,643✔
363
}
364

365
bool Test::Result::test_ne(std::string_view what, const BigInt& produced, const BigInt& expected) {
97✔
366
   if(produced != expected) {
97✔
367
      return test_success();
96✔
368
   }
369

370
   std::ostringstream err;
1✔
371
   err << who() << " " << what << " produced " << produced << " prohibited value";
1✔
372
   return test_failure(err.str());
1✔
373
}
1✔
374
#endif
375

376
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
377
bool Test::Result::test_eq(std::string_view what, const Botan::EC_Point& a, const Botan::EC_Point& b) {
3,248✔
378
   //return test_is_eq(what, a, b);
379
   if(a == b) {
3,248✔
380
      return test_success();
3,248✔
381
   }
382

383
   std::ostringstream err;
×
384
   err << who() << " " << what << " a=(" << a.get_affine_x() << "," << a.get_affine_y() << ")"
×
385
       << " b=(" << b.get_affine_x() << "," << b.get_affine_y();
×
386
   return test_failure(err.str());
×
387
}
×
388
#endif
389

390
bool Test::Result::test_eq(std::string_view what, bool produced, bool expected) {
378,463✔
391
   return test_is_eq(what, produced, expected);
378,463✔
392
}
393

394
bool Test::Result::test_rc_ok(std::string_view func, int rc) {
2,810✔
395
   if(rc != 0) {
2,810✔
396
      std::ostringstream err;
1✔
397
      err << m_who << " " << func << " unexpectedly failed with error code " << rc;
1✔
398
      return test_failure(err.str());
1✔
399
   }
1✔
400

401
   return test_success();
2,809✔
402
}
403

404
bool Test::Result::test_rc_fail(std::string_view func, std::string_view why, int rc) {
26✔
405
   if(rc == 0) {
26✔
406
      std::ostringstream err;
1✔
407
      err << m_who << " call to " << func << " unexpectedly succeeded expecting failure because " << why;
1✔
408
      return test_failure(err.str());
1✔
409
   }
1✔
410

411
   return test_success();
25✔
412
}
413

414
bool Test::Result::test_rc_init(std::string_view func, int rc) {
117✔
415
   if(rc == 0) {
117✔
416
      return test_success();
117✔
417
   } else {
418
      std::ostringstream msg;
×
419
      msg << m_who;
×
420
      msg << " " << func;
×
421

422
      // -40 is BOTAN_FFI_ERROR_NOT_IMPLEMENTED
423
      if(rc == -40) {
×
424
         msg << " returned not implemented";
×
425
      } else {
426
         msg << " unexpectedly failed with error code " << rc;
×
427
      }
428

429
      if(rc == -40) {
×
430
         this->test_note(msg.str());
×
431
      } else {
432
         this->test_failure(msg.str());
×
433
      }
434
      return false;
×
435
   }
×
436
}
437

438
bool Test::Result::test_rc(std::string_view func, int expected, int rc) {
416✔
439
   if(expected != rc) {
416✔
440
      std::ostringstream err;
1✔
441
      err << m_who;
1✔
442
      err << " call to " << func << " unexpectedly returned " << rc;
1✔
443
      err << " but expecting " << expected;
1✔
444
      return test_failure(err.str());
1✔
445
   }
1✔
446

447
   return test_success();
415✔
448
}
449

450
void Test::initialize(std::string test_name, CodeLocation location) {
419✔
451
   m_test_name = std::move(test_name);
419✔
452
   m_registration_location = location;
419✔
453
}
419✔
454

455
Botan::RandomNumberGenerator& Test::rng() const {
458,738✔
456
   if(!m_test_rng) {
458,738✔
457
      m_test_rng = Test::new_rng(m_test_name);
145✔
458
   }
459

460
   return *m_test_rng;
458,738✔
461
}
462

463
std::optional<std::string> Test::supported_ec_group_name(std::vector<std::string> preferred_groups) {
151✔
464
#if defined(BOTAN_HAS_ECC_GROUP)
465
   if(preferred_groups.empty()) {
151✔
466
      preferred_groups = {
149✔
467
         "secp256r1",
468
         "brainpool256r1",
469
         "secp384r1",
470
         "brainpool384r1",
471
         "secp521r1",
472
         "brainpool512r1",
473
      };
1,192✔
474
   }
475

476
   for(const auto& group : preferred_groups) {
151✔
477
      if(Botan::EC_Group::supports_named_group(group)) {
151✔
478
         return group;
151✔
479
      }
480
   }
481
#else
482
   BOTAN_UNUSED(preferred_groups);
483
#endif
484

485
   return std::nullopt;
×
486
}
298✔
487

488
std::vector<uint8_t> Test::mutate_vec(const std::vector<uint8_t>& v,
96,742✔
489
                                      Botan::RandomNumberGenerator& rng,
490
                                      bool maybe_resize,
491
                                      size_t min_offset) {
492
   std::vector<uint8_t> r = v;
96,742✔
493

494
   if(maybe_resize && (r.empty() || rng.next_byte() < 32)) {
110,320✔
495
      // TODO: occasionally truncate, insert at random index
496
      const size_t add = 1 + (rng.next_byte() % 16);
2,156✔
497
      r.resize(r.size() + add);
2,156✔
498
      rng.randomize(&r[r.size() - add], add);
2,156✔
499
   }
500

501
   if(r.size() > min_offset) {
96,742✔
502
      const size_t offset = std::max<size_t>(min_offset, rng.next_byte() % r.size());
95,204✔
503
      const uint8_t perturb = rng.next_nonzero_byte();
95,204✔
504
      r[offset] ^= perturb;
95,204✔
505
   }
506

507
   return r;
96,742✔
508
}
×
509

510
std::vector<std::string> Test::possible_providers(const std::string& /*alg*/) {
×
511
   return Test::provider_filter({"base"});
×
512
}
513

514
//static
515
std::string Test::format_time(uint64_t nanoseconds) {
1,470✔
516
   std::ostringstream o;
1,470✔
517

518
   if(nanoseconds > 1000000000) {
1,470✔
519
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000000.0 << " sec";
151✔
520
   } else {
521
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000.0 << " msec";
1,319✔
522
   }
523

524
   return o.str();
2,940✔
525
}
1,470✔
526

527
// TODO: this should move to `StdoutReporter`
528
std::string Test::Result::result_string() const {
2,540✔
529
   const bool verbose = Test::options().verbose();
2,540✔
530

531
   if(tests_run() == 0 && !verbose) {
2,540✔
532
      return "";
20✔
533
   }
534

535
   std::ostringstream report;
2,520✔
536

537
   report << who() << " ran ";
2,520✔
538

539
   if(tests_run() == 0) {
2,520✔
540
      report << "ZERO";
×
541
   } else {
542
      report << tests_run();
2,520✔
543
   }
544
   report << " tests";
2,520✔
545

546
   if(m_ns_taken > 0) {
2,520✔
547
      report << " in " << format_time(m_ns_taken);
2,938✔
548
   }
549

550
   if(tests_failed() > 0) {
2,520✔
551
      report << " " << tests_failed() << " FAILED";
25✔
552
   } else {
553
      report << " all ok";
2,495✔
554
   }
555

556
   report << "\n";
2,520✔
557

558
   for(size_t i = 0; i != m_fail_log.size(); ++i) {
2,545✔
559
      report << "Failure " << (i + 1) << ": " << m_fail_log[i];
25✔
560
      if(m_where) {
25✔
561
         report << " (at " << m_where->path << ":" << m_where->line << ")";
×
562
      }
563
      report << "\n";
25✔
564
   }
565

566
   if(!m_fail_log.empty() || tests_run() == 0 || verbose) {
2,520✔
567
      for(size_t i = 0; i != m_log.size(); ++i) {
25✔
568
         report << "Note " << (i + 1) << ": " << m_log[i] << "\n";
×
569
      }
570
   }
571

572
   return report.str();
2,520✔
573
}
2,520✔
574

575
namespace {
576

577
class Test_Registry {
578
   public:
579
      static Test_Registry& instance() {
1,279✔
580
         static Test_Registry registry;
1,280✔
581
         return registry;
1,279✔
582
      }
583

584
      void register_test(const std::string& category,
419✔
585
                         const std::string& name,
586
                         bool smoke_test,
587
                         bool needs_serialization,
588
                         std::function<std::unique_ptr<Test>()> maker_fn) {
589
         if(m_tests.contains(name)) {
419✔
590
            throw Test_Error("Duplicate registration of test '" + name + "'");
×
591
         }
592

593
         if(m_tests.contains(category)) {
419✔
594
            throw Test_Error("'" + category + "' cannot be used as category, test exists");
×
595
         }
596

597
         if(m_categories.contains(name)) {
419✔
598
            throw Test_Error("'" + name + "' cannot be used as test name, category exists");
×
599
         }
600

601
         if(smoke_test) {
419✔
602
            m_smoke_tests.push_back(name);
10✔
603
         }
604

605
         if(needs_serialization) {
419✔
606
            m_mutexed_tests.push_back(name);
21✔
607
         }
608

609
         m_tests.emplace(name, std::move(maker_fn));
419✔
610
         m_categories.emplace(category, name);
419✔
611
      }
419✔
612

613
      std::unique_ptr<Test> get_test(const std::string& test_name) const {
419✔
614
         auto i = m_tests.find(test_name);
419✔
615
         if(i != m_tests.end()) {
419✔
616
            return i->second();
419✔
617
         }
618
         return nullptr;
×
619
      }
620

621
      std::vector<std::string> registered_tests() const {
×
622
         std::vector<std::string> s;
×
623
         s.reserve(m_tests.size());
×
624
         for(auto&& i : m_tests) {
×
625
            s.push_back(i.first);
×
626
         }
627
         return s;
×
628
      }
×
629

630
      std::vector<std::string> registered_test_categories() const {
×
631
         std::set<std::string> s;
×
632
         for(auto&& i : m_categories) {
×
633
            s.insert(i.first);
×
634
         }
635
         return std::vector<std::string>(s.begin(), s.end());
×
636
      }
×
637

638
      std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
1✔
639
                                                       const std::vector<std::string>& to_be_skipped) {
640
         std::vector<std::string> result;
1✔
641

642
         std::set<std::string> to_be_skipped_set(to_be_skipped.begin(), to_be_skipped.end());
1✔
643
         // TODO: this is O(n^2), but we have a relatively small number of tests.
644
         auto insert_if_not_exists_and_not_skipped = [&](const std::string& test_name) {
420✔
645
            if(!Botan::value_exists(result, test_name) && !to_be_skipped_set.contains(test_name)) {
838✔
646
               result.push_back(test_name);
409✔
647
            }
648
         };
420✔
649

650
         if(requested.empty()) {
1✔
651
            /*
652
            If nothing was requested on the command line, run everything. First
653
            run the "essentials" to smoke test, then everything else in
654
            alphabetical order.
655
            */
656
            result = m_smoke_tests;
1✔
657
            for(const auto& [test_name, _] : m_tests) {
420✔
658
               insert_if_not_exists_and_not_skipped(test_name);
419✔
659
            }
660
         } else {
661
            for(const auto& r : requested) {
×
662
               if(m_tests.contains(r)) {
×
663
                  insert_if_not_exists_and_not_skipped(r);
×
664
               } else if(auto elems = m_categories.equal_range(r); elems.first != m_categories.end()) {
×
665
                  for(; elems.first != elems.second; ++elems.first) {
×
666
                     insert_if_not_exists_and_not_skipped(elems.first->second);
×
667
                  }
668
               } else {
669
                  throw Test_Error("Unknown test suite or category: " + r);
×
670
               }
671
            }
672
         }
673

674
         return result;
1✔
675
      }
1✔
676

677
      bool needs_serialization(const std::string& test_name) const {
440✔
678
         return Botan::value_exists(m_mutexed_tests, test_name);
21✔
679
      }
680

681
   private:
682
      Test_Registry() = default;
1✔
683

684
   private:
685
      std::map<std::string, std::function<std::unique_ptr<Test>()>> m_tests;
686
      std::multimap<std::string, std::string> m_categories;
687
      std::vector<std::string> m_smoke_tests;
688
      std::vector<std::string> m_mutexed_tests;
689
};
690

691
}  // namespace
692

693
// static Test:: functions
694

695
//static
696
void Test::register_test(const std::string& category,
419✔
697
                         const std::string& name,
698
                         bool smoke_test,
699
                         bool needs_serialization,
700
                         std::function<std::unique_ptr<Test>()> maker_fn) {
701
   Test_Registry::instance().register_test(category, name, smoke_test, needs_serialization, std::move(maker_fn));
838✔
702
}
419✔
703

704
//static
705
uint64_t Test::timestamp() {
180,010✔
706
   auto now = std::chrono::system_clock::now().time_since_epoch();
180,010✔
707
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
2,383✔
708
}
709

710
//static
711
std::vector<Test::Result> Test::flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists) {
4✔
712
   std::vector<Test::Result> results;
4✔
713
   for(auto& result_list : result_lists) {
26✔
714
      for(auto& result : result_list) {
71✔
715
         results.emplace_back(std::move(result));
49✔
716
      }
717
   }
718
   return results;
4✔
719
}
×
720

721
//static
722
std::vector<std::string> Test::registered_tests() {
×
723
   return Test_Registry::instance().registered_tests();
×
724
}
725

726
//static
727
std::vector<std::string> Test::registered_test_categories() {
×
728
   return Test_Registry::instance().registered_test_categories();
×
729
}
730

731
//static
732
std::unique_ptr<Test> Test::get_test(const std::string& test_name) {
419✔
733
   return Test_Registry::instance().get_test(test_name);
419✔
734
}
735

736
//static
737
bool Test::test_needs_serialization(const std::string& test_name) {
419✔
738
   return Test_Registry::instance().needs_serialization(test_name);
419✔
739
}
740

741
//static
742
std::vector<std::string> Test::filter_registered_tests(const std::vector<std::string>& requested,
1✔
743
                                                       const std::vector<std::string>& to_be_skipped) {
744
   return Test_Registry::instance().filter_registered_tests(requested, to_be_skipped);
1✔
745
}
746

747
//static
748
std::string Test::temp_file_name(const std::string& basename) {
21✔
749
   // TODO add a --tmp-dir option to the tests to specify where these files go
750

751
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
752

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

756
   const int fd = ::mkstemp(mkstemp_basename.data());
21✔
757

758
   // error
759
   if(fd < 0) {
21✔
760
      return "";
×
761
   }
762

763
   ::close(fd);
21✔
764

765
   return mkstemp_basename;
21✔
766
#else
767
   // For now just create the temp in the current working directory
768
   return basename;
769
#endif
770
}
21✔
771

772
bool Test::copy_file(const std::string& from, const std::string& to) {
1✔
773
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(__cpp_lib_filesystem)
774
   std::error_code ec;  // don't throw, just return false on error
1✔
775
   return std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
1✔
776
#else
777
   // TODO: implement fallbacks to POSIX or WIN32
778
   // ... but then again: it's 2023 and we're using C++20 :o)
779
   BOTAN_UNUSED(from, to);
780
   throw Botan::No_Filesystem_Access();
781
#endif
782
}
783

784
std::string Test::read_data_file(const std::string& path) {
38✔
785
   const std::string fsname = Test::data_file(path);
38✔
786
   std::ifstream file(fsname.c_str());
38✔
787
   if(!file.good()) {
38✔
788
      throw Test_Error("Error reading from " + fsname);
×
789
   }
790

791
   return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
76✔
792
}
38✔
793

794
std::vector<uint8_t> Test::read_binary_data_file(const std::string& path) {
34✔
795
   const std::string fsname = Test::data_file(path);
34✔
796
   std::ifstream file(fsname.c_str(), std::ios::binary);
34✔
797
   if(!file.good()) {
34✔
798
      throw Test_Error("Error reading from " + fsname);
×
799
   }
800

801
   std::vector<uint8_t> contents;
34✔
802

803
   while(file.good()) {
74✔
804
      std::vector<uint8_t> buf(4096);
40✔
805
      file.read(reinterpret_cast<char*>(buf.data()), buf.size());
40✔
806
      const size_t got = static_cast<size_t>(file.gcount());
40✔
807

808
      if(got == 0 && file.eof()) {
40✔
809
         break;
810
      }
811

812
      contents.insert(contents.end(), buf.data(), buf.data() + got);
40✔
813
   }
40✔
814

815
   return contents;
68✔
816
}
34✔
817

818
// static member variables of Test
819

820
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
821
Test_Options Test::m_opts;
822
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
823
std::string Test::m_test_rng_seed;
824

825
//static
826
void Test::set_test_options(const Test_Options& opts) {
1✔
827
   m_opts = opts;
1✔
828
}
1✔
829

830
namespace {
831

832
/*
833
* This is a fast, simple, deterministic PRNG that's used for running
834
* the tests. It is not intended to be cryptographically secure.
835
*/
836
class Testsuite_RNG final : public Botan::RandomNumberGenerator {
8✔
837
   public:
838
      std::string name() const override { return "Testsuite_RNG"; }
×
839

840
      void clear() override { m_x = 0; }
×
841

842
      bool accepts_input() const override { return true; }
×
843

844
      bool is_seeded() const override { return true; }
276,680✔
845

846
      void fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) override {
10,247,714✔
847
         for(const auto byte : input) {
10,247,714✔
848
            mix(byte);
×
849
         }
850

851
         for(auto& byte : output) {
73,439,767✔
852
            byte = mix();
63,192,053✔
853
         }
854
      }
10,247,714✔
855

856
      Testsuite_RNG(std::string_view seed, std::string_view test_name) : m_x(0) {
276✔
857
         for(const char c : seed) {
8,280✔
858
            this->mix(static_cast<uint8_t>(c));
8,004✔
859
         }
860
         for(const char c : test_name) {
5,578✔
861
            this->mix(static_cast<uint8_t>(c));
5,302✔
862
         }
863
      }
276✔
864

865
   private:
866
      uint8_t mix(uint8_t input = 0) {
63,205,359✔
867
         m_x ^= input;
63,205,359✔
868
         m_x *= 0xF2E16957;
63,205,359✔
869
         m_x += 0xE50B590F;
63,205,359✔
870
         return static_cast<uint8_t>(m_x >> 27);
63,205,359✔
871
      }
872

873
      uint64_t m_x;
874
};
875

876
}  // namespace
877

878
//static
879
void Test::set_test_rng_seed(std::span<const uint8_t> seed, size_t epoch) {
1✔
880
   m_test_rng_seed = Botan::fmt("seed={} epoch={}", Botan::hex_encode(seed), epoch);
1✔
881
}
1✔
882

883
//static
884
std::unique_ptr<Botan::RandomNumberGenerator> Test::new_rng(std::string_view test_name) {
268✔
885
   return std::make_unique<Testsuite_RNG>(m_test_rng_seed, test_name);
268✔
886
}
887

888
//static
889
std::shared_ptr<Botan::RandomNumberGenerator> Test::new_shared_rng(std::string_view test_name) {
8✔
890
   return std::make_shared<Testsuite_RNG>(m_test_rng_seed, test_name);
8✔
891
}
892

893
//static
894
std::string Test::data_file(const std::string& file) {
773✔
895
   return options().data_dir() + "/" + file;
1,546✔
896
}
897

898
//static
899
std::string Test::data_dir(const std::string& subdir) {
1✔
900
   return options().data_dir() + "/" + subdir;
2✔
901
}
902

903
//static
904
std::vector<std::string> Test::files_in_data_dir(const std::string& subdir) {
393✔
905
   auto fs = Botan::get_files_recursive(options().data_dir() + "/" + subdir);
1,179✔
906
   if(fs.empty()) {
393✔
907
      throw Test_Error("Test::files_in_data_dir encountered empty subdir " + subdir);
×
908
   }
909
   return fs;
393✔
910
}
×
911

912
//static
913
std::string Test::data_file_as_temporary_copy(const std::string& what) {
1✔
914
   auto tmp_basename = what;
1✔
915
   std::replace(tmp_basename.begin(), tmp_basename.end(), '/', '_');
1✔
916
   auto temp_file = temp_file_name("tmp-" + tmp_basename);
1✔
917
   if(temp_file.empty()) {
1✔
918
      return "";
×
919
   }
920
   if(!Test::copy_file(data_file(what), temp_file)) {
1✔
921
      return "";
×
922
   }
923
   return temp_file;
1✔
924
}
1✔
925

926
//static
927
std::vector<std::string> Test::provider_filter(const std::vector<std::string>& providers) {
49,022✔
928
   if(m_opts.provider().empty()) {
49,022✔
929
      return providers;
49,022✔
930
   }
931
   for(auto&& provider : providers) {
×
932
      if(provider == m_opts.provider()) {
×
933
         return std::vector<std::string>{provider};
×
934
      }
935
   }
936
   return std::vector<std::string>{};
×
937
}
×
938

939
std::string Test::random_password(Botan::RandomNumberGenerator& rng) {
222✔
940
   const size_t len = 1 + rng.next_byte() % 32;
222✔
941
   return Botan::hex_encode(rng.random_vec(len));
444✔
942
}
943

944
size_t Test::random_index(Botan::RandomNumberGenerator& rng, size_t max) {
8,062✔
945
   return Botan::load_be(rng.random_array<8>()) % max;
8,062✔
946
}
947

948
void VarMap::clear() {
34,281✔
949
   m_vars.clear();
×
950
}
×
951

952
namespace {
953

954
bool varmap_pair_lt(const std::pair<std::string, std::string>& kv, const std::string& k) {
1,713,618✔
955
   return kv.first < k;
1,713,618✔
956
}
957

958
}  // namespace
959

960
void VarMap::add(const std::string& key, const std::string& value) {
156,235✔
961
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
156,235✔
962

963
   if(i != m_vars.end() && i->first == key) {
156,235✔
964
      i->second = value;
44,405✔
965
   } else {
966
      m_vars.emplace(i, key, value);
111,830✔
967
   }
968
}
156,235✔
969

970
std::optional<std::string> VarMap::get_var(const std::string& key) const {
568,446✔
971
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
568,446✔
972

973
   if(i != m_vars.end() && i->first == key) {
568,446✔
974
      return i->second;
498,591✔
975
   } else {
976
      return {};
69,855✔
977
   }
978
}
979

980
bool VarMap::has_key(const std::string& key) const {
213,574✔
981
   return get_var(key).has_value();
213,574✔
982
}
983

984
std::string VarMap::get_req_str(const std::string& key) const {
259,629✔
985
   auto var = get_var(key);
259,629✔
986
   if(var) {
259,629✔
987
      return *var;
519,258✔
988
   } else {
989
      throw Test_Error("Test missing variable " + key);
×
990
   }
991
}
259,629✔
992

993
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(const std::string& key) const {
12✔
994
   const auto var = get_req_str(key);
12✔
995

996
   std::vector<std::vector<uint8_t>> bin_list;
12✔
997

998
   for(auto&& part : Botan::split_on(var, ',')) {
62✔
999
      try {
50✔
1000
         bin_list.push_back(Botan::hex_decode(part));
100✔
1001
      } catch(std::exception& e) {
×
1002
         std::ostringstream oss;
×
1003
         oss << "Bad input '" << part << "'"
×
1004
             << " in binary list key " << key << " - " << e.what();
×
1005
         throw Test_Error(oss.str());
×
1006
      }
×
1007
   }
12✔
1008

1009
   return bin_list;
12✔
1010
}
12✔
1011

1012
std::vector<uint8_t> VarMap::get_req_bin(const std::string& key) const {
163,711✔
1013
   const auto var = get_req_str(key);
163,711✔
1014

1015
   try {
163,711✔
1016
      if(var.starts_with("0x")) {
163,711✔
1017
         if(var.size() % 2 == 0) {
×
1018
            return Botan::hex_decode(var.substr(2));
×
1019
         } else {
1020
            std::string z = var;
×
1021
            std::swap(z[0], z[1]);  // swap 0x to x0 then remove x
×
1022
            return Botan::hex_decode(z.substr(1));
×
1023
         }
×
1024
      } else {
1025
         return Botan::hex_decode(var);
163,711✔
1026
      }
1027
   } catch(std::exception& e) {
×
1028
      std::ostringstream oss;
×
1029
      oss << "Bad input '" << var << "'"
×
1030
          << " for key " << key << " - " << e.what();
×
1031
      throw Test_Error(oss.str());
×
1032
   }
×
1033
}
163,711✔
1034

1035
std::string VarMap::get_opt_str(const std::string& key, const std::string& def_value) const {
14,378✔
1036
   if(auto v = get_var(key)) {
14,378✔
1037
      return *v;
57✔
1038
   } else {
1039
      return def_value;
28,699✔
1040
   }
14,378✔
1041
}
1042

1043
bool VarMap::get_req_bool(const std::string& key) const {
39✔
1044
   const auto var = get_req_str(key);
39✔
1045

1046
   if(var == "true") {
39✔
1047
      return true;
1048
   } else if(var == "false") {
23✔
1049
      return false;
1050
   } else {
1051
      throw Test_Error("Invalid boolean for key '" + key + "' value '" + var + "'");
×
1052
   }
1053
}
39✔
1054

1055
size_t VarMap::get_req_sz(const std::string& key) const {
4,547✔
1056
   return Botan::to_u32bit(get_req_str(key));
4,547✔
1057
}
1058

1059
uint8_t VarMap::get_req_u8(const std::string& key) const {
17✔
1060
   const size_t s = this->get_req_sz(key);
17✔
1061
   if(s > 256) {
17✔
1062
      throw Test_Error("Invalid " + key + " expected uint8_t got " + std::to_string(s));
×
1063
   }
1064
   return static_cast<uint8_t>(s);
17✔
1065
}
1066

1067
uint32_t VarMap::get_req_u32(const std::string& key) const {
14✔
1068
   return static_cast<uint32_t>(get_req_sz(key));
14✔
1069
}
1070

1071
uint64_t VarMap::get_req_u64(const std::string& key) const {
17✔
1072
   const auto var = get_req_str(key);
17✔
1073
   try {
17✔
1074
      return std::stoull(var);
17✔
1075
   } catch(std::exception&) {
×
1076
      throw Test_Error("Invalid u64 value '" + var + "'");
×
1077
   }
×
1078
}
17✔
1079

1080
size_t VarMap::get_opt_sz(const std::string& key, const size_t def_value) const {
31,379✔
1081
   if(auto v = get_var(key)) {
31,379✔
1082
      return Botan::to_u32bit(*v);
12,244✔
1083
   } else {
1084
      return def_value;
1085
   }
31,379✔
1086
}
1087

1088
uint64_t VarMap::get_opt_u64(const std::string& key, const uint64_t def_value) const {
3,538✔
1089
   if(auto v = get_var(key)) {
3,538✔
1090
      try {
641✔
1091
         return std::stoull(*v);
3,538✔
1092
      } catch(std::exception&) {
×
1093
         throw Test_Error("Invalid u64 value '" + *v + "'");
×
1094
      }
×
1095
   } else {
1096
      return def_value;
1097
   }
3,538✔
1098
}
×
1099

1100
std::vector<uint8_t> VarMap::get_opt_bin(const std::string& key) const {
45,868✔
1101
   if(auto v = get_var(key)) {
45,868✔
1102
      try {
16,134✔
1103
         return Botan::hex_decode(*v);
16,134✔
1104
      } catch(std::exception&) {
×
1105
         throw Test_Error("Test invalid hex input '" + *v + "'" + +" for key " + key);
×
1106
      }
×
1107
   } else {
1108
      return {};
29,734✔
1109
   };
45,868✔
1110
}
×
1111

1112
#if defined(BOTAN_HAS_BIGINT)
1113
Botan::BigInt VarMap::get_req_bn(const std::string& key) const {
38,502✔
1114
   const auto var = get_req_str(key);
38,502✔
1115

1116
   try {
38,502✔
1117
      return Botan::BigInt(var);
38,502✔
1118
   } catch(std::exception&) {
×
1119
      throw Test_Error("Test invalid bigint input '" + var + "' for key " + key);
×
1120
   }
×
1121
}
38,502✔
1122

1123
Botan::BigInt VarMap::get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const {
80✔
1124
   if(auto v = get_var(key)) {
80✔
1125
      try {
56✔
1126
         return Botan::BigInt(*v);
56✔
1127
      } catch(std::exception&) {
×
1128
         throw Test_Error("Test invalid bigint input '" + *v + "' for key " + key);
×
1129
      }
×
1130
   } else {
1131
      return def_value;
24✔
1132
   }
80✔
1133
}
×
1134
#endif
1135

1136
class Text_Based_Test::Text_Based_Test_Data {
1137
   public:
1138
      Text_Based_Test_Data(const std::string& data_src,
181✔
1139
                           const std::string& required_keys_str,
1140
                           const std::string& optional_keys_str) :
181✔
1141
            m_data_src(data_src) {
362✔
1142
         if(required_keys_str.empty()) {
181✔
1143
            throw Test_Error("Invalid test spec");
×
1144
         }
1145

1146
         m_required_keys = Botan::split_on(required_keys_str, ',');
181✔
1147
         std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
181✔
1148

1149
         m_all_keys.insert(m_required_keys.begin(), m_required_keys.end());
181✔
1150
         m_all_keys.insert(optional_keys.begin(), optional_keys.end());
181✔
1151
         m_output_key = m_required_keys.at(m_required_keys.size() - 1);
181✔
1152
      }
181✔
1153

1154
      std::string get_next_line();
1155

1156
      const std::string& current_source_name() const { return m_cur_src_name; }
×
1157

1158
      bool known_key(const std::string& key) const;
1159

1160
      const std::vector<std::string>& required_keys() const { return m_required_keys; }
48,388✔
1161

1162
      const std::string& output_key() const { return m_output_key; }
156,235✔
1163

1164
      const std::vector<std::string>& cpu_flags() const { return m_cpu_flags; }
48,249✔
1165

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

1168
      const std::string& initial_data_src_name() const { return m_data_src; }
181✔
1169

1170
   private:
1171
      std::string m_data_src;
1172
      std::vector<std::string> m_required_keys;
1173
      std::unordered_set<std::string> m_all_keys;
1174
      std::string m_output_key;
1175

1176
      bool m_first = true;
1177
      std::unique_ptr<std::istream> m_cur;
1178
      std::string m_cur_src_name;
1179
      std::deque<std::string> m_srcs;
1180
      std::vector<std::string> m_cpu_flags;
1181
};
1182

1183
Text_Based_Test::Text_Based_Test(const std::string& data_src,
181✔
1184
                                 const std::string& required_keys,
1185
                                 const std::string& optional_keys) :
181✔
1186
      m_data(std::make_unique<Text_Based_Test_Data>(data_src, required_keys, optional_keys)) {}
181✔
1187

1188
Text_Based_Test::~Text_Based_Test() = default;
181✔
1189

1190
std::string Text_Based_Test::Text_Based_Test_Data::get_next_line() {
157,242✔
1191
   while(true) {
157,500✔
1192
      if(m_cur == nullptr || m_cur->good() == false) {
157,500✔
1193
         if(m_srcs.empty()) {
450✔
1194
            if(m_first) {
362✔
1195
               if(m_data_src.ends_with(".vec")) {
181✔
1196
                  m_srcs.push_back(Test::data_file(m_data_src));
338✔
1197
               } else {
1198
                  const auto fs = Test::files_in_data_dir(m_data_src);
12✔
1199
                  m_srcs.assign(fs.begin(), fs.end());
12✔
1200
                  if(m_srcs.empty()) {
12✔
1201
                     throw Test_Error("Error reading test data dir " + m_data_src);
×
1202
                  }
1203
               }
12✔
1204

1205
               m_first = false;
181✔
1206
            } else {
1207
               return "";  // done
181✔
1208
            }
1209
         }
1210

1211
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
357✔
1212
         m_cur_src_name = m_srcs[0];
269✔
1213

1214
#if defined(BOTAN_HAS_CPUID)
1215
         // Reinit cpuid on new file if needed
1216
         if(m_cpu_flags.empty() == false) {
269✔
1217
            m_cpu_flags.clear();
19✔
1218
            Botan::CPUID::initialize();
19✔
1219
         }
1220
#endif
1221

1222
         if(!m_cur->good()) {
269✔
1223
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
1224
         }
1225

1226
         m_srcs.pop_front();
269✔
1227
      }
1228

1229
      while(m_cur->good()) {
227,897✔
1230
         std::string line;
227,639✔
1231
         std::getline(*m_cur, line);
227,639✔
1232

1233
         if(line.empty()) {
227,639✔
1234
            continue;
55,310✔
1235
         }
1236

1237
         if(line[0] == '#') {
172,329✔
1238
            if(line.starts_with("#test ")) {
15,289✔
1239
               return line;
21✔
1240
            } else {
1241
               continue;
15,268✔
1242
            }
1243
         }
1244

1245
         return line;
157,040✔
1246
      }
227,639✔
1247
   }
1248
}
1249

1250
bool Text_Based_Test::Text_Based_Test_Data::known_key(const std::string& key) const {
156,235✔
1251
   return m_all_keys.contains(key);
156,235✔
1252
}
1253

1254
namespace {
1255

1256
// strips leading and trailing but not internal whitespace
1257
std::string strip_ws(const std::string& in) {
312,470✔
1258
   const char* whitespace = " ";
312,470✔
1259

1260
   const auto first_c = in.find_first_not_of(whitespace);
312,470✔
1261
   if(first_c == std::string::npos) {
312,470✔
1262
      return "";
1,033✔
1263
   }
1264

1265
   const auto last_c = in.find_last_not_of(whitespace);
311,437✔
1266

1267
   return in.substr(first_c, last_c - first_c + 1);
311,437✔
1268
}
1269

1270
std::vector<std::string> parse_cpuid_bits(const std::vector<std::string>& tok) {
21✔
1271
   std::vector<std::string> bits;
21✔
1272

1273
#if defined(BOTAN_HAS_CPUID)
1274
   for(size_t i = 1; i < tok.size(); ++i) {
106✔
1275
      if(auto bit = Botan::CPUID::bit_from_string(tok[i])) {
85✔
1276
         bits.push_back(bit->to_string());
98✔
1277
      }
1278
   }
1279
#else
1280
   BOTAN_UNUSED(tok);
1281
#endif
1282

1283
   return bits;
21✔
1284
}
×
1285

1286
}  // namespace
1287

1288
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) {
32,609✔
1289
   return false;
32,609✔
1290
}
1291

1292
std::vector<Test::Result> Text_Based_Test::run() {
181✔
1293
   std::vector<Test::Result> results;
181✔
1294

1295
   std::string header;
181✔
1296
   std::string header_or_name = m_data->initial_data_src_name();
181✔
1297
   VarMap vars;
181✔
1298
   size_t test_cnt = 0;
181✔
1299

1300
   while(true) {
157,242✔
1301
      const std::string line = m_data->get_next_line();
157,242✔
1302
      if(line.empty()) {
157,242✔
1303
         // EOF
1304
         break;
1305
      }
1306

1307
      if(line.starts_with("#test ")) {
157,061✔
1308
         std::vector<std::string> pragma_tokens = Botan::split_on(line.substr(6), ' ');
21✔
1309

1310
         if(pragma_tokens.empty()) {
21✔
1311
            throw Test_Error("Empty pragma found in " + m_data->current_source_name());
×
1312
         }
1313

1314
         if(pragma_tokens[0] != "cpuid") {
21✔
1315
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1316
         }
1317

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

1322
         m_data->set_cpu_flags(parse_cpuid_bits(pragma_tokens));
42✔
1323

1324
         continue;
21✔
1325
      } else if(line[0] == '#') {
157,061✔
1326
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1327
      }
1328

1329
      if(line[0] == '[' && line[line.size() - 1] == ']') {
157,040✔
1330
         header = line.substr(1, line.size() - 2);
805✔
1331
         header_or_name = header;
805✔
1332
         test_cnt = 0;
805✔
1333
         vars.clear();
805✔
1334
         continue;
805✔
1335
      }
1336

1337
      const std::string test_id = "test " + std::to_string(test_cnt);
312,470✔
1338

1339
      auto equal_i = line.find_first_of('=');
156,235✔
1340

1341
      if(equal_i == std::string::npos) {
156,235✔
1342
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1343
         continue;
×
1344
      }
1345

1346
      const std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
312,470✔
1347
      const std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
312,470✔
1348

1349
      if(!m_data->known_key(key)) {
156,235✔
1350
         auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key));
×
1351
         results.push_back(r);
×
1352
      }
×
1353

1354
      vars.add(key, val);
156,235✔
1355

1356
      if(key == m_data->output_key()) {
156,235✔
1357
         try {
48,388✔
1358
            for(const auto& req_key : m_data->required_keys()) {
245,554✔
1359
               if(!vars.has_key(req_key)) {
197,166✔
1360
                  auto r =
×
1361
                     Test::Result::Failure(header_or_name, Botan::fmt("{} missing required key {}", test_id, req_key));
×
1362
                  results.push_back(r);
×
1363
               }
×
1364
            }
1365

1366
            if(skip_this_test(header, vars)) {
48,388✔
1367
               continue;
139✔
1368
            }
1369

1370
            ++test_cnt;
48,249✔
1371

1372
            const uint64_t start = Test::timestamp();
48,249✔
1373

1374
            Test::Result result = run_one_test(header, vars);
48,249✔
1375
#if defined(BOTAN_HAS_CPUID)
1376
            if(!m_data->cpu_flags().empty()) {
48,249✔
1377
               for(const auto& cpuid_str : m_data->cpu_flags()) {
30,621✔
1378
                  if(const auto bit = Botan::CPUID::Feature::from_string(cpuid_str)) {
21,677✔
1379
                     if(Botan::CPUID::has(*bit)) {
21,677✔
1380
                        Botan::CPUID::clear_cpuid_bit(*bit);
16,577✔
1381
                        // now re-run the test
1382
                        result.merge(run_one_test(header, vars));
16,577✔
1383
                     }
1384
                  }
1385
               }
1386
               Botan::CPUID::initialize();
8,944✔
1387
            }
1388
#endif
1389
            result.set_ns_consumed(Test::timestamp() - start);
48,249✔
1390

1391
            if(result.tests_failed() > 0) {
48,249✔
1392
               std::ostringstream oss;
×
1393
               oss << "Test # " << test_cnt << " ";
×
1394
               if(!header.empty()) {
×
1395
                  oss << header << " ";
×
1396
               }
1397
               oss << "failed ";
×
1398

1399
               for(const auto& k : m_data->required_keys()) {
×
1400
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1401
               }
1402

1403
               result.test_note(oss.str());
×
1404
            }
×
1405
            results.push_back(result);
48,249✔
1406
         } catch(std::exception& e) {
48,249✔
1407
            std::ostringstream oss;
×
1408
            oss << "Test # " << test_cnt << " ";
×
1409
            if(!header.empty()) {
×
1410
               oss << header << " ";
×
1411
            }
1412

1413
            for(const auto& k : m_data->required_keys()) {
×
1414
               oss << k << "=" << vars.get_req_str(k) << " ";
×
1415
            }
1416

1417
            oss << "failed with exception '" << e.what() << "'";
×
1418

1419
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1420
         }
×
1421

1422
         if(clear_between_callbacks()) {
48,249✔
1423
            vars.clear();
189,572✔
1424
         }
1425
      }
1426
   }
157,339✔
1427

1428
   if(results.empty()) {
181✔
1429
      return results;
1430
   }
1431

1432
   try {
181✔
1433
      std::vector<Test::Result> final_tests = run_final_tests();
181✔
1434
      results.insert(results.end(), final_tests.begin(), final_tests.end());
181✔
1435
   } catch(std::exception& e) {
181✔
1436
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1437
   }
×
1438

1439
   return results;
1440
}
181✔
1441

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