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

randombit / botan / 22018375255

14 Feb 2026 01:37PM UTC coverage: 90.069% (+0.007%) from 90.062%
22018375255

Pull #5330

github

web-flow
Merge d3b2de7c6 into fa5638d32
Pull Request #5330: Avoid including assert.h into tests.h

102246 of 113520 relevant lines covered (90.07%)

11438982.24 hits per line

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

79.67
/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,126✔
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,761✔
71
   if(who() != other.who()) {
126,761✔
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,688✔
81
   }
82

83
   m_timestamp = std::min(m_timestamp, other.m_timestamp);
126,761✔
84
   m_ns_taken += other.m_ns_taken;
126,761✔
85
   m_tests_passed += other.m_tests_passed;
126,761✔
86
   m_fail_log.insert(m_fail_log.end(), other.m_fail_log.begin(), other.m_fail_log.end());
126,761✔
87
   m_log.insert(m_log.end(), other.m_log.begin(), other.m_log.end());
126,761✔
88
}
126,761✔
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
Test::Result::ThrowExpectations::~ThrowExpectations() {
67,783✔
136
   BOTAN_ASSERT_NOMSG(m_consumed);
67,783✔
137
}
130,020✔
138

139
void Test::Result::ThrowExpectations::assert_that_success_is_not_expected() const {
62,237✔
140
   BOTAN_ASSERT_NOMSG(!m_expect_success);
62,048✔
141
}
62,048✔
142

143
Test::Result::ThrowExpectations& Test::Result::ThrowExpectations::expect_success() {
1,645✔
144
   BOTAN_ASSERT_NOMSG(!m_expected_message && !m_expected_exception_check_fn);
1,645✔
145
   m_expect_success = true;
1,645✔
146
   return *this;
1,645✔
147
}
148

149
Test::Result::ThrowExpectations& Test::Result::ThrowExpectations::expect_message(std::string_view message) {
189✔
150
   assert_that_success_is_not_expected();
189✔
151
   m_expected_message = message;
189✔
152
   return *this;
189✔
153
}
154

155
bool Test::Result::ThrowExpectations::check(std::string_view test_name, Test::Result& result) {
67,783✔
156
   m_consumed = true;
67,783✔
157

158
   try {
67,783✔
159
      m_fn();
67,783✔
160
      if(!m_expect_success) {
1,646✔
161
         return result.test_failure(Botan::fmt("{} failed to throw expected exception", test_name));
2✔
162
      }
163
   } catch(const std::exception& ex) {
66,137✔
164
      if(m_expect_success) {
66,135✔
165
         return result.test_failure(Botan::fmt("{} threw unexpected exception: {}", test_name, ex.what()));
1✔
166
      }
167
      if(m_expected_exception_check_fn && !m_expected_exception_check_fn(std::current_exception())) {
190,230✔
168
         return result.test_failure(Botan::fmt("{} threw unexpected exception: {}", test_name, ex.what()));
2✔
169
      }
170
      if(m_expected_message.has_value() && m_expected_message.value() != ex.what()) {
66,132✔
171
         return result.test_failure(Botan::fmt("{} threw exception with unexpected message (expected {} got {})",
1✔
172
                                               test_name,
173
                                               m_expected_message.value(),
1✔
174
                                               ex.what()));
2✔
175
      }
176
   } catch(...) {
66,137✔
177
      if(m_expect_success || m_expected_exception_check_fn || m_expected_message.has_value()) {
2✔
178
         return result.test_failure(Botan::fmt("{} threw unexpected unknown exception", test_name));
1✔
179
      }
180
   }
2✔
181

182
   return result.test_success();
67,776✔
183
}
184

185
bool Test::Result::test_throws(std::string_view what, std::function<void()> fn) {
3,916✔
186
   return ThrowExpectations(std::move(fn)).check(what, *this);
11,748✔
187
}
188

189
bool Test::Result::test_throws(std::string_view what, std::string_view expected, std::function<void()> fn) {
174✔
190
   return ThrowExpectations(std::move(fn)).expect_message(expected).check(what, *this);
522✔
191
}
192

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

197
bool Test::Result::test_success(std::string_view note) {
3,620,267✔
198
   if(Test::options().log_success()) {
3,620,242✔
199
      test_note(note);
×
200
   }
201
   ++m_tests_passed;
3,620,267✔
202
   return true;
775,713✔
203
}
204

205
bool Test::Result::test_failure(std::string_view what, std::string_view error) {
2✔
206
   return test_failure(Botan::fmt("{} {} with error {}", who(), what, error));
2✔
207
}
208

209
void Test::Result::test_failure(std::string_view what, const uint8_t buf[], size_t buf_len) {
×
210
   return test_failure(what, {buf, buf_len});
×
211
}
212

213
void Test::Result::test_failure(std::string_view what, std::span<const uint8_t> context) {
1✔
214
   test_failure(Botan::fmt("{} {} with value {}", who(), what, Botan::hex_encode(context)));
2✔
215
}
1✔
216

217
bool Test::Result::test_failure(std::string_view err) {
25✔
218
   m_fail_log.push_back(std::string(err));
25✔
219

220
   if(Test::options().abort_on_first_fail() && m_who != "Failing Test") {
25✔
221
      std::abort();
×
222
   }
223
   return false;
25✔
224
}
225

226
namespace {
227

228
bool same_contents(const uint8_t x[], const uint8_t y[], size_t len) {
292,418✔
229
   return (len == 0) ? true : std::memcmp(x, y, len) == 0;
290,987✔
230
}
231

232
}  // namespace
233

234
bool Test::Result::test_ne(std::string_view what,
3,408✔
235
                           const uint8_t produced[],
236
                           size_t produced_len,
237
                           const uint8_t expected[],
238
                           size_t expected_len) {
239
   if(produced_len == expected_len && same_contents(produced, expected, expected_len)) {
3,408✔
240
      return test_failure(Botan::fmt("{} {} produced matching bytes", who(), what));
4✔
241
   }
242
   return test_success();
3,406✔
243
}
244

245
bool Test::Result::test_eq(std::string_view what, std::span<const uint8_t> produced, const char* expected_hex) {
471✔
246
   const std::vector<uint8_t> expected = Botan::hex_decode(expected_hex);
471✔
247
   return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
471✔
248
}
471✔
249

250
bool Test::Result::test_eq(const char* producer,
290,963✔
251
                           std::string_view what,
252
                           const uint8_t produced[],
253
                           size_t produced_size,
254
                           const uint8_t expected[],
255
                           size_t expected_size) {
256
   if(produced_size == expected_size && same_contents(produced, expected, expected_size)) {
290,963✔
257
      return test_success();
290,962✔
258
   }
259

260
   std::ostringstream err;
1✔
261

262
   err << who();
1✔
263

264
   if(producer != nullptr) {
1✔
265
      err << " producer '" << producer << "'";
×
266
   }
267

268
   err << " unexpected result for " << what;
1✔
269

270
   if(produced_size != expected_size) {
1✔
271
      err << " produced " << produced_size << " bytes expected " << expected_size;
1✔
272
   }
273

274
   std::vector<uint8_t> xor_diff(std::min(produced_size, expected_size));
2✔
275
   size_t bytes_different = 0;
1✔
276

277
   for(size_t i = 0; i != xor_diff.size(); ++i) {
4✔
278
      xor_diff[i] = produced[i] ^ expected[i];
3✔
279
      if(xor_diff[i] > 0) {
3✔
280
         bytes_different++;
3✔
281
      }
282
   }
283

284
   err << "\nProduced: " << Botan::hex_encode(produced, produced_size)
1✔
285
       << "\nExpected: " << Botan::hex_encode(expected, expected_size);
3✔
286

287
   if(bytes_different > 0) {
1✔
288
      err << "\nXOR Diff: " << Botan::hex_encode(xor_diff);
1✔
289
   }
290

291
   return test_failure(err.str());
1✔
292
}
1✔
293

294
bool Test::Result::test_is_nonempty(std::string_view what_is_it, std::string_view to_examine) {
38,829✔
295
   if(to_examine.empty()) {
38,829✔
296
      return test_failure(what_is_it, "was empty");
1✔
297
   }
298
   return test_success();
38,828✔
299
}
300

301
bool Test::Result::test_eq(std::string_view what, std::string_view produced, std::string_view expected) {
76,783✔
302
   return test_is_eq(what, produced, expected);
76,783✔
303
}
304

305
bool Test::Result::test_eq(std::string_view what, const char* produced, const char* expected) {
29✔
306
   return test_is_eq(what, std::string(produced), std::string(expected));
29✔
307
}
308

309
bool Test::Result::test_eq(std::string_view what, size_t produced, size_t expected) {
146,708✔
310
   return test_is_eq(what, produced, expected);
146,708✔
311
}
312

313
bool Test::Result::test_eq_sz(std::string_view what, size_t produced, size_t expected) {
45,789✔
314
   return test_is_eq(what, produced, expected);
45,789✔
315
}
316

317
bool Test::Result::test_lt(std::string_view what, size_t produced, size_t expected) {
5,639✔
318
   if(produced >= expected) {
5,639✔
319
      std::ostringstream err;
1✔
320
      err << m_who << " " << what;
1✔
321
      err << " unexpected result " << produced << " >= " << expected;
1✔
322
      return test_failure(err.str());
1✔
323
   }
1✔
324

325
   return test_success();
5,638✔
326
}
327

328
bool Test::Result::test_lte(std::string_view what, size_t produced, size_t expected) {
1,021,636✔
329
   if(produced > expected) {
1,021,636✔
330
      std::ostringstream err;
1✔
331
      err << m_who << " " << what << " unexpected result " << produced << " > " << expected;
1✔
332
      return test_failure(err.str());
1✔
333
   }
1✔
334

335
   return test_success();
1,021,635✔
336
}
337

338
bool Test::Result::test_gte(std::string_view what, size_t produced, size_t expected) {
1,142,430✔
339
   if(produced < expected) {
1,142,430✔
340
      std::ostringstream err;
1✔
341
      err << m_who;
1✔
342
      err << " " << what;
1✔
343
      err << " unexpected result " << produced << " < " << expected;
1✔
344
      return test_failure(err.str());
1✔
345
   }
1✔
346

347
   return test_success();
1,142,429✔
348
}
349

350
bool Test::Result::test_gt(std::string_view what, size_t produced, size_t expected) {
22,373✔
351
   if(produced <= expected) {
22,373✔
352
      std::ostringstream err;
×
353
      err << m_who;
×
354
      err << " " << what;
×
355
      err << " unexpected result " << produced << " <= " << expected;
×
356
      return test_failure(err.str());
×
357
   }
×
358

359
   return test_success();
22,373✔
360
}
361

362
bool Test::Result::test_ne(std::string_view what, std::string_view str1, std::string_view str2) {
26✔
363
   if(str1 != str2) {
26✔
364
      return test_success(Botan::fmt("{} != {}", str1, str2));
25✔
365
   } else {
366
      return test_failure(Botan::fmt("{} {} unexpectedly produced matching strings {}", who(), what, str1));
1✔
367
   }
368
}
369

370
bool Test::Result::test_ne(std::string_view what, size_t produced, size_t expected) {
119✔
371
   if(produced != expected) {
119✔
372
      return test_success();
118✔
373
   }
374

375
   std::ostringstream err;
1✔
376
   err << who() << " " << what << " produced " << produced << " unexpected value";
1✔
377
   return test_failure(err.str());
1✔
378
}
1✔
379

380
#if defined(BOTAN_HAS_BIGINT)
381
bool Test::Result::test_eq(std::string_view what, const BigInt& produced, const BigInt& expected) {
252,639✔
382
   return test_is_eq(what, produced, expected);
252,639✔
383
}
384

385
bool Test::Result::test_ne(std::string_view what, const BigInt& produced, const BigInt& expected) {
97✔
386
   if(produced != expected) {
97✔
387
      return test_success();
96✔
388
   }
389

390
   std::ostringstream err;
1✔
391
   err << who() << " " << what << " produced " << produced << " prohibited value";
1✔
392
   return test_failure(err.str());
1✔
393
}
1✔
394
#endif
395

396
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
397
bool Test::Result::test_eq(std::string_view what, const Botan::EC_Point& a, const Botan::EC_Point& b) {
3,248✔
398
   //return test_is_eq(what, a, b);
399
   if(a == b) {
3,248✔
400
      return test_success();
3,248✔
401
   }
402

403
   std::ostringstream err;
×
404
   err << who() << " " << what << " a=(" << a.get_affine_x() << "," << a.get_affine_y() << ")"
×
405
       << " b=(" << b.get_affine_x() << "," << b.get_affine_y();
×
406
   return test_failure(err.str());
×
407
}
×
408
#endif
409

410
bool Test::Result::test_eq(std::string_view what, bool produced, bool expected) {
378,487✔
411
   return test_is_eq(what, produced, expected);
378,487✔
412
}
413

414
bool Test::Result::test_rc_ok(std::string_view func, int rc) {
2,810✔
415
   if(rc != 0) {
2,810✔
416
      std::ostringstream err;
1✔
417
      err << m_who << " " << func << " unexpectedly failed with error code " << rc;
1✔
418
      return test_failure(err.str());
1✔
419
   }
1✔
420

421
   return test_success();
2,809✔
422
}
423

424
bool Test::Result::test_rc_fail(std::string_view func, std::string_view why, int rc) {
26✔
425
   if(rc == 0) {
26✔
426
      std::ostringstream err;
1✔
427
      err << m_who << " call to " << func << " unexpectedly succeeded expecting failure because " << why;
1✔
428
      return test_failure(err.str());
1✔
429
   }
1✔
430

431
   return test_success();
25✔
432
}
433

434
bool Test::Result::test_rc_init(std::string_view func, int rc) {
117✔
435
   if(rc == 0) {
117✔
436
      return test_success();
117✔
437
   } else {
438
      std::ostringstream msg;
×
439
      msg << m_who;
×
440
      msg << " " << func;
×
441

442
      // -40 is BOTAN_FFI_ERROR_NOT_IMPLEMENTED
443
      if(rc == -40) {
×
444
         msg << " returned not implemented";
×
445
      } else {
446
         msg << " unexpectedly failed with error code " << rc;
×
447
      }
448

449
      if(rc == -40) {
×
450
         this->test_note(msg.str());
×
451
      } else {
452
         this->test_failure(msg.str());
×
453
      }
454
      return false;
×
455
   }
×
456
}
457

458
bool Test::Result::test_rc(std::string_view func, int expected, int rc) {
416✔
459
   if(expected != rc) {
416✔
460
      std::ostringstream err;
1✔
461
      err << m_who;
1✔
462
      err << " call to " << func << " unexpectedly returned " << rc;
1✔
463
      err << " but expecting " << expected;
1✔
464
      return test_failure(err.str());
1✔
465
   }
1✔
466

467
   return test_success();
415✔
468
}
469

470
void Test::initialize(std::string test_name, CodeLocation location) {
419✔
471
   m_test_name = std::move(test_name);
419✔
472
   m_registration_location = location;
419✔
473
}
419✔
474

475
Botan::RandomNumberGenerator& Test::rng() const {
463,040✔
476
   if(!m_test_rng) {
463,040✔
477
      m_test_rng = Test::new_rng(m_test_name);
145✔
478
   }
479

480
   return *m_test_rng;
463,040✔
481
}
482

483
std::optional<std::string> Test::supported_ec_group_name(std::vector<std::string> preferred_groups) {
151✔
484
#if defined(BOTAN_HAS_ECC_GROUP)
485
   if(preferred_groups.empty()) {
151✔
486
      preferred_groups = {
149✔
487
         "secp256r1",
488
         "brainpool256r1",
489
         "secp384r1",
490
         "brainpool384r1",
491
         "secp521r1",
492
         "brainpool512r1",
493
      };
1,192✔
494
   }
495

496
   for(const auto& group : preferred_groups) {
151✔
497
      if(Botan::EC_Group::supports_named_group(group)) {
151✔
498
         return group;
151✔
499
      }
500
   }
501
#else
502
   BOTAN_UNUSED(preferred_groups);
503
#endif
504

505
   return std::nullopt;
×
506
}
298✔
507

508
std::vector<uint8_t> Test::mutate_vec(const std::vector<uint8_t>& v,
96,742✔
509
                                      Botan::RandomNumberGenerator& rng,
510
                                      bool maybe_resize,
511
                                      size_t min_offset) {
512
   std::vector<uint8_t> r = v;
96,742✔
513

514
   if(maybe_resize && (r.empty() || rng.next_byte() < 32)) {
110,320✔
515
      // TODO: occasionally truncate, insert at random index
516
      const size_t add = 1 + (rng.next_byte() % 16);
2,170✔
517
      r.resize(r.size() + add);
2,170✔
518
      rng.randomize(&r[r.size() - add], add);
2,170✔
519
   }
520

521
   if(r.size() > min_offset) {
96,742✔
522
      const size_t offset = std::max<size_t>(min_offset, rng.next_byte() % r.size());
95,204✔
523
      const uint8_t perturb = rng.next_nonzero_byte();
95,204✔
524
      r[offset] ^= perturb;
95,204✔
525
   }
526

527
   return r;
96,742✔
528
}
×
529

530
std::vector<std::string> Test::possible_providers(const std::string& /*alg*/) {
×
531
   return Test::provider_filter({"base"});
×
532
}
533

534
//static
535
std::string Test::format_time(uint64_t nanoseconds) {
1,470✔
536
   std::ostringstream o;
1,470✔
537

538
   if(nanoseconds > 1000000000) {
1,470✔
539
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000000.0 << " sec";
156✔
540
   } else {
541
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000.0 << " msec";
1,314✔
542
   }
543

544
   return o.str();
2,940✔
545
}
1,470✔
546

547
// TODO: this should move to `StdoutReporter`
548
std::string Test::Result::result_string() const {
2,541✔
549
   const bool verbose = Test::options().verbose();
2,541✔
550

551
   if(tests_run() == 0 && !verbose) {
2,541✔
552
      return "";
20✔
553
   }
554

555
   std::ostringstream report;
2,521✔
556

557
   report << who() << " ran ";
2,521✔
558

559
   if(tests_run() == 0) {
2,521✔
560
      report << "ZERO";
×
561
   } else {
562
      report << tests_run();
2,521✔
563
   }
564
   report << " tests";
2,521✔
565

566
   if(m_ns_taken > 0) {
2,521✔
567
      report << " in " << format_time(m_ns_taken);
2,938✔
568
   }
569

570
   if(tests_failed() > 0) {
2,521✔
571
      report << " " << tests_failed() << " FAILED";
25✔
572
   } else {
573
      report << " all ok";
2,496✔
574
   }
575

576
   report << "\n";
2,521✔
577

578
   for(size_t i = 0; i != m_fail_log.size(); ++i) {
2,546✔
579
      report << "Failure " << (i + 1) << ": " << m_fail_log[i];
25✔
580
      if(m_where) {
25✔
581
         report << " (at " << m_where->path << ":" << m_where->line << ")";
×
582
      }
583
      report << "\n";
25✔
584
   }
585

586
   if(!m_fail_log.empty() || tests_run() == 0 || verbose) {
2,521✔
587
      for(size_t i = 0; i != m_log.size(); ++i) {
25✔
588
         report << "Note " << (i + 1) << ": " << m_log[i] << "\n";
×
589
      }
590
   }
591

592
   return report.str();
2,521✔
593
}
2,521✔
594

595
namespace {
596

597
class Test_Registry {
598
   public:
599
      static Test_Registry& instance() {
1,279✔
600
         static Test_Registry registry;
1,280✔
601
         return registry;
1,279✔
602
      }
603

604
      void register_test(const std::string& category,
419✔
605
                         const std::string& name,
606
                         bool smoke_test,
607
                         bool needs_serialization,
608
                         std::function<std::unique_ptr<Test>()> maker_fn) {
609
         if(m_tests.contains(name)) {
419✔
610
            throw Test_Error("Duplicate registration of test '" + name + "'");
×
611
         }
612

613
         if(m_tests.contains(category)) {
419✔
614
            throw Test_Error("'" + category + "' cannot be used as category, test exists");
×
615
         }
616

617
         if(m_categories.contains(name)) {
419✔
618
            throw Test_Error("'" + name + "' cannot be used as test name, category exists");
×
619
         }
620

621
         if(smoke_test) {
419✔
622
            m_smoke_tests.push_back(name);
10✔
623
         }
624

625
         if(needs_serialization) {
419✔
626
            m_mutexed_tests.push_back(name);
21✔
627
         }
628

629
         m_tests.emplace(name, std::move(maker_fn));
419✔
630
         m_categories.emplace(category, name);
419✔
631
      }
419✔
632

633
      std::unique_ptr<Test> get_test(const std::string& test_name) const {
419✔
634
         auto i = m_tests.find(test_name);
419✔
635
         if(i != m_tests.end()) {
419✔
636
            return i->second();
419✔
637
         }
638
         return nullptr;
×
639
      }
640

641
      std::vector<std::string> registered_tests() const {
×
642
         std::vector<std::string> s;
×
643
         s.reserve(m_tests.size());
×
644
         for(auto&& i : m_tests) {
×
645
            s.push_back(i.first);
×
646
         }
647
         return s;
×
648
      }
×
649

650
      std::vector<std::string> registered_test_categories() const {
×
651
         std::set<std::string> s;
×
652
         for(auto&& i : m_categories) {
×
653
            s.insert(i.first);
×
654
         }
655
         return std::vector<std::string>(s.begin(), s.end());
×
656
      }
×
657

658
      std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
1✔
659
                                                       const std::vector<std::string>& to_be_skipped) {
660
         std::vector<std::string> result;
1✔
661

662
         std::set<std::string> to_be_skipped_set(to_be_skipped.begin(), to_be_skipped.end());
1✔
663
         // TODO: this is O(n^2), but we have a relatively small number of tests.
664
         auto insert_if_not_exists_and_not_skipped = [&](const std::string& test_name) {
420✔
665
            if(!Botan::value_exists(result, test_name) && !to_be_skipped_set.contains(test_name)) {
838✔
666
               result.push_back(test_name);
409✔
667
            }
668
         };
420✔
669

670
         if(requested.empty()) {
1✔
671
            /*
672
            If nothing was requested on the command line, run everything. First
673
            run the "essentials" to smoke test, then everything else in
674
            alphabetical order.
675
            */
676
            result = m_smoke_tests;
1✔
677
            for(const auto& [test_name, _] : m_tests) {
420✔
678
               insert_if_not_exists_and_not_skipped(test_name);
419✔
679
            }
680
         } else {
681
            for(const auto& r : requested) {
×
682
               if(m_tests.contains(r)) {
×
683
                  insert_if_not_exists_and_not_skipped(r);
×
684
               } else if(auto elems = m_categories.equal_range(r); elems.first != m_categories.end()) {
×
685
                  for(; elems.first != elems.second; ++elems.first) {
×
686
                     insert_if_not_exists_and_not_skipped(elems.first->second);
×
687
                  }
688
               } else {
689
                  throw Test_Error("Unknown test suite or category: " + r);
×
690
               }
691
            }
692
         }
693

694
         return result;
1✔
695
      }
1✔
696

697
      bool needs_serialization(const std::string& test_name) const {
440✔
698
         return Botan::value_exists(m_mutexed_tests, test_name);
21✔
699
      }
700

701
   private:
702
      Test_Registry() = default;
1✔
703

704
   private:
705
      std::map<std::string, std::function<std::unique_ptr<Test>()>> m_tests;
706
      std::multimap<std::string, std::string> m_categories;
707
      std::vector<std::string> m_smoke_tests;
708
      std::vector<std::string> m_mutexed_tests;
709
};
710

711
}  // namespace
712

713
// static Test:: functions
714

715
//static
716
void Test::register_test(const std::string& category,
419✔
717
                         const std::string& name,
718
                         bool smoke_test,
719
                         bool needs_serialization,
720
                         std::function<std::unique_ptr<Test>()> maker_fn) {
721
   Test_Registry::instance().register_test(category, name, smoke_test, needs_serialization, std::move(maker_fn));
838✔
722
}
419✔
723

724
//static
725
uint64_t Test::timestamp() {
180,013✔
726
   auto now = std::chrono::system_clock::now().time_since_epoch();
180,013✔
727
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
2,383✔
728
}
729

730
//static
731
std::vector<Test::Result> Test::flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists) {
4✔
732
   std::vector<Test::Result> results;
4✔
733
   for(auto& result_list : result_lists) {
26✔
734
      for(auto& result : result_list) {
71✔
735
         results.emplace_back(std::move(result));
49✔
736
      }
737
   }
738
   return results;
4✔
739
}
×
740

741
//static
742
std::vector<std::string> Test::registered_tests() {
×
743
   return Test_Registry::instance().registered_tests();
×
744
}
745

746
//static
747
std::vector<std::string> Test::registered_test_categories() {
×
748
   return Test_Registry::instance().registered_test_categories();
×
749
}
750

751
//static
752
std::unique_ptr<Test> Test::get_test(const std::string& test_name) {
419✔
753
   return Test_Registry::instance().get_test(test_name);
419✔
754
}
755

756
//static
757
bool Test::test_needs_serialization(const std::string& test_name) {
419✔
758
   return Test_Registry::instance().needs_serialization(test_name);
419✔
759
}
760

761
//static
762
std::vector<std::string> Test::filter_registered_tests(const std::vector<std::string>& requested,
1✔
763
                                                       const std::vector<std::string>& to_be_skipped) {
764
   return Test_Registry::instance().filter_registered_tests(requested, to_be_skipped);
1✔
765
}
766

767
//static
768
std::string Test::temp_file_name(const std::string& basename) {
21✔
769
   // TODO add a --tmp-dir option to the tests to specify where these files go
770

771
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
772

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

776
   const int fd = ::mkstemp(mkstemp_basename.data());
21✔
777

778
   // error
779
   if(fd < 0) {
21✔
780
      return "";
×
781
   }
782

783
   ::close(fd);
21✔
784

785
   return mkstemp_basename;
21✔
786
#else
787
   // For now just create the temp in the current working directory
788
   return basename;
789
#endif
790
}
21✔
791

792
bool Test::copy_file(const std::string& from, const std::string& to) {
1✔
793
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(__cpp_lib_filesystem)
794
   std::error_code ec;  // don't throw, just return false on error
1✔
795
   return std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
1✔
796
#else
797
   // TODO: implement fallbacks to POSIX or WIN32
798
   // ... but then again: it's 2023 and we're using C++20 :o)
799
   BOTAN_UNUSED(from, to);
800
   throw Botan::No_Filesystem_Access();
801
#endif
802
}
803

804
std::string Test::read_data_file(const std::string& path) {
38✔
805
   const std::string fsname = Test::data_file(path);
38✔
806
   std::ifstream file(fsname.c_str());
38✔
807
   if(!file.good()) {
38✔
808
      throw Test_Error("Error reading from " + fsname);
×
809
   }
810

811
   return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
76✔
812
}
38✔
813

814
std::vector<uint8_t> Test::read_binary_data_file(const std::string& path) {
34✔
815
   const std::string fsname = Test::data_file(path);
34✔
816
   std::ifstream file(fsname.c_str(), std::ios::binary);
34✔
817
   if(!file.good()) {
34✔
818
      throw Test_Error("Error reading from " + fsname);
×
819
   }
820

821
   std::vector<uint8_t> contents;
34✔
822

823
   while(file.good()) {
74✔
824
      std::vector<uint8_t> buf(4096);
40✔
825
      file.read(reinterpret_cast<char*>(buf.data()), buf.size());
40✔
826
      const size_t got = static_cast<size_t>(file.gcount());
40✔
827

828
      if(got == 0 && file.eof()) {
40✔
829
         break;
830
      }
831

832
      contents.insert(contents.end(), buf.data(), buf.data() + got);
40✔
833
   }
40✔
834

835
   return contents;
68✔
836
}
34✔
837

838
// static member variables of Test
839

840
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
841
Test_Options Test::m_opts;
842
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
843
std::string Test::m_test_rng_seed;
844

845
//static
846
void Test::set_test_options(const Test_Options& opts) {
1✔
847
   m_opts = opts;
1✔
848
}
1✔
849

850
namespace {
851

852
/*
853
* This is a fast, simple, deterministic PRNG that's used for running
854
* the tests. It is not intended to be cryptographically secure.
855
*/
856
class Testsuite_RNG final : public Botan::RandomNumberGenerator {
8✔
857
   public:
858
      std::string name() const override { return "Testsuite_RNG"; }
×
859

860
      void clear() override { m_x = 0; }
×
861

862
      bool accepts_input() const override { return true; }
×
863

864
      bool is_seeded() const override { return true; }
276,302✔
865

866
      void fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) override {
10,314,155✔
867
         for(const auto byte : input) {
10,314,155✔
868
            mix(byte);
×
869
         }
870

871
         for(auto& byte : output) {
73,266,031✔
872
            byte = mix();
62,951,876✔
873
         }
874
      }
10,314,155✔
875

876
      Testsuite_RNG(std::string_view seed, std::string_view test_name) : m_x(0) {
276✔
877
         for(const char c : seed) {
8,280✔
878
            this->mix(static_cast<uint8_t>(c));
8,004✔
879
         }
880
         for(const char c : test_name) {
5,578✔
881
            this->mix(static_cast<uint8_t>(c));
5,302✔
882
         }
883
      }
276✔
884

885
   private:
886
      uint8_t mix(uint8_t input = 0) {
62,965,182✔
887
         m_x ^= input;
62,965,182✔
888
         m_x *= 0xF2E16957;
62,965,182✔
889
         m_x += 0xE50B590F;
62,965,182✔
890
         return static_cast<uint8_t>(m_x >> 27);
62,965,182✔
891
      }
892

893
      uint64_t m_x;
894
};
895

896
}  // namespace
897

898
//static
899
void Test::set_test_rng_seed(std::span<const uint8_t> seed, size_t epoch) {
1✔
900
   m_test_rng_seed = Botan::fmt("seed={} epoch={}", Botan::hex_encode(seed), epoch);
1✔
901
}
1✔
902

903
//static
904
std::unique_ptr<Botan::RandomNumberGenerator> Test::new_rng(std::string_view test_name) {
268✔
905
   return std::make_unique<Testsuite_RNG>(m_test_rng_seed, test_name);
268✔
906
}
907

908
//static
909
std::shared_ptr<Botan::RandomNumberGenerator> Test::new_shared_rng(std::string_view test_name) {
8✔
910
   return std::make_shared<Testsuite_RNG>(m_test_rng_seed, test_name);
8✔
911
}
912

913
//static
914
std::string Test::data_file(const std::string& file) {
773✔
915
   return options().data_dir() + "/" + file;
1,546✔
916
}
917

918
//static
919
std::string Test::data_dir(const std::string& subdir) {
1✔
920
   return options().data_dir() + "/" + subdir;
2✔
921
}
922

923
//static
924
std::vector<std::string> Test::files_in_data_dir(const std::string& subdir) {
393✔
925
   auto fs = Botan::get_files_recursive(options().data_dir() + "/" + subdir);
1,179✔
926
   if(fs.empty()) {
393✔
927
      throw Test_Error("Test::files_in_data_dir encountered empty subdir " + subdir);
×
928
   }
929
   return fs;
393✔
930
}
×
931

932
//static
933
std::string Test::data_file_as_temporary_copy(const std::string& what) {
1✔
934
   auto tmp_basename = what;
1✔
935
   std::replace(tmp_basename.begin(), tmp_basename.end(), '/', '_');
1✔
936
   auto temp_file = temp_file_name("tmp-" + tmp_basename);
1✔
937
   if(temp_file.empty()) {
1✔
938
      return "";
×
939
   }
940
   if(!Test::copy_file(data_file(what), temp_file)) {
1✔
941
      return "";
×
942
   }
943
   return temp_file;
1✔
944
}
1✔
945

946
//static
947
std::vector<std::string> Test::provider_filter(const std::vector<std::string>& providers) {
49,022✔
948
   if(m_opts.provider().empty()) {
49,022✔
949
      return providers;
49,022✔
950
   }
951
   for(auto&& provider : providers) {
×
952
      if(provider == m_opts.provider()) {
×
953
         return std::vector<std::string>{provider};
×
954
      }
955
   }
956
   return std::vector<std::string>{};
×
957
}
×
958

959
std::string Test::random_password(Botan::RandomNumberGenerator& rng) {
222✔
960
   const size_t len = 1 + rng.next_byte() % 32;
222✔
961
   return Botan::hex_encode(rng.random_vec(len));
444✔
962
}
963

964
size_t Test::random_index(Botan::RandomNumberGenerator& rng, size_t max) {
8,062✔
965
   return Botan::load_be(rng.random_array<8>()) % max;
8,062✔
966
}
967

968
void VarMap::clear() {
34,281✔
969
   m_vars.clear();
×
970
}
×
971

972
namespace {
973

974
bool varmap_pair_lt(const std::pair<std::string, std::string>& kv, const std::string& k) {
1,713,618✔
975
   return kv.first < k;
1,713,618✔
976
}
977

978
}  // namespace
979

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

983
   if(i != m_vars.end() && i->first == key) {
156,235✔
984
      i->second = value;
44,405✔
985
   } else {
986
      m_vars.emplace(i, key, value);
111,830✔
987
   }
988
}
156,235✔
989

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

993
   if(i != m_vars.end() && i->first == key) {
568,446✔
994
      return i->second;
498,591✔
995
   } else {
996
      return {};
69,855✔
997
   }
998
}
999

1000
bool VarMap::has_key(const std::string& key) const {
213,574✔
1001
   return get_var(key).has_value();
213,574✔
1002
}
1003

1004
std::string VarMap::get_req_str(const std::string& key) const {
259,629✔
1005
   auto var = get_var(key);
259,629✔
1006
   if(var) {
259,629✔
1007
      return *var;
519,258✔
1008
   } else {
1009
      throw Test_Error("Test missing variable " + key);
×
1010
   }
1011
}
259,629✔
1012

1013
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(const std::string& key) const {
12✔
1014
   const auto var = get_req_str(key);
12✔
1015

1016
   std::vector<std::vector<uint8_t>> bin_list;
12✔
1017

1018
   for(auto&& part : Botan::split_on(var, ',')) {
62✔
1019
      try {
50✔
1020
         bin_list.push_back(Botan::hex_decode(part));
100✔
1021
      } catch(std::exception& e) {
×
1022
         std::ostringstream oss;
×
1023
         oss << "Bad input '" << part << "'"
×
1024
             << " in binary list key " << key << " - " << e.what();
×
1025
         throw Test_Error(oss.str());
×
1026
      }
×
1027
   }
12✔
1028

1029
   return bin_list;
12✔
1030
}
12✔
1031

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

1035
   try {
163,711✔
1036
      if(var.starts_with("0x")) {
163,711✔
1037
         if(var.size() % 2 == 0) {
×
1038
            return Botan::hex_decode(var.substr(2));
×
1039
         } else {
1040
            std::string z = var;
×
1041
            std::swap(z[0], z[1]);  // swap 0x to x0 then remove x
×
1042
            return Botan::hex_decode(z.substr(1));
×
1043
         }
×
1044
      } else {
1045
         return Botan::hex_decode(var);
163,711✔
1046
      }
1047
   } catch(std::exception& e) {
×
1048
      std::ostringstream oss;
×
1049
      oss << "Bad input '" << var << "'"
×
1050
          << " for key " << key << " - " << e.what();
×
1051
      throw Test_Error(oss.str());
×
1052
   }
×
1053
}
163,711✔
1054

1055
std::string VarMap::get_opt_str(const std::string& key, const std::string& def_value) const {
14,378✔
1056
   if(auto v = get_var(key)) {
14,378✔
1057
      return *v;
57✔
1058
   } else {
1059
      return def_value;
28,699✔
1060
   }
14,378✔
1061
}
1062

1063
bool VarMap::get_req_bool(const std::string& key) const {
39✔
1064
   const auto var = get_req_str(key);
39✔
1065

1066
   if(var == "true") {
39✔
1067
      return true;
1068
   } else if(var == "false") {
23✔
1069
      return false;
1070
   } else {
1071
      throw Test_Error("Invalid boolean for key '" + key + "' value '" + var + "'");
×
1072
   }
1073
}
39✔
1074

1075
size_t VarMap::get_req_sz(const std::string& key) const {
4,547✔
1076
   return Botan::to_u32bit(get_req_str(key));
4,547✔
1077
}
1078

1079
uint8_t VarMap::get_req_u8(const std::string& key) const {
17✔
1080
   const size_t s = this->get_req_sz(key);
17✔
1081
   if(s > 256) {
17✔
1082
      throw Test_Error("Invalid " + key + " expected uint8_t got " + std::to_string(s));
×
1083
   }
1084
   return static_cast<uint8_t>(s);
17✔
1085
}
1086

1087
uint32_t VarMap::get_req_u32(const std::string& key) const {
14✔
1088
   return static_cast<uint32_t>(get_req_sz(key));
14✔
1089
}
1090

1091
uint64_t VarMap::get_req_u64(const std::string& key) const {
17✔
1092
   const auto var = get_req_str(key);
17✔
1093
   try {
17✔
1094
      return std::stoull(var);
17✔
1095
   } catch(std::exception&) {
×
1096
      throw Test_Error("Invalid u64 value '" + var + "'");
×
1097
   }
×
1098
}
17✔
1099

1100
size_t VarMap::get_opt_sz(const std::string& key, const size_t def_value) const {
31,379✔
1101
   if(auto v = get_var(key)) {
31,379✔
1102
      return Botan::to_u32bit(*v);
12,244✔
1103
   } else {
1104
      return def_value;
1105
   }
31,379✔
1106
}
1107

1108
uint64_t VarMap::get_opt_u64(const std::string& key, const uint64_t def_value) const {
3,538✔
1109
   if(auto v = get_var(key)) {
3,538✔
1110
      try {
641✔
1111
         return std::stoull(*v);
3,538✔
1112
      } catch(std::exception&) {
×
1113
         throw Test_Error("Invalid u64 value '" + *v + "'");
×
1114
      }
×
1115
   } else {
1116
      return def_value;
1117
   }
3,538✔
1118
}
×
1119

1120
std::vector<uint8_t> VarMap::get_opt_bin(const std::string& key) const {
45,868✔
1121
   if(auto v = get_var(key)) {
45,868✔
1122
      try {
16,134✔
1123
         return Botan::hex_decode(*v);
16,134✔
1124
      } catch(std::exception&) {
×
1125
         throw Test_Error("Test invalid hex input '" + *v + "'" + +" for key " + key);
×
1126
      }
×
1127
   } else {
1128
      return {};
29,734✔
1129
   };
45,868✔
1130
}
×
1131

1132
#if defined(BOTAN_HAS_BIGINT)
1133
Botan::BigInt VarMap::get_req_bn(const std::string& key) const {
38,502✔
1134
   const auto var = get_req_str(key);
38,502✔
1135

1136
   try {
38,502✔
1137
      return Botan::BigInt(var);
38,502✔
1138
   } catch(std::exception&) {
×
1139
      throw Test_Error("Test invalid bigint input '" + var + "' for key " + key);
×
1140
   }
×
1141
}
38,502✔
1142

1143
Botan::BigInt VarMap::get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const {
80✔
1144
   if(auto v = get_var(key)) {
80✔
1145
      try {
56✔
1146
         return Botan::BigInt(*v);
56✔
1147
      } catch(std::exception&) {
×
1148
         throw Test_Error("Test invalid bigint input '" + *v + "' for key " + key);
×
1149
      }
×
1150
   } else {
1151
      return def_value;
24✔
1152
   }
80✔
1153
}
×
1154
#endif
1155

1156
class Text_Based_Test::Text_Based_Test_Data {
1157
   public:
1158
      Text_Based_Test_Data(const std::string& data_src,
181✔
1159
                           const std::string& required_keys_str,
1160
                           const std::string& optional_keys_str) :
181✔
1161
            m_data_src(data_src) {
362✔
1162
         if(required_keys_str.empty()) {
181✔
1163
            throw Test_Error("Invalid test spec");
×
1164
         }
1165

1166
         m_required_keys = Botan::split_on(required_keys_str, ',');
181✔
1167
         std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
181✔
1168

1169
         m_all_keys.insert(m_required_keys.begin(), m_required_keys.end());
181✔
1170
         m_all_keys.insert(optional_keys.begin(), optional_keys.end());
181✔
1171
         m_output_key = m_required_keys.at(m_required_keys.size() - 1);
181✔
1172
      }
181✔
1173

1174
      std::string get_next_line();
1175

1176
      const std::string& current_source_name() const { return m_cur_src_name; }
×
1177

1178
      bool known_key(const std::string& key) const;
1179

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

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

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

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

1188
      const std::string& initial_data_src_name() const { return m_data_src; }
181✔
1189

1190
   private:
1191
      std::string m_data_src;
1192
      std::vector<std::string> m_required_keys;
1193
      std::unordered_set<std::string> m_all_keys;
1194
      std::string m_output_key;
1195

1196
      bool m_first = true;
1197
      std::unique_ptr<std::istream> m_cur;
1198
      std::string m_cur_src_name;
1199
      std::deque<std::string> m_srcs;
1200
      std::vector<std::string> m_cpu_flags;
1201
};
1202

1203
Text_Based_Test::Text_Based_Test(const std::string& data_src,
181✔
1204
                                 const std::string& required_keys,
1205
                                 const std::string& optional_keys) :
181✔
1206
      m_data(std::make_unique<Text_Based_Test_Data>(data_src, required_keys, optional_keys)) {}
181✔
1207

1208
Text_Based_Test::~Text_Based_Test() = default;
181✔
1209

1210
std::string Text_Based_Test::Text_Based_Test_Data::get_next_line() {
157,242✔
1211
   while(true) {
157,500✔
1212
      if(m_cur == nullptr || m_cur->good() == false) {
157,500✔
1213
         if(m_srcs.empty()) {
450✔
1214
            if(m_first) {
362✔
1215
               if(m_data_src.ends_with(".vec")) {
181✔
1216
                  m_srcs.push_back(Test::data_file(m_data_src));
338✔
1217
               } else {
1218
                  const auto fs = Test::files_in_data_dir(m_data_src);
12✔
1219
                  m_srcs.assign(fs.begin(), fs.end());
12✔
1220
                  if(m_srcs.empty()) {
12✔
1221
                     throw Test_Error("Error reading test data dir " + m_data_src);
×
1222
                  }
1223
               }
12✔
1224

1225
               m_first = false;
181✔
1226
            } else {
1227
               return "";  // done
181✔
1228
            }
1229
         }
1230

1231
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
357✔
1232
         m_cur_src_name = m_srcs[0];
269✔
1233

1234
#if defined(BOTAN_HAS_CPUID)
1235
         // Reinit cpuid on new file if needed
1236
         if(m_cpu_flags.empty() == false) {
269✔
1237
            m_cpu_flags.clear();
19✔
1238
            Botan::CPUID::initialize();
19✔
1239
         }
1240
#endif
1241

1242
         if(!m_cur->good()) {
269✔
1243
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
1244
         }
1245

1246
         m_srcs.pop_front();
269✔
1247
      }
1248

1249
      while(m_cur->good()) {
227,897✔
1250
         std::string line;
227,639✔
1251
         std::getline(*m_cur, line);
227,639✔
1252

1253
         if(line.empty()) {
227,639✔
1254
            continue;
55,310✔
1255
         }
1256

1257
         if(line[0] == '#') {
172,329✔
1258
            if(line.starts_with("#test ")) {
15,289✔
1259
               return line;
21✔
1260
            } else {
1261
               continue;
15,268✔
1262
            }
1263
         }
1264

1265
         return line;
157,040✔
1266
      }
227,639✔
1267
   }
1268
}
1269

1270
bool Text_Based_Test::Text_Based_Test_Data::known_key(const std::string& key) const {
156,235✔
1271
   return m_all_keys.contains(key);
156,235✔
1272
}
1273

1274
namespace {
1275

1276
// strips leading and trailing but not internal whitespace
1277
std::string strip_ws(const std::string& in) {
312,470✔
1278
   const char* whitespace = " ";
312,470✔
1279

1280
   const auto first_c = in.find_first_not_of(whitespace);
312,470✔
1281
   if(first_c == std::string::npos) {
312,470✔
1282
      return "";
1,033✔
1283
   }
1284

1285
   const auto last_c = in.find_last_not_of(whitespace);
311,437✔
1286

1287
   return in.substr(first_c, last_c - first_c + 1);
311,437✔
1288
}
1289

1290
std::vector<std::string> parse_cpuid_bits(const std::vector<std::string>& tok) {
21✔
1291
   std::vector<std::string> bits;
21✔
1292

1293
#if defined(BOTAN_HAS_CPUID)
1294
   for(size_t i = 1; i < tok.size(); ++i) {
106✔
1295
      if(auto bit = Botan::CPUID::bit_from_string(tok[i])) {
85✔
1296
         bits.push_back(bit->to_string());
98✔
1297
      }
1298
   }
1299
#else
1300
   BOTAN_UNUSED(tok);
1301
#endif
1302

1303
   return bits;
21✔
1304
}
×
1305

1306
}  // namespace
1307

1308
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) {
32,609✔
1309
   return false;
32,609✔
1310
}
1311

1312
std::vector<Test::Result> Text_Based_Test::run() {
181✔
1313
   std::vector<Test::Result> results;
181✔
1314

1315
   std::string header;
181✔
1316
   std::string header_or_name = m_data->initial_data_src_name();
181✔
1317
   VarMap vars;
181✔
1318
   size_t test_cnt = 0;
181✔
1319

1320
   while(true) {
157,242✔
1321
      const std::string line = m_data->get_next_line();
157,242✔
1322
      if(line.empty()) {
157,242✔
1323
         // EOF
1324
         break;
1325
      }
1326

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

1330
         if(pragma_tokens.empty()) {
21✔
1331
            throw Test_Error("Empty pragma found in " + m_data->current_source_name());
×
1332
         }
1333

1334
         if(pragma_tokens[0] != "cpuid") {
21✔
1335
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1336
         }
1337

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

1342
         m_data->set_cpu_flags(parse_cpuid_bits(pragma_tokens));
42✔
1343

1344
         continue;
21✔
1345
      } else if(line[0] == '#') {
157,061✔
1346
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1347
      }
1348

1349
      if(line[0] == '[' && line[line.size() - 1] == ']') {
157,040✔
1350
         header = line.substr(1, line.size() - 2);
805✔
1351
         header_or_name = header;
805✔
1352
         test_cnt = 0;
805✔
1353
         vars.clear();
805✔
1354
         continue;
805✔
1355
      }
1356

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

1359
      auto equal_i = line.find_first_of('=');
156,235✔
1360

1361
      if(equal_i == std::string::npos) {
156,235✔
1362
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1363
         continue;
×
1364
      }
1365

1366
      const std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
312,470✔
1367
      const std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
312,470✔
1368

1369
      if(!m_data->known_key(key)) {
156,235✔
1370
         auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key));
×
1371
         results.push_back(r);
×
1372
      }
×
1373

1374
      vars.add(key, val);
156,235✔
1375

1376
      if(key == m_data->output_key()) {
156,235✔
1377
         try {
48,388✔
1378
            for(const auto& req_key : m_data->required_keys()) {
245,554✔
1379
               if(!vars.has_key(req_key)) {
197,166✔
1380
                  auto r =
×
1381
                     Test::Result::Failure(header_or_name, Botan::fmt("{} missing required key {}", test_id, req_key));
×
1382
                  results.push_back(r);
×
1383
               }
×
1384
            }
1385

1386
            if(skip_this_test(header, vars)) {
48,388✔
1387
               continue;
139✔
1388
            }
1389

1390
            ++test_cnt;
48,249✔
1391

1392
            const uint64_t start = Test::timestamp();
48,249✔
1393

1394
            Test::Result result = run_one_test(header, vars);
48,249✔
1395
#if defined(BOTAN_HAS_CPUID)
1396
            if(!m_data->cpu_flags().empty()) {
48,249✔
1397
               for(const auto& cpuid_str : m_data->cpu_flags()) {
30,621✔
1398
                  if(const auto bit = Botan::CPUID::Feature::from_string(cpuid_str)) {
21,677✔
1399
                     if(Botan::CPUID::has(*bit)) {
21,677✔
1400
                        Botan::CPUID::clear_cpuid_bit(*bit);
16,577✔
1401
                        // now re-run the test
1402
                        result.merge(run_one_test(header, vars));
16,577✔
1403
                     }
1404
                  }
1405
               }
1406
               Botan::CPUID::initialize();
8,944✔
1407
            }
1408
#endif
1409
            result.set_ns_consumed(Test::timestamp() - start);
48,249✔
1410

1411
            if(result.tests_failed() > 0) {
48,249✔
1412
               std::ostringstream oss;
×
1413
               oss << "Test # " << test_cnt << " ";
×
1414
               if(!header.empty()) {
×
1415
                  oss << header << " ";
×
1416
               }
1417
               oss << "failed ";
×
1418

1419
               for(const auto& k : m_data->required_keys()) {
×
1420
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1421
               }
1422

1423
               result.test_note(oss.str());
×
1424
            }
×
1425
            results.push_back(result);
48,249✔
1426
         } catch(std::exception& e) {
48,249✔
1427
            std::ostringstream oss;
×
1428
            oss << "Test # " << test_cnt << " ";
×
1429
            if(!header.empty()) {
×
1430
               oss << header << " ";
×
1431
            }
1432

1433
            for(const auto& k : m_data->required_keys()) {
×
1434
               oss << k << "=" << vars.get_req_str(k) << " ";
×
1435
            }
1436

1437
            oss << "failed with exception '" << e.what() << "'";
×
1438

1439
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1440
         }
×
1441

1442
         if(clear_between_callbacks()) {
48,249✔
1443
            vars.clear();
189,572✔
1444
         }
1445
      }
1446
   }
157,339✔
1447

1448
   if(results.empty()) {
181✔
1449
      return results;
1450
   }
1451

1452
   try {
181✔
1453
      std::vector<Test::Result> final_tests = run_final_tests();
181✔
1454
      results.insert(results.end(), final_tests.begin(), final_tests.end());
181✔
1455
   } catch(std::exception& e) {
181✔
1456
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1457
   }
×
1458

1459
   return results;
1460
}
181✔
1461

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