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

randombit / botan / 21753596263

06 Feb 2026 02:13PM UTC coverage: 90.063% (-0.01%) from 90.073%
21753596263

Pull #5289

github

web-flow
Merge 587099284 into 8ea0ca252
Pull Request #5289: Further misc header reductions, forward declarations, etc

102237 of 113517 relevant lines covered (90.06%)

11402137.11 hits per line

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

79.39
/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/internal/filesystem.h>
12
#include <botan/internal/fmt.h>
13
#include <botan/internal/loadstor.h>
14
#include <botan/internal/parsing.h>
15
#include <botan/internal/stl_util.h>
16
#include <botan/internal/target_info.h>
17
#include <chrono>
18
#include <deque>
19
#include <fstream>
20
#include <iomanip>
21
#include <set>
22
#include <sstream>
23
#include <unordered_set>
24

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

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

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

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

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

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

53
namespace Botan_Tests {
54

55
Test::Test() = default;
419✔
56

57
Test::~Test() = default;
564✔
58

59
Test::Result::Result(std::string who) : m_who(std::move(who)), m_timestamp(Test::timestamp()) {}
81,126✔
60

61
void Test::Result::merge(const Result& other, bool ignore_test_name) {
126,761✔
62
   if(who() != other.who()) {
126,761✔
63
      if(!ignore_test_name) {
73✔
64
         throw Test_Error("Merging tests from different sources");
×
65
      }
66

67
      // When deliberately merging results with different names, the code location is
68
      // likely inconsistent and must be discarded.
69
      m_where.reset();
73✔
70
   } else {
71
      m_where = other.m_where;
126,688✔
72
   }
73

74
   m_timestamp = std::min(m_timestamp, other.m_timestamp);
126,761✔
75
   m_ns_taken += other.m_ns_taken;
126,761✔
76
   m_tests_passed += other.m_tests_passed;
126,761✔
77
   m_fail_log.insert(m_fail_log.end(), other.m_fail_log.begin(), other.m_fail_log.end());
126,761✔
78
   m_log.insert(m_log.end(), other.m_log.begin(), other.m_log.end());
126,761✔
79
}
126,761✔
80

81
void Test::Result::start_timer() {
1,192✔
82
   if(m_started == 0) {
1,192✔
83
      m_started = Test::timestamp();
2,384✔
84
   }
85
}
1,192✔
86

87
void Test::Result::end_timer() {
1,304✔
88
   if(m_started > 0) {
1,304✔
89
      m_ns_taken += Test::timestamp() - m_started;
2,382✔
90
      m_started = 0;
1,191✔
91
   }
92
}
1,304✔
93

94
void Test::Result::test_note(const std::string& who, std::span<const uint8_t> data) {
12✔
95
   const std::string hex = Botan::hex_encode(data);
12✔
96
   return test_note(who, hex.c_str());
12✔
97
}
12✔
98

99
void Test::Result::test_note(const std::string& note, const char* extra) {
2,767✔
100
   if(!note.empty()) {
2,767✔
101
      std::ostringstream out;
2,767✔
102
      out << who() << " " << note;
2,767✔
103
      if(extra != nullptr) {
2,767✔
104
         out << ": " << extra;
12✔
105
      }
106
      m_log.push_back(out.str());
2,767✔
107
   }
2,767✔
108
}
2,767✔
109

110
void Test::Result::note_missing(const std::string& whatever) {
275✔
111
   static std::set<std::string> s_already_seen;
275✔
112

113
   if(!s_already_seen.contains(whatever)) {
275✔
114
      test_note("Skipping tests due to missing " + whatever);
5✔
115
      s_already_seen.insert(whatever);
5✔
116
   }
117
}
275✔
118

119
bool Test::Result::ThrowExpectations::check(const std::string& test_name, Test::Result& result) {
67,786✔
120
   m_consumed = true;
67,786✔
121

122
   try {
67,786✔
123
      m_fn();
67,786✔
124
      if(!m_expect_success) {
1,646✔
125
         return result.test_failure(test_name + " failed to throw expected exception");
2✔
126
      }
127
   } catch(const std::exception& ex) {
66,140✔
128
      if(m_expect_success) {
66,138✔
129
         return result.test_failure(test_name + " threw unexpected exception: " + ex.what());
2✔
130
      }
131
      if(m_expected_exception_check_fn && !m_expected_exception_check_fn(std::current_exception())) {
190,233✔
132
         return result.test_failure(test_name + " threw unexpected exception: " + ex.what());
4✔
133
      }
134
      if(m_expected_message.has_value() && m_expected_message.value() != ex.what()) {
66,135✔
135
         return result.test_failure(test_name + " threw exception with unexpected message (expected: '" +
3✔
136
                                    m_expected_message.value() + "', got: '" + ex.what() + "')");
6✔
137
      }
138
   } catch(...) {
66,140✔
139
      if(m_expect_success || m_expected_exception_check_fn || m_expected_message.has_value()) {
2✔
140
         return result.test_failure(test_name + " threw unexpected unknown exception");
1✔
141
      }
142
   }
2✔
143

144
   return result.test_success(test_name + " behaved as expected");
135,558✔
145
}
146

147
bool Test::Result::test_throws(const std::string& what, const std::function<void()>& fn) {
3,919✔
148
   return ThrowExpectations(fn).check(what, *this);
7,838✔
149
}
150

151
bool Test::Result::test_throws(const std::string& what, const std::string& expected, const std::function<void()>& fn) {
174✔
152
   return ThrowExpectations(fn).expect_message(expected).check(what, *this);
348✔
153
}
154

155
bool Test::Result::test_no_throw(const std::string& what, const std::function<void()>& fn) {
1,645✔
156
   return ThrowExpectations(fn).expect_success().check(what, *this);
3,290✔
157
}
158

159
bool Test::Result::test_success(const std::string& note) {
3,620,213✔
160
   if(Test::options().log_success()) {
3,620,081✔
161
      test_note(note);
×
162
   }
163
   ++m_tests_passed;
3,620,213✔
164
   return true;
775,649✔
165
}
166

167
bool Test::Result::test_failure(const std::string& what, const std::string& error) {
1✔
168
   return test_failure(who() + " " + what + " with error " + error);
4✔
169
}
170

171
void Test::Result::test_failure(const std::string& what, const uint8_t buf[], size_t buf_len) {
1✔
172
   test_failure(who() + ": " + what + " buf len " + std::to_string(buf_len) + " value " +
5✔
173
                Botan::hex_encode(buf, buf_len));
1✔
174
}
1✔
175

176
bool Test::Result::test_failure(const std::string& err) {
25✔
177
   m_fail_log.push_back(err);
25✔
178

179
   if(Test::options().abort_on_first_fail() && m_who != "Failing Test") {
25✔
180
      std::abort();
×
181
   }
182
   return false;
25✔
183
}
184

185
namespace {
186

187
bool same_contents(const uint8_t x[], const uint8_t y[], size_t len) {
292,308✔
188
   return (len == 0) ? true : std::memcmp(x, y, len) == 0;
290,877✔
189
}
190

191
}  // namespace
192

193
bool Test::Result::test_ne(const std::string& what,
3,406✔
194
                           const uint8_t produced[],
195
                           size_t produced_len,
196
                           const uint8_t expected[],
197
                           size_t expected_len) {
198
   if(produced_len == expected_len && same_contents(produced, expected, expected_len)) {
3,406✔
199
      return test_failure(who() + ": " + what + " produced matching");
6✔
200
   }
201
   return test_success();
6,808✔
202
}
203

204
bool Test::Result::test_eq(const std::string& what, std::span<const uint8_t> produced, const char* expected_hex) {
453✔
205
   const std::vector<uint8_t> expected = Botan::hex_decode(expected_hex);
453✔
206
   return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
453✔
207
}
453✔
208

209
bool Test::Result::test_eq(const char* producer,
290,856✔
210
                           const std::string& what,
211
                           const uint8_t produced[],
212
                           size_t produced_size,
213
                           const uint8_t expected[],
214
                           size_t expected_size) {
215
   if(produced_size == expected_size && same_contents(produced, expected, expected_size)) {
290,856✔
216
      return test_success();
581,710✔
217
   }
218

219
   std::ostringstream err;
1✔
220

221
   err << who();
1✔
222

223
   if(producer != nullptr) {
1✔
224
      err << " producer '" << producer << "'";
×
225
   }
226

227
   err << " unexpected result for " << what;
1✔
228

229
   if(produced_size != expected_size) {
1✔
230
      err << " produced " << produced_size << " bytes expected " << expected_size;
1✔
231
   }
232

233
   std::vector<uint8_t> xor_diff(std::min(produced_size, expected_size));
2✔
234
   size_t bytes_different = 0;
1✔
235

236
   for(size_t i = 0; i != xor_diff.size(); ++i) {
4✔
237
      xor_diff[i] = produced[i] ^ expected[i];
3✔
238
      if(xor_diff[i] > 0) {
3✔
239
         bytes_different++;
3✔
240
      }
241
   }
242

243
   err << "\nProduced: " << Botan::hex_encode(produced, produced_size)
1✔
244
       << "\nExpected: " << Botan::hex_encode(expected, expected_size);
3✔
245

246
   if(bytes_different > 0) {
1✔
247
      err << "\nXOR Diff: " << Botan::hex_encode(xor_diff);
1✔
248
   }
249

250
   return test_failure(err.str());
1✔
251
}
1✔
252

253
bool Test::Result::test_is_nonempty(const std::string& what_is_it, const std::string& to_examine) {
38,829✔
254
   if(to_examine.empty()) {
38,829✔
255
      return test_failure(what_is_it + " was empty");
1✔
256
   }
257
   return test_success();
77,656✔
258
}
259

260
bool Test::Result::test_eq(const std::string& what, const std::string& produced, const std::string& expected) {
76,783✔
261
   return test_is_eq(what, produced, expected);
76,783✔
262
}
263

264
bool Test::Result::test_eq(const std::string& what, const char* produced, const char* expected) {
29✔
265
   return test_is_eq(what, std::string(produced), std::string(expected));
29✔
266
}
267

268
bool Test::Result::test_eq(const std::string& what, size_t produced, size_t expected) {
146,717✔
269
   return test_is_eq(what, produced, expected);
146,717✔
270
}
271

272
bool Test::Result::test_eq_sz(const std::string& what, size_t produced, size_t expected) {
45,789✔
273
   return test_is_eq(what, produced, expected);
45,789✔
274
}
275

276
bool Test::Result::test_eq(const std::string& what,
107✔
277
                           const Botan::OctetString& produced,
278
                           const Botan::OctetString& expected) {
279
   std::ostringstream out;
107✔
280
   out << m_who << " " << what;
107✔
281

282
   if(produced == expected) {
107✔
283
      out << " produced expected result " << produced.to_string();
214✔
284
      return test_success(out.str());
107✔
285
   } else {
286
      out << " produced unexpected result '" << produced.to_string() << "' expected '" << expected.to_string() << "'";
×
287
      return test_failure(out.str());
×
288
   }
289
}
107✔
290

291
bool Test::Result::test_lt(const std::string& what, size_t produced, size_t expected) {
5,639✔
292
   if(produced >= expected) {
5,639✔
293
      std::ostringstream err;
1✔
294
      err << m_who << " " << what;
1✔
295
      err << " unexpected result " << produced << " >= " << expected;
1✔
296
      return test_failure(err.str());
1✔
297
   }
1✔
298

299
   return test_success();
11,276✔
300
}
301

302
bool Test::Result::test_lte(const std::string& what, size_t produced, size_t expected) {
1,021,636✔
303
   if(produced > expected) {
1,021,636✔
304
      std::ostringstream err;
1✔
305
      err << m_who << " " << what << " unexpected result " << produced << " > " << expected;
1✔
306
      return test_failure(err.str());
1✔
307
   }
1✔
308

309
   return test_success();
2,043,270✔
310
}
311

312
bool Test::Result::test_gte(const std::string& what, size_t produced, size_t expected) {
1,142,430✔
313
   if(produced < expected) {
1,142,430✔
314
      std::ostringstream err;
1✔
315
      err << m_who;
1✔
316
      err << " " << what;
1✔
317
      err << " unexpected result " << produced << " < " << expected;
1✔
318
      return test_failure(err.str());
1✔
319
   }
1✔
320

321
   return test_success();
2,284,858✔
322
}
323

324
bool Test::Result::test_gt(const std::string& what, size_t produced, size_t expected) {
22,373✔
325
   if(produced <= expected) {
22,373✔
326
      std::ostringstream err;
×
327
      err << m_who;
×
328
      err << " " << what;
×
329
      err << " unexpected result " << produced << " <= " << expected;
×
330
      return test_failure(err.str());
×
331
   }
×
332

333
   return test_success();
44,746✔
334
}
335

336
bool Test::Result::test_ne(const std::string& what, const std::string& str1, const std::string& str2) {
26✔
337
   if(str1 != str2) {
26✔
338
      return test_success(str1 + " != " + str2);
50✔
339
   }
340

341
   return test_failure(who() + " " + what + " produced matching strings " + str1);
4✔
342
}
343

344
bool Test::Result::test_ne(const std::string& what, size_t produced, size_t expected) {
119✔
345
   if(produced != expected) {
119✔
346
      return test_success();
236✔
347
   }
348

349
   std::ostringstream err;
1✔
350
   err << who() << " " << what << " produced " << produced << " unexpected value";
1✔
351
   return test_failure(err.str());
1✔
352
}
1✔
353

354
#if defined(BOTAN_HAS_BIGINT)
355
bool Test::Result::test_eq(const std::string& what, const BigInt& produced, const BigInt& expected) {
252,629✔
356
   return test_is_eq(what, produced, expected);
252,629✔
357
}
358

359
bool Test::Result::test_ne(const std::string& what, const BigInt& produced, const BigInt& expected) {
97✔
360
   if(produced != expected) {
97✔
361
      return test_success();
192✔
362
   }
363

364
   std::ostringstream err;
1✔
365
   err << who() << " " << what << " produced " << produced << " prohibited value";
1✔
366
   return test_failure(err.str());
1✔
367
}
1✔
368
#endif
369

370
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
371
bool Test::Result::test_eq(const std::string& what, const Botan::EC_Point& a, const Botan::EC_Point& b) {
3,248✔
372
   //return test_is_eq(what, a, b);
373
   if(a == b) {
3,248✔
374
      return test_success();
6,496✔
375
   }
376

377
   std::ostringstream err;
×
378
   err << who() << " " << what << " a=(" << a.get_affine_x() << "," << a.get_affine_y() << ")"
×
379
       << " b=(" << b.get_affine_x() << "," << b.get_affine_y();
×
380
   return test_failure(err.str());
×
381
}
×
382
#endif
383

384
bool Test::Result::test_eq(const std::string& what, bool produced, bool expected) {
378,430✔
385
   return test_is_eq(what, produced, expected);
378,430✔
386
}
387

388
bool Test::Result::test_rc_init(const std::string& func, int rc) {
117✔
389
   if(rc == 0) {
117✔
390
      return test_success();
234✔
391
   } else {
392
      std::ostringstream msg;
×
393
      msg << m_who;
×
394
      msg << " " << func;
×
395

396
      // -40 is BOTAN_FFI_ERROR_NOT_IMPLEMENTED
397
      if(rc == -40) {
×
398
         msg << " returned not implemented";
×
399
      } else {
400
         msg << " unexpectedly failed with error code " << rc;
×
401
      }
402

403
      if(rc == -40) {
×
404
         this->test_note(msg.str());
×
405
      } else {
406
         this->test_failure(msg.str());
×
407
      }
408
      return false;
×
409
   }
×
410
}
411

412
bool Test::Result::test_rc(const std::string& func, int expected, int rc) {
416✔
413
   if(expected != rc) {
416✔
414
      std::ostringstream err;
1✔
415
      err << m_who;
1✔
416
      err << " call to " << func << " unexpectedly returned " << rc;
1✔
417
      err << " but expecting " << expected;
1✔
418
      return test_failure(err.str());
1✔
419
   }
1✔
420

421
   return test_success();
830✔
422
}
423

424
void Test::initialize(std::string test_name, CodeLocation location) {
419✔
425
   m_test_name = std::move(test_name);
419✔
426
   m_registration_location = location;
419✔
427
}
419✔
428

429
Botan::RandomNumberGenerator& Test::rng() const {
461,902✔
430
   if(!m_test_rng) {
461,902✔
431
      m_test_rng = Test::new_rng(m_test_name);
145✔
432
   }
433

434
   return *m_test_rng;
461,902✔
435
}
436

437
std::optional<std::string> Test::supported_ec_group_name(std::vector<std::string> preferred_groups) {
151✔
438
#if defined(BOTAN_HAS_ECC_GROUP)
439
   if(preferred_groups.empty()) {
151✔
440
      preferred_groups = {
149✔
441
         "secp256r1",
442
         "brainpool256r1",
443
         "secp384r1",
444
         "brainpool384r1",
445
         "secp521r1",
446
         "brainpool512r1",
447
      };
1,192✔
448
   }
449

450
   for(const auto& group : preferred_groups) {
151✔
451
      if(Botan::EC_Group::supports_named_group(group)) {
151✔
452
         return group;
151✔
453
      }
454
   }
455
#else
456
   BOTAN_UNUSED(preferred_groups);
457
#endif
458

459
   return std::nullopt;
×
460
}
298✔
461

462
std::vector<uint8_t> Test::mutate_vec(const std::vector<uint8_t>& v,
96,742✔
463
                                      Botan::RandomNumberGenerator& rng,
464
                                      bool maybe_resize,
465
                                      size_t min_offset) {
466
   std::vector<uint8_t> r = v;
96,742✔
467

468
   if(maybe_resize && (r.empty() || rng.next_byte() < 32)) {
110,316✔
469
      // TODO: occasionally truncate, insert at random index
470
      const size_t add = 1 + (rng.next_byte() % 16);
2,145✔
471
      r.resize(r.size() + add);
2,145✔
472
      rng.randomize(&r[r.size() - add], add);
2,145✔
473
   }
474

475
   if(r.size() > min_offset) {
96,742✔
476
      const size_t offset = std::max<size_t>(min_offset, rng.next_byte() % r.size());
95,204✔
477
      const uint8_t perturb = rng.next_nonzero_byte();
95,204✔
478
      r[offset] ^= perturb;
95,204✔
479
   }
480

481
   return r;
96,742✔
482
}
×
483

484
std::vector<std::string> Test::possible_providers(const std::string& /*alg*/) {
×
485
   return Test::provider_filter({"base"});
×
486
}
487

488
//static
489
std::string Test::format_time(uint64_t nanoseconds) {
1,470✔
490
   std::ostringstream o;
1,470✔
491

492
   if(nanoseconds > 1000000000) {
1,470✔
493
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000000.0 << " sec";
153✔
494
   } else {
495
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000.0 << " msec";
1,317✔
496
   }
497

498
   return o.str();
2,940✔
499
}
1,470✔
500

501
Test::Result::Result(std::string who, const std::vector<Result>& downstream_results) : Result(std::move(who)) {
14✔
502
   for(const auto& result : downstream_results) {
82✔
503
      merge(result, true /* ignore non-matching test names */);
68✔
504
   }
505
}
14✔
506

507
// TODO: this should move to `StdoutReporter`
508
std::string Test::Result::result_string() const {
2,541✔
509
   const bool verbose = Test::options().verbose();
2,541✔
510

511
   if(tests_run() == 0 && !verbose) {
2,541✔
512
      return "";
21✔
513
   }
514

515
   std::ostringstream report;
2,520✔
516

517
   report << who() << " ran ";
2,520✔
518

519
   if(tests_run() == 0) {
2,520✔
520
      report << "ZERO";
×
521
   } else {
522
      report << tests_run();
2,520✔
523
   }
524
   report << " tests";
2,520✔
525

526
   if(m_ns_taken > 0) {
2,520✔
527
      report << " in " << format_time(m_ns_taken);
2,938✔
528
   }
529

530
   if(tests_failed() > 0) {
2,520✔
531
      report << " " << tests_failed() << " FAILED";
25✔
532
   } else {
533
      report << " all ok";
2,495✔
534
   }
535

536
   report << "\n";
2,520✔
537

538
   for(size_t i = 0; i != m_fail_log.size(); ++i) {
2,545✔
539
      report << "Failure " << (i + 1) << ": " << m_fail_log[i];
25✔
540
      if(m_where) {
25✔
541
         report << " (at " << m_where->path << ":" << m_where->line << ")";
×
542
      }
543
      report << "\n";
25✔
544
   }
545

546
   if(!m_fail_log.empty() || tests_run() == 0 || verbose) {
2,520✔
547
      for(size_t i = 0; i != m_log.size(); ++i) {
25✔
548
         report << "Note " << (i + 1) << ": " << m_log[i] << "\n";
×
549
      }
550
   }
551

552
   return report.str();
2,520✔
553
}
2,520✔
554

555
namespace {
556

557
class Test_Registry {
558
   public:
559
      static Test_Registry& instance() {
1,279✔
560
         static Test_Registry registry;
1,280✔
561
         return registry;
1,279✔
562
      }
563

564
      void register_test(const std::string& category,
419✔
565
                         const std::string& name,
566
                         bool smoke_test,
567
                         bool needs_serialization,
568
                         std::function<std::unique_ptr<Test>()> maker_fn) {
569
         if(m_tests.contains(name)) {
419✔
570
            throw Test_Error("Duplicate registration of test '" + name + "'");
×
571
         }
572

573
         if(m_tests.contains(category)) {
419✔
574
            throw Test_Error("'" + category + "' cannot be used as category, test exists");
×
575
         }
576

577
         if(m_categories.contains(name)) {
419✔
578
            throw Test_Error("'" + name + "' cannot be used as test name, category exists");
×
579
         }
580

581
         if(smoke_test) {
419✔
582
            m_smoke_tests.push_back(name);
10✔
583
         }
584

585
         if(needs_serialization) {
419✔
586
            m_mutexed_tests.push_back(name);
21✔
587
         }
588

589
         m_tests.emplace(name, std::move(maker_fn));
419✔
590
         m_categories.emplace(category, name);
419✔
591
      }
419✔
592

593
      std::unique_ptr<Test> get_test(const std::string& test_name) const {
419✔
594
         auto i = m_tests.find(test_name);
419✔
595
         if(i != m_tests.end()) {
419✔
596
            return i->second();
419✔
597
         }
598
         return nullptr;
×
599
      }
600

601
      std::vector<std::string> registered_tests() const {
×
602
         std::vector<std::string> s;
×
603
         s.reserve(m_tests.size());
×
604
         for(auto&& i : m_tests) {
×
605
            s.push_back(i.first);
×
606
         }
607
         return s;
×
608
      }
×
609

610
      std::vector<std::string> registered_test_categories() const {
×
611
         std::set<std::string> s;
×
612
         for(auto&& i : m_categories) {
×
613
            s.insert(i.first);
×
614
         }
615
         return std::vector<std::string>(s.begin(), s.end());
×
616
      }
×
617

618
      std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
1✔
619
                                                       const std::vector<std::string>& to_be_skipped) {
620
         std::vector<std::string> result;
1✔
621

622
         std::set<std::string> to_be_skipped_set(to_be_skipped.begin(), to_be_skipped.end());
1✔
623
         // TODO: this is O(n^2), but we have a relatively small number of tests.
624
         auto insert_if_not_exists_and_not_skipped = [&](const std::string& test_name) {
420✔
625
            if(!Botan::value_exists(result, test_name) && !to_be_skipped_set.contains(test_name)) {
838✔
626
               result.push_back(test_name);
409✔
627
            }
628
         };
420✔
629

630
         if(requested.empty()) {
1✔
631
            /*
632
            If nothing was requested on the command line, run everything. First
633
            run the "essentials" to smoke test, then everything else in
634
            alphabetical order.
635
            */
636
            result = m_smoke_tests;
1✔
637
            for(const auto& [test_name, _] : m_tests) {
420✔
638
               insert_if_not_exists_and_not_skipped(test_name);
419✔
639
            }
640
         } else {
641
            for(const auto& r : requested) {
×
642
               if(m_tests.contains(r)) {
×
643
                  insert_if_not_exists_and_not_skipped(r);
×
644
               } else if(auto elems = m_categories.equal_range(r); elems.first != m_categories.end()) {
×
645
                  for(; elems.first != elems.second; ++elems.first) {
×
646
                     insert_if_not_exists_and_not_skipped(elems.first->second);
×
647
                  }
648
               } else {
649
                  throw Test_Error("Unknown test suite or category: " + r);
×
650
               }
651
            }
652
         }
653

654
         return result;
1✔
655
      }
1✔
656

657
      bool needs_serialization(const std::string& test_name) const {
440✔
658
         return Botan::value_exists(m_mutexed_tests, test_name);
21✔
659
      }
660

661
   private:
662
      Test_Registry() = default;
1✔
663

664
   private:
665
      std::map<std::string, std::function<std::unique_ptr<Test>()>> m_tests;
666
      std::multimap<std::string, std::string> m_categories;
667
      std::vector<std::string> m_smoke_tests;
668
      std::vector<std::string> m_mutexed_tests;
669
};
670

671
}  // namespace
672

673
// static Test:: functions
674

675
//static
676
void Test::register_test(const std::string& category,
419✔
677
                         const std::string& name,
678
                         bool smoke_test,
679
                         bool needs_serialization,
680
                         std::function<std::unique_ptr<Test>()> maker_fn) {
681
   Test_Registry::instance().register_test(category, name, smoke_test, needs_serialization, std::move(maker_fn));
838✔
682
}
419✔
683

684
//static
685
uint64_t Test::timestamp() {
180,013✔
686
   auto now = std::chrono::system_clock::now().time_since_epoch();
180,013✔
687
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
2,383✔
688
}
689

690
//static
691
std::vector<Test::Result> Test::flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists) {
4✔
692
   std::vector<Test::Result> results;
4✔
693
   for(auto& result_list : result_lists) {
26✔
694
      for(auto& result : result_list) {
71✔
695
         results.emplace_back(std::move(result));
49✔
696
      }
697
   }
698
   return results;
4✔
699
}
×
700

701
//static
702
std::vector<std::string> Test::registered_tests() {
×
703
   return Test_Registry::instance().registered_tests();
×
704
}
705

706
//static
707
std::vector<std::string> Test::registered_test_categories() {
×
708
   return Test_Registry::instance().registered_test_categories();
×
709
}
710

711
//static
712
std::unique_ptr<Test> Test::get_test(const std::string& test_name) {
419✔
713
   return Test_Registry::instance().get_test(test_name);
419✔
714
}
715

716
//static
717
bool Test::test_needs_serialization(const std::string& test_name) {
419✔
718
   return Test_Registry::instance().needs_serialization(test_name);
419✔
719
}
720

721
//static
722
std::vector<std::string> Test::filter_registered_tests(const std::vector<std::string>& requested,
1✔
723
                                                       const std::vector<std::string>& to_be_skipped) {
724
   return Test_Registry::instance().filter_registered_tests(requested, to_be_skipped);
1✔
725
}
726

727
//static
728
std::string Test::temp_file_name(const std::string& basename) {
21✔
729
   // TODO add a --tmp-dir option to the tests to specify where these files go
730

731
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
732

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

736
   const int fd = ::mkstemp(mkstemp_basename.data());
21✔
737

738
   // error
739
   if(fd < 0) {
21✔
740
      return "";
×
741
   }
742

743
   ::close(fd);
21✔
744

745
   return mkstemp_basename;
21✔
746
#else
747
   // For now just create the temp in the current working directory
748
   return basename;
749
#endif
750
}
21✔
751

752
bool Test::copy_file(const std::string& from, const std::string& to) {
1✔
753
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(__cpp_lib_filesystem)
754
   std::error_code ec;  // don't throw, just return false on error
1✔
755
   return std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
1✔
756
#else
757
   // TODO: implement fallbacks to POSIX or WIN32
758
   // ... but then again: it's 2023 and we're using C++20 :o)
759
   BOTAN_UNUSED(from, to);
760
   throw Botan::No_Filesystem_Access();
761
#endif
762
}
763

764
std::string Test::read_data_file(const std::string& path) {
38✔
765
   const std::string fsname = Test::data_file(path);
38✔
766
   std::ifstream file(fsname.c_str());
38✔
767
   if(!file.good()) {
38✔
768
      throw Test_Error("Error reading from " + fsname);
×
769
   }
770

771
   return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
76✔
772
}
38✔
773

774
std::vector<uint8_t> Test::read_binary_data_file(const std::string& path) {
34✔
775
   const std::string fsname = Test::data_file(path);
34✔
776
   std::ifstream file(fsname.c_str(), std::ios::binary);
34✔
777
   if(!file.good()) {
34✔
778
      throw Test_Error("Error reading from " + fsname);
×
779
   }
780

781
   std::vector<uint8_t> contents;
34✔
782

783
   while(file.good()) {
74✔
784
      std::vector<uint8_t> buf(4096);
40✔
785
      file.read(reinterpret_cast<char*>(buf.data()), buf.size());
40✔
786
      const size_t got = static_cast<size_t>(file.gcount());
40✔
787

788
      if(got == 0 && file.eof()) {
40✔
789
         break;
790
      }
791

792
      contents.insert(contents.end(), buf.data(), buf.data() + got);
40✔
793
   }
40✔
794

795
   return contents;
68✔
796
}
34✔
797

798
// static member variables of Test
799

800
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
801
Test_Options Test::m_opts;
802
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
803
std::string Test::m_test_rng_seed;
804

805
//static
806
void Test::set_test_options(const Test_Options& opts) {
1✔
807
   m_opts = opts;
1✔
808
}
1✔
809

810
namespace {
811

812
/*
813
* This is a fast, simple, deterministic PRNG that's used for running
814
* the tests. It is not intended to be cryptographically secure.
815
*/
816
class Testsuite_RNG final : public Botan::RandomNumberGenerator {
8✔
817
   public:
818
      std::string name() const override { return "Testsuite_RNG"; }
×
819

820
      void clear() override { m_x = 0; }
×
821

822
      bool accepts_input() const override { return true; }
×
823

824
      bool is_seeded() const override { return true; }
276,976✔
825

826
      void fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) override {
10,250,181✔
827
         for(const auto byte : input) {
10,250,181✔
828
            mix(byte);
×
829
         }
830

831
         for(auto& byte : output) {
73,225,466✔
832
            byte = mix();
62,975,285✔
833
         }
834
      }
10,250,181✔
835

836
      Testsuite_RNG(std::string_view seed, std::string_view test_name) : m_x(0) {
276✔
837
         for(const char c : seed) {
8,280✔
838
            this->mix(static_cast<uint8_t>(c));
8,004✔
839
         }
840
         for(const char c : test_name) {
5,578✔
841
            this->mix(static_cast<uint8_t>(c));
5,302✔
842
         }
843
      }
276✔
844

845
   private:
846
      uint8_t mix(uint8_t input = 0) {
62,988,591✔
847
         m_x ^= input;
62,988,591✔
848
         m_x *= 0xF2E16957;
62,988,591✔
849
         m_x += 0xE50B590F;
62,988,591✔
850
         return static_cast<uint8_t>(m_x >> 27);
62,988,591✔
851
      }
852

853
      uint64_t m_x;
854
};
855

856
}  // namespace
857

858
//static
859
void Test::set_test_rng_seed(std::span<const uint8_t> seed, size_t epoch) {
1✔
860
   m_test_rng_seed = Botan::fmt("seed={} epoch={}", Botan::hex_encode(seed), epoch);
1✔
861
}
1✔
862

863
//static
864
std::unique_ptr<Botan::RandomNumberGenerator> Test::new_rng(std::string_view test_name) {
268✔
865
   return std::make_unique<Testsuite_RNG>(m_test_rng_seed, test_name);
268✔
866
}
867

868
//static
869
std::shared_ptr<Botan::RandomNumberGenerator> Test::new_shared_rng(std::string_view test_name) {
8✔
870
   return std::make_shared<Testsuite_RNG>(m_test_rng_seed, test_name);
8✔
871
}
872

873
//static
874
std::string Test::data_file(const std::string& file) {
773✔
875
   return options().data_dir() + "/" + file;
1,546✔
876
}
877

878
//static
879
std::string Test::data_dir(const std::string& subdir) {
1✔
880
   return options().data_dir() + "/" + subdir;
2✔
881
}
882

883
//static
884
std::vector<std::string> Test::files_in_data_dir(const std::string& subdir) {
393✔
885
   auto fs = Botan::get_files_recursive(options().data_dir() + "/" + subdir);
1,179✔
886
   if(fs.empty()) {
393✔
887
      throw Test_Error("Test::files_in_data_dir encountered empty subdir " + subdir);
×
888
   }
889
   return fs;
393✔
890
}
×
891

892
//static
893
std::string Test::data_file_as_temporary_copy(const std::string& what) {
1✔
894
   auto tmp_basename = what;
1✔
895
   std::replace(tmp_basename.begin(), tmp_basename.end(), '/', '_');
1✔
896
   auto temp_file = temp_file_name("tmp-" + tmp_basename);
1✔
897
   if(temp_file.empty()) {
1✔
898
      return "";
×
899
   }
900
   if(!Test::copy_file(data_file(what), temp_file)) {
1✔
901
      return "";
×
902
   }
903
   return temp_file;
1✔
904
}
1✔
905

906
//static
907
std::vector<std::string> Test::provider_filter(const std::vector<std::string>& providers) {
49,022✔
908
   if(m_opts.provider().empty()) {
49,022✔
909
      return providers;
49,022✔
910
   }
911
   for(auto&& provider : providers) {
×
912
      if(provider == m_opts.provider()) {
×
913
         return std::vector<std::string>{provider};
×
914
      }
915
   }
916
   return std::vector<std::string>{};
×
917
}
×
918

919
std::string Test::random_password(Botan::RandomNumberGenerator& rng) {
222✔
920
   const size_t len = 1 + rng.next_byte() % 32;
222✔
921
   return Botan::hex_encode(rng.random_vec(len));
444✔
922
}
923

924
size_t Test::random_index(Botan::RandomNumberGenerator& rng, size_t max) {
8,062✔
925
   return Botan::load_be(rng.random_array<8>()) % max;
8,062✔
926
}
927

928
void VarMap::clear() {
34,281✔
929
   m_vars.clear();
×
930
}
×
931

932
namespace {
933

934
bool varmap_pair_lt(const std::pair<std::string, std::string>& kv, const std::string& k) {
1,713,618✔
935
   return kv.first < k;
1,713,618✔
936
}
937

938
}  // namespace
939

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

943
   if(i != m_vars.end() && i->first == key) {
156,235✔
944
      i->second = value;
44,405✔
945
   } else {
946
      m_vars.emplace(i, key, value);
111,830✔
947
   }
948
}
156,235✔
949

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

953
   if(i != m_vars.end() && i->first == key) {
568,446✔
954
      return i->second;
498,591✔
955
   } else {
956
      return {};
69,855✔
957
   }
958
}
959

960
bool VarMap::has_key(const std::string& key) const {
213,574✔
961
   return get_var(key).has_value();
213,574✔
962
}
963

964
std::string VarMap::get_req_str(const std::string& key) const {
259,629✔
965
   auto var = get_var(key);
259,629✔
966
   if(var) {
259,629✔
967
      return *var;
519,258✔
968
   } else {
969
      throw Test_Error("Test missing variable " + key);
×
970
   }
971
}
259,629✔
972

973
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(const std::string& key) const {
12✔
974
   const auto var = get_req_str(key);
12✔
975

976
   std::vector<std::vector<uint8_t>> bin_list;
12✔
977

978
   for(auto&& part : Botan::split_on(var, ',')) {
62✔
979
      try {
50✔
980
         bin_list.push_back(Botan::hex_decode(part));
100✔
981
      } catch(std::exception& e) {
×
982
         std::ostringstream oss;
×
983
         oss << "Bad input '" << part << "'"
×
984
             << " in binary list key " << key << " - " << e.what();
×
985
         throw Test_Error(oss.str());
×
986
      }
×
987
   }
12✔
988

989
   return bin_list;
12✔
990
}
12✔
991

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

995
   try {
163,711✔
996
      if(var.starts_with("0x")) {
163,711✔
997
         if(var.size() % 2 == 0) {
×
998
            return Botan::hex_decode(var.substr(2));
×
999
         } else {
1000
            std::string z = var;
×
1001
            std::swap(z[0], z[1]);  // swap 0x to x0 then remove x
×
1002
            return Botan::hex_decode(z.substr(1));
×
1003
         }
×
1004
      } else {
1005
         return Botan::hex_decode(var);
163,711✔
1006
      }
1007
   } catch(std::exception& e) {
×
1008
      std::ostringstream oss;
×
1009
      oss << "Bad input '" << var << "'"
×
1010
          << " for key " << key << " - " << e.what();
×
1011
      throw Test_Error(oss.str());
×
1012
   }
×
1013
}
163,711✔
1014

1015
std::string VarMap::get_opt_str(const std::string& key, const std::string& def_value) const {
14,378✔
1016
   if(auto v = get_var(key)) {
14,378✔
1017
      return *v;
57✔
1018
   } else {
1019
      return def_value;
28,699✔
1020
   }
14,378✔
1021
}
1022

1023
bool VarMap::get_req_bool(const std::string& key) const {
39✔
1024
   const auto var = get_req_str(key);
39✔
1025

1026
   if(var == "true") {
39✔
1027
      return true;
1028
   } else if(var == "false") {
23✔
1029
      return false;
1030
   } else {
1031
      throw Test_Error("Invalid boolean for key '" + key + "' value '" + var + "'");
×
1032
   }
1033
}
39✔
1034

1035
size_t VarMap::get_req_sz(const std::string& key) const {
4,547✔
1036
   return Botan::to_u32bit(get_req_str(key));
4,547✔
1037
}
1038

1039
uint8_t VarMap::get_req_u8(const std::string& key) const {
17✔
1040
   const size_t s = this->get_req_sz(key);
17✔
1041
   if(s > 256) {
17✔
1042
      throw Test_Error("Invalid " + key + " expected uint8_t got " + std::to_string(s));
×
1043
   }
1044
   return static_cast<uint8_t>(s);
17✔
1045
}
1046

1047
uint32_t VarMap::get_req_u32(const std::string& key) const {
14✔
1048
   return static_cast<uint32_t>(get_req_sz(key));
14✔
1049
}
1050

1051
uint64_t VarMap::get_req_u64(const std::string& key) const {
17✔
1052
   const auto var = get_req_str(key);
17✔
1053
   try {
17✔
1054
      return std::stoull(var);
17✔
1055
   } catch(std::exception&) {
×
1056
      throw Test_Error("Invalid u64 value '" + var + "'");
×
1057
   }
×
1058
}
17✔
1059

1060
size_t VarMap::get_opt_sz(const std::string& key, const size_t def_value) const {
31,379✔
1061
   if(auto v = get_var(key)) {
31,379✔
1062
      return Botan::to_u32bit(*v);
12,244✔
1063
   } else {
1064
      return def_value;
1065
   }
31,379✔
1066
}
1067

1068
uint64_t VarMap::get_opt_u64(const std::string& key, const uint64_t def_value) const {
3,538✔
1069
   if(auto v = get_var(key)) {
3,538✔
1070
      try {
641✔
1071
         return std::stoull(*v);
3,538✔
1072
      } catch(std::exception&) {
×
1073
         throw Test_Error("Invalid u64 value '" + *v + "'");
×
1074
      }
×
1075
   } else {
1076
      return def_value;
1077
   }
3,538✔
1078
}
1079

1080
std::vector<uint8_t> VarMap::get_opt_bin(const std::string& key) const {
45,868✔
1081
   if(auto v = get_var(key)) {
45,868✔
1082
      try {
16,134✔
1083
         return Botan::hex_decode(*v);
16,134✔
1084
      } catch(std::exception&) {
×
1085
         throw Test_Error("Test invalid hex input '" + *v + "'" + +" for key " + key);
×
1086
      }
×
1087
   } else {
1088
      return {};
29,734✔
1089
   };
45,868✔
1090
}
1091

1092
#if defined(BOTAN_HAS_BIGINT)
1093
Botan::BigInt VarMap::get_req_bn(const std::string& key) const {
38,502✔
1094
   const auto var = get_req_str(key);
38,502✔
1095

1096
   try {
38,502✔
1097
      return Botan::BigInt(var);
38,502✔
1098
   } catch(std::exception&) {
×
1099
      throw Test_Error("Test invalid bigint input '" + var + "' for key " + key);
×
1100
   }
×
1101
}
38,502✔
1102

1103
Botan::BigInt VarMap::get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const {
80✔
1104
   if(auto v = get_var(key)) {
80✔
1105
      try {
56✔
1106
         return Botan::BigInt(*v);
56✔
1107
      } catch(std::exception&) {
×
1108
         throw Test_Error("Test invalid bigint input '" + *v + "' for key " + key);
×
1109
      }
×
1110
   } else {
1111
      return def_value;
24✔
1112
   }
80✔
1113
}
1114
#endif
1115

1116
class Text_Based_Test::Text_Based_Test_Data {
1117
   public:
1118
      Text_Based_Test_Data(const std::string& data_src,
181✔
1119
                           const std::string& required_keys_str,
1120
                           const std::string& optional_keys_str) :
181✔
1121
            m_data_src(data_src) {
362✔
1122
         if(required_keys_str.empty()) {
181✔
1123
            throw Test_Error("Invalid test spec");
×
1124
         }
1125

1126
         m_required_keys = Botan::split_on(required_keys_str, ',');
181✔
1127
         std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
181✔
1128

1129
         m_all_keys.insert(m_required_keys.begin(), m_required_keys.end());
181✔
1130
         m_all_keys.insert(optional_keys.begin(), optional_keys.end());
181✔
1131
         m_output_key = m_required_keys.at(m_required_keys.size() - 1);
181✔
1132
      }
181✔
1133

1134
      std::string get_next_line();
1135

1136
      const std::string& current_source_name() const { return m_cur_src_name; }
×
1137

1138
      bool known_key(const std::string& key) const;
1139

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

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

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

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

1148
      const std::string& initial_data_src_name() const { return m_data_src; }
181✔
1149

1150
   private:
1151
      std::string m_data_src;
1152
      std::vector<std::string> m_required_keys;
1153
      std::unordered_set<std::string> m_all_keys;
1154
      std::string m_output_key;
1155

1156
      bool m_first = true;
1157
      std::unique_ptr<std::istream> m_cur;
1158
      std::string m_cur_src_name;
1159
      std::deque<std::string> m_srcs;
1160
      std::vector<std::string> m_cpu_flags;
1161
};
1162

1163
Text_Based_Test::Text_Based_Test(const std::string& data_src,
181✔
1164
                                 const std::string& required_keys,
1165
                                 const std::string& optional_keys) :
181✔
1166
      m_data(std::make_unique<Text_Based_Test_Data>(data_src, required_keys, optional_keys)) {}
181✔
1167

1168
Text_Based_Test::~Text_Based_Test() = default;
181✔
1169

1170
std::string Text_Based_Test::Text_Based_Test_Data::get_next_line() {
157,242✔
1171
   while(true) {
157,500✔
1172
      if(m_cur == nullptr || m_cur->good() == false) {
157,500✔
1173
         if(m_srcs.empty()) {
450✔
1174
            if(m_first) {
362✔
1175
               if(m_data_src.ends_with(".vec")) {
181✔
1176
                  m_srcs.push_back(Test::data_file(m_data_src));
338✔
1177
               } else {
1178
                  const auto fs = Test::files_in_data_dir(m_data_src);
12✔
1179
                  m_srcs.assign(fs.begin(), fs.end());
12✔
1180
                  if(m_srcs.empty()) {
12✔
1181
                     throw Test_Error("Error reading test data dir " + m_data_src);
×
1182
                  }
1183
               }
12✔
1184

1185
               m_first = false;
181✔
1186
            } else {
1187
               return "";  // done
181✔
1188
            }
1189
         }
1190

1191
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
357✔
1192
         m_cur_src_name = m_srcs[0];
269✔
1193

1194
#if defined(BOTAN_HAS_CPUID)
1195
         // Reinit cpuid on new file if needed
1196
         if(m_cpu_flags.empty() == false) {
269✔
1197
            m_cpu_flags.clear();
19✔
1198
            Botan::CPUID::initialize();
19✔
1199
         }
1200
#endif
1201

1202
         if(!m_cur->good()) {
269✔
1203
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
1204
         }
1205

1206
         m_srcs.pop_front();
269✔
1207
      }
1208

1209
      while(m_cur->good()) {
227,897✔
1210
         std::string line;
227,639✔
1211
         std::getline(*m_cur, line);
227,639✔
1212

1213
         if(line.empty()) {
227,639✔
1214
            continue;
55,310✔
1215
         }
1216

1217
         if(line[0] == '#') {
172,329✔
1218
            if(line.starts_with("#test ")) {
15,289✔
1219
               return line;
21✔
1220
            } else {
1221
               continue;
15,268✔
1222
            }
1223
         }
1224

1225
         return line;
157,040✔
1226
      }
227,639✔
1227
   }
1228
}
1229

1230
bool Text_Based_Test::Text_Based_Test_Data::known_key(const std::string& key) const {
156,235✔
1231
   return m_all_keys.contains(key);
156,235✔
1232
}
1233

1234
namespace {
1235

1236
// strips leading and trailing but not internal whitespace
1237
std::string strip_ws(const std::string& in) {
312,470✔
1238
   const char* whitespace = " ";
312,470✔
1239

1240
   const auto first_c = in.find_first_not_of(whitespace);
312,470✔
1241
   if(first_c == std::string::npos) {
312,470✔
1242
      return "";
1,033✔
1243
   }
1244

1245
   const auto last_c = in.find_last_not_of(whitespace);
311,437✔
1246

1247
   return in.substr(first_c, last_c - first_c + 1);
311,437✔
1248
}
1249

1250
std::vector<std::string> parse_cpuid_bits(const std::vector<std::string>& tok) {
21✔
1251
   std::vector<std::string> bits;
21✔
1252

1253
#if defined(BOTAN_HAS_CPUID)
1254
   for(size_t i = 1; i < tok.size(); ++i) {
106✔
1255
      if(auto bit = Botan::CPUID::bit_from_string(tok[i])) {
85✔
1256
         bits.push_back(bit->to_string());
98✔
1257
      }
1258
   }
1259
#else
1260
   BOTAN_UNUSED(tok);
1261
#endif
1262

1263
   return bits;
21✔
1264
}
×
1265

1266
}  // namespace
1267

1268
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) {
32,609✔
1269
   return false;
32,609✔
1270
}
1271

1272
std::vector<Test::Result> Text_Based_Test::run() {
181✔
1273
   std::vector<Test::Result> results;
181✔
1274

1275
   std::string header;
181✔
1276
   std::string header_or_name = m_data->initial_data_src_name();
181✔
1277
   VarMap vars;
181✔
1278
   size_t test_cnt = 0;
181✔
1279

1280
   while(true) {
157,242✔
1281
      const std::string line = m_data->get_next_line();
157,242✔
1282
      if(line.empty()) {
157,242✔
1283
         // EOF
1284
         break;
1285
      }
1286

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

1290
         if(pragma_tokens.empty()) {
21✔
1291
            throw Test_Error("Empty pragma found in " + m_data->current_source_name());
×
1292
         }
1293

1294
         if(pragma_tokens[0] != "cpuid") {
21✔
1295
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1296
         }
1297

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

1302
         m_data->set_cpu_flags(parse_cpuid_bits(pragma_tokens));
42✔
1303

1304
         continue;
21✔
1305
      } else if(line[0] == '#') {
157,061✔
1306
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1307
      }
1308

1309
      if(line[0] == '[' && line[line.size() - 1] == ']') {
157,040✔
1310
         header = line.substr(1, line.size() - 2);
805✔
1311
         header_or_name = header;
805✔
1312
         test_cnt = 0;
805✔
1313
         vars.clear();
805✔
1314
         continue;
805✔
1315
      }
1316

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

1319
      auto equal_i = line.find_first_of('=');
156,235✔
1320

1321
      if(equal_i == std::string::npos) {
156,235✔
1322
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1323
         continue;
×
1324
      }
1325

1326
      const std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
312,470✔
1327
      const std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
312,470✔
1328

1329
      if(!m_data->known_key(key)) {
156,235✔
1330
         auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key));
×
1331
         results.push_back(r);
×
1332
      }
×
1333

1334
      vars.add(key, val);
156,235✔
1335

1336
      if(key == m_data->output_key()) {
156,235✔
1337
         try {
48,388✔
1338
            for(const auto& req_key : m_data->required_keys()) {
245,554✔
1339
               if(!vars.has_key(req_key)) {
197,166✔
1340
                  auto r =
×
1341
                     Test::Result::Failure(header_or_name, Botan::fmt("{} missing required key {}", test_id, req_key));
×
1342
                  results.push_back(r);
×
1343
               }
×
1344
            }
1345

1346
            if(skip_this_test(header, vars)) {
48,388✔
1347
               continue;
139✔
1348
            }
1349

1350
            ++test_cnt;
48,249✔
1351

1352
            const uint64_t start = Test::timestamp();
48,249✔
1353

1354
            Test::Result result = run_one_test(header, vars);
48,249✔
1355
#if defined(BOTAN_HAS_CPUID)
1356
            if(!m_data->cpu_flags().empty()) {
48,249✔
1357
               for(const auto& cpuid_str : m_data->cpu_flags()) {
30,621✔
1358
                  if(const auto bit = Botan::CPUID::Feature::from_string(cpuid_str)) {
21,677✔
1359
                     if(Botan::CPUID::has(*bit)) {
21,677✔
1360
                        Botan::CPUID::clear_cpuid_bit(*bit);
16,577✔
1361
                        // now re-run the test
1362
                        result.merge(run_one_test(header, vars));
16,577✔
1363
                     }
1364
                  }
1365
               }
1366
               Botan::CPUID::initialize();
8,944✔
1367
            }
1368
#endif
1369
            result.set_ns_consumed(Test::timestamp() - start);
48,249✔
1370

1371
            if(result.tests_failed() > 0) {
48,249✔
1372
               std::ostringstream oss;
×
1373
               oss << "Test # " << test_cnt << " ";
×
1374
               if(!header.empty()) {
×
1375
                  oss << header << " ";
×
1376
               }
1377
               oss << "failed ";
×
1378

1379
               for(const auto& k : m_data->required_keys()) {
×
1380
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1381
               }
1382

1383
               result.test_note(oss.str());
×
1384
            }
×
1385
            results.push_back(result);
48,249✔
1386
         } catch(std::exception& e) {
48,249✔
1387
            std::ostringstream oss;
×
1388
            oss << "Test # " << test_cnt << " ";
×
1389
            if(!header.empty()) {
×
1390
               oss << header << " ";
×
1391
            }
1392

1393
            for(const auto& k : m_data->required_keys()) {
×
1394
               oss << k << "=" << vars.get_req_str(k) << " ";
×
1395
            }
1396

1397
            oss << "failed with exception '" << e.what() << "'";
×
1398

1399
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1400
         }
×
1401

1402
         if(clear_between_callbacks()) {
48,249✔
1403
            vars.clear();
189,572✔
1404
         }
1405
      }
1406
   }
157,339✔
1407

1408
   if(results.empty()) {
181✔
1409
      return results;
1410
   }
1411

1412
   try {
181✔
1413
      std::vector<Test::Result> final_tests = run_final_tests();
181✔
1414
      results.insert(results.end(), final_tests.begin(), final_tests.end());
181✔
1415
   } catch(std::exception& e) {
181✔
1416
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1417
   }
×
1418

1419
   return results;
1420
}
181✔
1421

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