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

randombit / botan / 22020292790

14 Feb 2026 04:03PM UTC coverage: 90.067% (+0.008%) from 90.059%
22020292790

push

github

web-flow
Merge pull request #5330 from randombit/jack/tests-no-assert

Avoid including assert.h into tests.h

102241 of 113517 relevant lines covered (90.07%)

11570076.55 hits per line

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

79.95
/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,238✔
198
   if(Test::options().log_success()) {
3,620,213✔
199
      test_note(note);
×
200
   }
201
   ++m_tests_passed;
3,620,238✔
202
   return true;
397,238✔
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,414✔
229
   return (len == 0) ? true : std::memcmp(x, y, len) == 0;
290,983✔
230
}
231

232
}  // namespace
233

234
bool Test::Result::test_ne(std::string_view what,
3,405✔
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,405✔
240
      return test_failure(Botan::fmt("{} {} produced matching bytes", who(), what));
4✔
241
   }
242
   return test_success();
3,403✔
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) {
30✔
306
   return test_is_eq(what, std::string(produced), std::string(expected));
30✔
307
}
308

309
bool Test::Result::test_u8_eq(uint8_t produced, uint8_t expected) {
214✔
310
   return test_sz_eq("comparison", produced, expected);
214✔
311
}
312

313
bool Test::Result::test_u8_eq(std::string_view what, uint8_t produced, uint8_t expected) {
46,561✔
314
   return test_sz_eq(what, produced, expected);
46,561✔
315
}
316

317
bool Test::Result::test_u16_eq(uint16_t produced, uint16_t expected) {
36✔
318
   return test_sz_eq("comparison", produced, expected);
36✔
319
}
320

321
bool Test::Result::test_u16_eq(std::string_view what, uint16_t produced, uint16_t expected) {
65,560✔
322
   return test_sz_eq(what, produced, expected);
65,560✔
323
}
324

325
bool Test::Result::test_u32_eq(uint32_t produced, uint32_t expected) {
12✔
326
   return test_sz_eq("comparison", produced, expected);
12✔
327
}
328

329
bool Test::Result::test_u32_eq(std::string_view what, uint32_t produced, uint32_t expected) {
4,136✔
330
   return test_sz_eq(what, produced, expected);
4,136✔
331
}
332

333
bool Test::Result::test_u64_eq(uint64_t produced, uint64_t expected) {
8✔
334
   return test_u64_eq("comparison", produced, expected);
8✔
335
}
336

337
bool Test::Result::test_u64_eq(std::string_view what, uint64_t produced, uint64_t expected) {
1,238✔
338
   if(produced == expected) {
1,238✔
339
      return test_success();
1,238✔
340
   } else {
341
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} == {}", who(), what, produced, expected));
×
342
   }
343
}
344

345
bool Test::Result::test_sz_eq(std::string_view what, size_t produced, size_t expected) {
192,813✔
346
   if(produced == expected) {
192,813✔
347
      return test_success();
192,812✔
348
   } else {
349
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} == {}", who(), what, produced, expected));
1✔
350
   }
351
}
352

353
bool Test::Result::test_sz_ne(std::string_view what, size_t produced, size_t expected) {
119✔
354
   if(produced != expected) {
119✔
355
      return test_success();
118✔
356
   } else {
357
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} != {}", who(), what, produced, expected));
1✔
358
   }
359
}
360

361
bool Test::Result::test_sz_lt(std::string_view what, size_t produced, size_t expected) {
5,639✔
362
   if(produced < expected) {
5,639✔
363
      return test_success();
5,638✔
364
   } else {
365
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} < {}", who(), what, produced, expected));
1✔
366
   }
367
}
368

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

377
bool Test::Result::test_sz_gt(std::string_view what, size_t produced, size_t expected) {
22,373✔
378
   if(produced > expected) {
22,373✔
379
      return test_success();
22,373✔
380
   } else {
381
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} > {}", who(), what, produced, expected));
×
382
   }
383
}
384

385
bool Test::Result::test_sz_gte(std::string_view what, size_t produced, size_t expected) {
1,142,430✔
386
   if(produced >= expected) {
1,142,430✔
387
      return test_success();
1,142,429✔
388
   } else {
389
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} >= {}", who(), what, produced, expected));
1✔
390
   }
391
}
392

393
bool Test::Result::test_ne(std::string_view what, std::string_view str1, std::string_view str2) {
26✔
394
   if(str1 != str2) {
26✔
395
      return test_success(Botan::fmt("{} != {}", str1, str2));
25✔
396
   } else {
397
      return test_failure(Botan::fmt("{} {} unexpectedly produced matching strings {}", who(), what, str1));
1✔
398
   }
399
}
400

401
#if defined(BOTAN_HAS_BIGINT)
402
bool Test::Result::test_eq(std::string_view what, const BigInt& produced, const BigInt& expected) {
252,650✔
403
   return test_is_eq(what, produced, expected);
252,650✔
404
}
405

406
bool Test::Result::test_ne(std::string_view what, const BigInt& produced, const BigInt& expected) {
97✔
407
   if(produced != expected) {
97✔
408
      return test_success();
96✔
409
   }
410

411
   std::ostringstream err;
1✔
412
   err << who() << " " << what << " produced " << produced << " prohibited value";
1✔
413
   return test_failure(err.str());
1✔
414
}
1✔
415
#endif
416

417
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
418
bool Test::Result::test_eq(std::string_view what, const Botan::EC_Point& a, const Botan::EC_Point& b) {
3,248✔
419
   //return test_is_eq(what, a, b);
420
   if(a == b) {
3,248✔
421
      return test_success();
3,248✔
422
   }
423

424
   std::ostringstream err;
×
425
   err << who() << " " << what << " a=(" << a.get_affine_x() << "," << a.get_affine_y() << ")"
×
426
       << " b=(" << b.get_affine_x() << "," << b.get_affine_y();
×
427
   return test_failure(err.str());
×
428
}
×
429
#endif
430

431
bool Test::Result::test_bool_eq(std::string_view what, bool produced, bool expected) {
378,453✔
432
   if(produced == expected) {
378,453✔
433
      return test_success();
378,453✔
434
   } else {
435
      if(expected == true) {
×
436
         return test_failure(Botan::fmt("Assertion failure in {}, {} was unexpectedly false", who(), what));
×
437
      } else {
438
         return test_failure(Botan::fmt("Assertion failure in {}, {} was unexpectedly true", who(), what));
×
439
      }
440
   }
441
}
442

443
bool Test::Result::test_is_true(std::string_view what, bool produced) {
74,923✔
444
   return test_bool_eq(what, produced, true);
74,923✔
445
}
446

447
bool Test::Result::test_is_false(std::string_view what, bool produced) {
125,665✔
448
   return test_bool_eq(what, produced, false);
125,665✔
449
}
450

451
bool Test::Result::test_rc_ok(std::string_view func, int rc) {
2,810✔
452
   if(rc != 0) {
2,810✔
453
      std::ostringstream err;
1✔
454
      err << m_who << " " << func << " unexpectedly failed with error code " << rc;
1✔
455
      return test_failure(err.str());
1✔
456
   }
1✔
457

458
   return test_success();
2,809✔
459
}
460

461
bool Test::Result::test_rc_fail(std::string_view func, std::string_view why, int rc) {
26✔
462
   if(rc == 0) {
26✔
463
      std::ostringstream err;
1✔
464
      err << m_who << " call to " << func << " unexpectedly succeeded expecting failure because " << why;
1✔
465
      return test_failure(err.str());
1✔
466
   }
1✔
467

468
   return test_success();
25✔
469
}
470

471
bool Test::Result::test_rc_init(std::string_view func, int rc) {
117✔
472
   if(rc == 0) {
117✔
473
      return test_success();
117✔
474
   } else {
475
      std::ostringstream msg;
×
476
      msg << m_who;
×
477
      msg << " " << func;
×
478

479
      // -40 is BOTAN_FFI_ERROR_NOT_IMPLEMENTED
480
      if(rc == -40) {
×
481
         msg << " returned not implemented";
×
482
      } else {
483
         msg << " unexpectedly failed with error code " << rc;
×
484
      }
485

486
      if(rc == -40) {
×
487
         this->test_note(msg.str());
×
488
      } else {
489
         this->test_failure(msg.str());
×
490
      }
491
      return false;
×
492
   }
×
493
}
494

495
bool Test::Result::test_rc(std::string_view func, int expected, int rc) {
416✔
496
   if(expected != rc) {
416✔
497
      std::ostringstream err;
1✔
498
      err << m_who;
1✔
499
      err << " call to " << func << " unexpectedly returned " << rc;
1✔
500
      err << " but expecting " << expected;
1✔
501
      return test_failure(err.str());
1✔
502
   }
1✔
503

504
   return test_success();
415✔
505
}
506

507
void Test::initialize(std::string test_name, CodeLocation location) {
419✔
508
   m_test_name = std::move(test_name);
419✔
509
   m_registration_location = location;
419✔
510
}
419✔
511

512
Botan::RandomNumberGenerator& Test::rng() const {
460,459✔
513
   if(!m_test_rng) {
460,459✔
514
      m_test_rng = Test::new_rng(m_test_name);
145✔
515
   }
516

517
   return *m_test_rng;
460,459✔
518
}
519

520
std::optional<std::string> Test::supported_ec_group_name(std::vector<std::string> preferred_groups) {
151✔
521
#if defined(BOTAN_HAS_ECC_GROUP)
522
   if(preferred_groups.empty()) {
151✔
523
      preferred_groups = {
149✔
524
         "secp256r1",
525
         "brainpool256r1",
526
         "secp384r1",
527
         "brainpool384r1",
528
         "secp521r1",
529
         "brainpool512r1",
530
      };
1,192✔
531
   }
532

533
   for(const auto& group : preferred_groups) {
151✔
534
      if(Botan::EC_Group::supports_named_group(group)) {
151✔
535
         return group;
151✔
536
      }
537
   }
538
#else
539
   BOTAN_UNUSED(preferred_groups);
540
#endif
541

542
   return std::nullopt;
×
543
}
298✔
544

545
std::vector<uint8_t> Test::mutate_vec(const std::vector<uint8_t>& v,
96,742✔
546
                                      Botan::RandomNumberGenerator& rng,
547
                                      bool maybe_resize,
548
                                      size_t min_offset) {
549
   std::vector<uint8_t> r = v;
96,742✔
550

551
   if(maybe_resize && (r.empty() || rng.next_byte() < 32)) {
110,314✔
552
      // TODO: occasionally truncate, insert at random index
553
      const size_t add = 1 + (rng.next_byte() % 16);
2,183✔
554
      r.resize(r.size() + add);
2,183✔
555
      rng.randomize(&r[r.size() - add], add);
2,183✔
556
   }
557

558
   if(r.size() > min_offset) {
96,742✔
559
      const size_t offset = std::max<size_t>(min_offset, rng.next_byte() % r.size());
95,204✔
560
      const uint8_t perturb = rng.next_nonzero_byte();
95,204✔
561
      r[offset] ^= perturb;
95,204✔
562
   }
563

564
   return r;
96,742✔
565
}
×
566

567
std::vector<std::string> Test::possible_providers(const std::string& /*alg*/) {
×
568
   return Test::provider_filter({"base"});
×
569
}
570

571
//static
572
std::string Test::format_time(uint64_t nanoseconds) {
1,470✔
573
   std::ostringstream o;
1,470✔
574

575
   if(nanoseconds > 1000000000) {
1,470✔
576
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000000.0 << " sec";
151✔
577
   } else {
578
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000.0 << " msec";
1,319✔
579
   }
580

581
   return o.str();
2,940✔
582
}
1,470✔
583

584
// TODO: this should move to `StdoutReporter`
585
std::string Test::Result::result_string() const {
2,541✔
586
   const bool verbose = Test::options().verbose();
2,541✔
587

588
   if(tests_run() == 0 && !verbose) {
2,541✔
589
      return "";
20✔
590
   }
591

592
   std::ostringstream report;
2,521✔
593

594
   report << who() << " ran ";
2,521✔
595

596
   if(tests_run() == 0) {
2,521✔
597
      report << "ZERO";
×
598
   } else {
599
      report << tests_run();
2,521✔
600
   }
601
   report << " tests";
2,521✔
602

603
   if(m_ns_taken > 0) {
2,521✔
604
      report << " in " << format_time(m_ns_taken);
2,938✔
605
   }
606

607
   if(tests_failed() > 0) {
2,521✔
608
      report << " " << tests_failed() << " FAILED";
25✔
609
   } else {
610
      report << " all ok";
2,496✔
611
   }
612

613
   report << "\n";
2,521✔
614

615
   for(size_t i = 0; i != m_fail_log.size(); ++i) {
2,546✔
616
      report << "Failure " << (i + 1) << ": " << m_fail_log[i];
25✔
617
      if(m_where) {
25✔
618
         report << " (at " << m_where->path << ":" << m_where->line << ")";
×
619
      }
620
      report << "\n";
25✔
621
   }
622

623
   if(!m_fail_log.empty() || tests_run() == 0 || verbose) {
2,521✔
624
      for(size_t i = 0; i != m_log.size(); ++i) {
25✔
625
         report << "Note " << (i + 1) << ": " << m_log[i] << "\n";
×
626
      }
627
   }
628

629
   return report.str();
2,521✔
630
}
2,521✔
631

632
namespace {
633

634
class Test_Registry {
635
   public:
636
      static Test_Registry& instance() {
1,279✔
637
         static Test_Registry registry;
1,280✔
638
         return registry;
1,279✔
639
      }
640

641
      void register_test(const std::string& category,
419✔
642
                         const std::string& name,
643
                         bool smoke_test,
644
                         bool needs_serialization,
645
                         std::function<std::unique_ptr<Test>()> maker_fn) {
646
         if(m_tests.contains(name)) {
419✔
647
            throw Test_Error("Duplicate registration of test '" + name + "'");
×
648
         }
649

650
         if(m_tests.contains(category)) {
419✔
651
            throw Test_Error("'" + category + "' cannot be used as category, test exists");
×
652
         }
653

654
         if(m_categories.contains(name)) {
419✔
655
            throw Test_Error("'" + name + "' cannot be used as test name, category exists");
×
656
         }
657

658
         if(smoke_test) {
419✔
659
            m_smoke_tests.push_back(name);
10✔
660
         }
661

662
         if(needs_serialization) {
419✔
663
            m_mutexed_tests.push_back(name);
21✔
664
         }
665

666
         m_tests.emplace(name, std::move(maker_fn));
419✔
667
         m_categories.emplace(category, name);
419✔
668
      }
419✔
669

670
      std::unique_ptr<Test> get_test(const std::string& test_name) const {
419✔
671
         auto i = m_tests.find(test_name);
419✔
672
         if(i != m_tests.end()) {
419✔
673
            return i->second();
419✔
674
         }
675
         return nullptr;
×
676
      }
677

678
      std::vector<std::string> registered_tests() const {
×
679
         std::vector<std::string> s;
×
680
         s.reserve(m_tests.size());
×
681
         for(auto&& i : m_tests) {
×
682
            s.push_back(i.first);
×
683
         }
684
         return s;
×
685
      }
×
686

687
      std::vector<std::string> registered_test_categories() const {
×
688
         std::set<std::string> s;
×
689
         for(auto&& i : m_categories) {
×
690
            s.insert(i.first);
×
691
         }
692
         return std::vector<std::string>(s.begin(), s.end());
×
693
      }
×
694

695
      std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
1✔
696
                                                       const std::vector<std::string>& to_be_skipped) {
697
         std::vector<std::string> result;
1✔
698

699
         std::set<std::string> to_be_skipped_set(to_be_skipped.begin(), to_be_skipped.end());
1✔
700
         // TODO: this is O(n^2), but we have a relatively small number of tests.
701
         auto insert_if_not_exists_and_not_skipped = [&](const std::string& test_name) {
420✔
702
            if(!Botan::value_exists(result, test_name) && !to_be_skipped_set.contains(test_name)) {
838✔
703
               result.push_back(test_name);
409✔
704
            }
705
         };
420✔
706

707
         if(requested.empty()) {
1✔
708
            /*
709
            If nothing was requested on the command line, run everything. First
710
            run the "essentials" to smoke test, then everything else in
711
            alphabetical order.
712
            */
713
            result = m_smoke_tests;
1✔
714
            for(const auto& [test_name, _] : m_tests) {
420✔
715
               insert_if_not_exists_and_not_skipped(test_name);
419✔
716
            }
717
         } else {
718
            for(const auto& r : requested) {
×
719
               if(m_tests.contains(r)) {
×
720
                  insert_if_not_exists_and_not_skipped(r);
×
721
               } else if(auto elems = m_categories.equal_range(r); elems.first != m_categories.end()) {
×
722
                  for(; elems.first != elems.second; ++elems.first) {
×
723
                     insert_if_not_exists_and_not_skipped(elems.first->second);
×
724
                  }
725
               } else {
726
                  throw Test_Error("Unknown test suite or category: " + r);
×
727
               }
728
            }
729
         }
730

731
         return result;
1✔
732
      }
1✔
733

734
      bool needs_serialization(const std::string& test_name) const {
440✔
735
         return Botan::value_exists(m_mutexed_tests, test_name);
21✔
736
      }
737

738
   private:
739
      Test_Registry() = default;
1✔
740

741
   private:
742
      std::map<std::string, std::function<std::unique_ptr<Test>()>> m_tests;
743
      std::multimap<std::string, std::string> m_categories;
744
      std::vector<std::string> m_smoke_tests;
745
      std::vector<std::string> m_mutexed_tests;
746
};
747

748
}  // namespace
749

750
// static Test:: functions
751

752
//static
753
void Test::register_test(const std::string& category,
419✔
754
                         const std::string& name,
755
                         bool smoke_test,
756
                         bool needs_serialization,
757
                         std::function<std::unique_ptr<Test>()> maker_fn) {
758
   Test_Registry::instance().register_test(category, name, smoke_test, needs_serialization, std::move(maker_fn));
838✔
759
}
419✔
760

761
//static
762
uint64_t Test::timestamp() {
180,013✔
763
   auto now = std::chrono::system_clock::now().time_since_epoch();
180,013✔
764
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
2,383✔
765
}
766

767
//static
768
std::vector<Test::Result> Test::flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists) {
4✔
769
   std::vector<Test::Result> results;
4✔
770
   for(auto& result_list : result_lists) {
26✔
771
      for(auto& result : result_list) {
71✔
772
         results.emplace_back(std::move(result));
49✔
773
      }
774
   }
775
   return results;
4✔
776
}
×
777

778
//static
779
std::vector<std::string> Test::registered_tests() {
×
780
   return Test_Registry::instance().registered_tests();
×
781
}
782

783
//static
784
std::vector<std::string> Test::registered_test_categories() {
×
785
   return Test_Registry::instance().registered_test_categories();
×
786
}
787

788
//static
789
std::unique_ptr<Test> Test::get_test(const std::string& test_name) {
419✔
790
   return Test_Registry::instance().get_test(test_name);
419✔
791
}
792

793
//static
794
bool Test::test_needs_serialization(const std::string& test_name) {
419✔
795
   return Test_Registry::instance().needs_serialization(test_name);
419✔
796
}
797

798
//static
799
std::vector<std::string> Test::filter_registered_tests(const std::vector<std::string>& requested,
1✔
800
                                                       const std::vector<std::string>& to_be_skipped) {
801
   return Test_Registry::instance().filter_registered_tests(requested, to_be_skipped);
1✔
802
}
803

804
//static
805
std::string Test::temp_file_name(const std::string& basename) {
21✔
806
   // TODO add a --tmp-dir option to the tests to specify where these files go
807

808
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
809

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

813
   const int fd = ::mkstemp(mkstemp_basename.data());
21✔
814

815
   // error
816
   if(fd < 0) {
21✔
817
      return "";
×
818
   }
819

820
   ::close(fd);
21✔
821

822
   return mkstemp_basename;
21✔
823
#else
824
   // For now just create the temp in the current working directory
825
   return basename;
826
#endif
827
}
21✔
828

829
bool Test::copy_file(const std::string& from, const std::string& to) {
1✔
830
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(__cpp_lib_filesystem)
831
   std::error_code ec;  // don't throw, just return false on error
1✔
832
   return std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
1✔
833
#else
834
   // TODO: implement fallbacks to POSIX or WIN32
835
   // ... but then again: it's 2023 and we're using C++20 :o)
836
   BOTAN_UNUSED(from, to);
837
   throw Botan::No_Filesystem_Access();
838
#endif
839
}
840

841
std::string Test::read_data_file(const std::string& path) {
38✔
842
   const std::string fsname = Test::data_file(path);
38✔
843
   std::ifstream file(fsname.c_str());
38✔
844
   if(!file.good()) {
38✔
845
      throw Test_Error("Error reading from " + fsname);
×
846
   }
847

848
   return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
76✔
849
}
38✔
850

851
std::vector<uint8_t> Test::read_binary_data_file(const std::string& path) {
34✔
852
   const std::string fsname = Test::data_file(path);
34✔
853
   std::ifstream file(fsname.c_str(), std::ios::binary);
34✔
854
   if(!file.good()) {
34✔
855
      throw Test_Error("Error reading from " + fsname);
×
856
   }
857

858
   std::vector<uint8_t> contents;
34✔
859

860
   while(file.good()) {
74✔
861
      std::vector<uint8_t> buf(4096);
40✔
862
      file.read(reinterpret_cast<char*>(buf.data()), buf.size());
40✔
863
      const size_t got = static_cast<size_t>(file.gcount());
40✔
864

865
      if(got == 0 && file.eof()) {
40✔
866
         break;
867
      }
868

869
      contents.insert(contents.end(), buf.data(), buf.data() + got);
40✔
870
   }
40✔
871

872
   return contents;
68✔
873
}
34✔
874

875
// static member variables of Test
876

877
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
878
Test_Options Test::m_opts;
879
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
880
std::string Test::m_test_rng_seed;
881

882
//static
883
void Test::set_test_options(const Test_Options& opts) {
1✔
884
   m_opts = opts;
1✔
885
}
1✔
886

887
namespace {
888

889
/*
890
* This is a fast, simple, deterministic PRNG that's used for running
891
* the tests. It is not intended to be cryptographically secure.
892
*/
893
class Testsuite_RNG final : public Botan::RandomNumberGenerator {
8✔
894
   public:
895
      std::string name() const override { return "Testsuite_RNG"; }
×
896

897
      void clear() override { m_x = 0; }
×
898

899
      bool accepts_input() const override { return true; }
×
900

901
      bool is_seeded() const override { return true; }
276,251✔
902

903
      void fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) override {
10,240,092✔
904
         for(const auto byte : input) {
10,240,092✔
905
            mix(byte);
×
906
         }
907

908
         for(auto& byte : output) {
73,563,339✔
909
            byte = mix();
63,323,247✔
910
         }
911
      }
10,240,092✔
912

913
      Testsuite_RNG(std::string_view seed, std::string_view test_name) : m_x(0) {
276✔
914
         for(const char c : seed) {
8,280✔
915
            this->mix(static_cast<uint8_t>(c));
8,004✔
916
         }
917
         for(const char c : test_name) {
5,578✔
918
            this->mix(static_cast<uint8_t>(c));
5,302✔
919
         }
920
      }
276✔
921

922
   private:
923
      uint8_t mix(uint8_t input = 0) {
63,336,553✔
924
         m_x ^= input;
63,336,553✔
925
         m_x *= 0xF2E16957;
63,336,553✔
926
         m_x += 0xE50B590F;
63,336,553✔
927
         return static_cast<uint8_t>(m_x >> 27);
63,336,553✔
928
      }
929

930
      uint64_t m_x;
931
};
932

933
}  // namespace
934

935
//static
936
void Test::set_test_rng_seed(std::span<const uint8_t> seed, size_t epoch) {
1✔
937
   m_test_rng_seed = Botan::fmt("seed={} epoch={}", Botan::hex_encode(seed), epoch);
1✔
938
}
1✔
939

940
//static
941
std::unique_ptr<Botan::RandomNumberGenerator> Test::new_rng(std::string_view test_name) {
268✔
942
   return std::make_unique<Testsuite_RNG>(m_test_rng_seed, test_name);
268✔
943
}
944

945
//static
946
std::shared_ptr<Botan::RandomNumberGenerator> Test::new_shared_rng(std::string_view test_name) {
8✔
947
   return std::make_shared<Testsuite_RNG>(m_test_rng_seed, test_name);
8✔
948
}
949

950
//static
951
std::string Test::data_file(const std::string& file) {
773✔
952
   return options().data_dir() + "/" + file;
1,546✔
953
}
954

955
//static
956
std::string Test::data_dir(const std::string& subdir) {
1✔
957
   return options().data_dir() + "/" + subdir;
2✔
958
}
959

960
//static
961
std::vector<std::string> Test::files_in_data_dir(const std::string& subdir) {
393✔
962
   auto fs = Botan::get_files_recursive(options().data_dir() + "/" + subdir);
1,179✔
963
   if(fs.empty()) {
393✔
964
      throw Test_Error("Test::files_in_data_dir encountered empty subdir " + subdir);
×
965
   }
966
   return fs;
393✔
967
}
×
968

969
//static
970
std::string Test::data_file_as_temporary_copy(const std::string& what) {
1✔
971
   auto tmp_basename = what;
1✔
972
   std::replace(tmp_basename.begin(), tmp_basename.end(), '/', '_');
1✔
973
   auto temp_file = temp_file_name("tmp-" + tmp_basename);
1✔
974
   if(temp_file.empty()) {
1✔
975
      return "";
×
976
   }
977
   if(!Test::copy_file(data_file(what), temp_file)) {
1✔
978
      return "";
×
979
   }
980
   return temp_file;
1✔
981
}
1✔
982

983
//static
984
std::vector<std::string> Test::provider_filter(const std::vector<std::string>& providers) {
49,022✔
985
   if(m_opts.provider().empty()) {
49,022✔
986
      return providers;
49,022✔
987
   }
988
   for(auto&& provider : providers) {
×
989
      if(provider == m_opts.provider()) {
×
990
         return std::vector<std::string>{provider};
×
991
      }
992
   }
993
   return std::vector<std::string>{};
×
994
}
×
995

996
std::string Test::random_password(Botan::RandomNumberGenerator& rng) {
222✔
997
   const size_t len = 1 + rng.next_byte() % 32;
222✔
998
   return Botan::hex_encode(rng.random_vec(len));
444✔
999
}
1000

1001
size_t Test::random_index(Botan::RandomNumberGenerator& rng, size_t max) {
8,062✔
1002
   return Botan::load_be(rng.random_array<8>()) % max;
8,062✔
1003
}
1004

1005
void VarMap::clear() {
34,281✔
1006
   m_vars.clear();
×
1007
}
×
1008

1009
namespace {
1010

1011
bool varmap_pair_lt(const std::pair<std::string, std::string>& kv, const std::string& k) {
1,713,618✔
1012
   return kv.first < k;
1,713,618✔
1013
}
1014

1015
}  // namespace
1016

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

1020
   if(i != m_vars.end() && i->first == key) {
156,235✔
1021
      i->second = value;
44,405✔
1022
   } else {
1023
      m_vars.emplace(i, key, value);
111,830✔
1024
   }
1025
}
156,235✔
1026

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

1030
   if(i != m_vars.end() && i->first == key) {
568,446✔
1031
      return i->second;
498,591✔
1032
   } else {
1033
      return {};
69,855✔
1034
   }
1035
}
1036

1037
bool VarMap::has_key(const std::string& key) const {
213,574✔
1038
   return get_var(key).has_value();
213,574✔
1039
}
1040

1041
std::string VarMap::get_req_str(const std::string& key) const {
259,629✔
1042
   auto var = get_var(key);
259,629✔
1043
   if(var) {
259,629✔
1044
      return *var;
519,258✔
1045
   } else {
1046
      throw Test_Error("Test missing variable " + key);
×
1047
   }
1048
}
259,629✔
1049

1050
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(const std::string& key) const {
12✔
1051
   const auto var = get_req_str(key);
12✔
1052

1053
   std::vector<std::vector<uint8_t>> bin_list;
12✔
1054

1055
   for(auto&& part : Botan::split_on(var, ',')) {
62✔
1056
      try {
50✔
1057
         bin_list.push_back(Botan::hex_decode(part));
100✔
1058
      } catch(std::exception& e) {
×
1059
         std::ostringstream oss;
×
1060
         oss << "Bad input '" << part << "'"
×
1061
             << " in binary list key " << key << " - " << e.what();
×
1062
         throw Test_Error(oss.str());
×
1063
      }
×
1064
   }
12✔
1065

1066
   return bin_list;
12✔
1067
}
12✔
1068

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

1072
   try {
163,711✔
1073
      if(var.starts_with("0x")) {
163,711✔
1074
         if(var.size() % 2 == 0) {
×
1075
            return Botan::hex_decode(var.substr(2));
×
1076
         } else {
1077
            std::string z = var;
×
1078
            std::swap(z[0], z[1]);  // swap 0x to x0 then remove x
×
1079
            return Botan::hex_decode(z.substr(1));
×
1080
         }
×
1081
      } else {
1082
         return Botan::hex_decode(var);
163,711✔
1083
      }
1084
   } catch(std::exception& e) {
×
1085
      std::ostringstream oss;
×
1086
      oss << "Bad input '" << var << "'"
×
1087
          << " for key " << key << " - " << e.what();
×
1088
      throw Test_Error(oss.str());
×
1089
   }
×
1090
}
163,711✔
1091

1092
std::string VarMap::get_opt_str(const std::string& key, const std::string& def_value) const {
14,378✔
1093
   if(auto v = get_var(key)) {
14,378✔
1094
      return *v;
57✔
1095
   } else {
1096
      return def_value;
28,699✔
1097
   }
14,378✔
1098
}
1099

1100
bool VarMap::get_req_bool(const std::string& key) const {
39✔
1101
   const auto var = get_req_str(key);
39✔
1102

1103
   if(var == "true") {
39✔
1104
      return true;
1105
   } else if(var == "false") {
23✔
1106
      return false;
1107
   } else {
1108
      throw Test_Error("Invalid boolean for key '" + key + "' value '" + var + "'");
×
1109
   }
1110
}
39✔
1111

1112
size_t VarMap::get_req_sz(const std::string& key) const {
4,547✔
1113
   return Botan::to_u32bit(get_req_str(key));
4,547✔
1114
}
1115

1116
uint8_t VarMap::get_req_u8(const std::string& key) const {
17✔
1117
   const size_t s = this->get_req_sz(key);
17✔
1118
   if(s > 256) {
17✔
1119
      throw Test_Error("Invalid " + key + " expected uint8_t got " + std::to_string(s));
×
1120
   }
1121
   return static_cast<uint8_t>(s);
17✔
1122
}
1123

1124
uint32_t VarMap::get_req_u32(const std::string& key) const {
14✔
1125
   return static_cast<uint32_t>(get_req_sz(key));
14✔
1126
}
1127

1128
uint64_t VarMap::get_req_u64(const std::string& key) const {
17✔
1129
   const auto var = get_req_str(key);
17✔
1130
   try {
17✔
1131
      return std::stoull(var);
17✔
1132
   } catch(std::exception&) {
×
1133
      throw Test_Error("Invalid u64 value '" + var + "'");
×
1134
   }
×
1135
}
17✔
1136

1137
size_t VarMap::get_opt_sz(const std::string& key, const size_t def_value) const {
31,379✔
1138
   if(auto v = get_var(key)) {
31,379✔
1139
      return Botan::to_u32bit(*v);
12,244✔
1140
   } else {
1141
      return def_value;
1142
   }
31,379✔
1143
}
1144

1145
uint64_t VarMap::get_opt_u64(const std::string& key, const uint64_t def_value) const {
3,538✔
1146
   if(auto v = get_var(key)) {
3,538✔
1147
      try {
641✔
1148
         return std::stoull(*v);
3,538✔
1149
      } catch(std::exception&) {
×
1150
         throw Test_Error("Invalid u64 value '" + *v + "'");
×
1151
      }
×
1152
   } else {
1153
      return def_value;
1154
   }
3,538✔
1155
}
×
1156

1157
std::vector<uint8_t> VarMap::get_opt_bin(const std::string& key) const {
45,868✔
1158
   if(auto v = get_var(key)) {
45,868✔
1159
      try {
16,134✔
1160
         return Botan::hex_decode(*v);
16,134✔
1161
      } catch(std::exception&) {
×
1162
         throw Test_Error("Test invalid hex input '" + *v + "'" + +" for key " + key);
×
1163
      }
×
1164
   } else {
1165
      return {};
29,734✔
1166
   };
45,868✔
1167
}
×
1168

1169
#if defined(BOTAN_HAS_BIGINT)
1170
Botan::BigInt VarMap::get_req_bn(const std::string& key) const {
38,502✔
1171
   const auto var = get_req_str(key);
38,502✔
1172

1173
   try {
38,502✔
1174
      return Botan::BigInt(var);
38,502✔
1175
   } catch(std::exception&) {
×
1176
      throw Test_Error("Test invalid bigint input '" + var + "' for key " + key);
×
1177
   }
×
1178
}
38,502✔
1179

1180
Botan::BigInt VarMap::get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const {
80✔
1181
   if(auto v = get_var(key)) {
80✔
1182
      try {
56✔
1183
         return Botan::BigInt(*v);
56✔
1184
      } catch(std::exception&) {
×
1185
         throw Test_Error("Test invalid bigint input '" + *v + "' for key " + key);
×
1186
      }
×
1187
   } else {
1188
      return def_value;
24✔
1189
   }
80✔
1190
}
×
1191
#endif
1192

1193
class Text_Based_Test::Text_Based_Test_Data {
1194
   public:
1195
      Text_Based_Test_Data(const std::string& data_src,
181✔
1196
                           const std::string& required_keys_str,
1197
                           const std::string& optional_keys_str) :
181✔
1198
            m_data_src(data_src) {
362✔
1199
         if(required_keys_str.empty()) {
181✔
1200
            throw Test_Error("Invalid test spec");
×
1201
         }
1202

1203
         m_required_keys = Botan::split_on(required_keys_str, ',');
181✔
1204
         std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
181✔
1205

1206
         m_all_keys.insert(m_required_keys.begin(), m_required_keys.end());
181✔
1207
         m_all_keys.insert(optional_keys.begin(), optional_keys.end());
181✔
1208
         m_output_key = m_required_keys.at(m_required_keys.size() - 1);
181✔
1209
      }
181✔
1210

1211
      std::string get_next_line();
1212

1213
      const std::string& current_source_name() const { return m_cur_src_name; }
×
1214

1215
      bool known_key(const std::string& key) const;
1216

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

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

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

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

1225
      const std::string& initial_data_src_name() const { return m_data_src; }
181✔
1226

1227
   private:
1228
      std::string m_data_src;
1229
      std::vector<std::string> m_required_keys;
1230
      std::unordered_set<std::string> m_all_keys;
1231
      std::string m_output_key;
1232

1233
      bool m_first = true;
1234
      std::unique_ptr<std::istream> m_cur;
1235
      std::string m_cur_src_name;
1236
      std::deque<std::string> m_srcs;
1237
      std::vector<std::string> m_cpu_flags;
1238
};
1239

1240
Text_Based_Test::Text_Based_Test(const std::string& data_src,
181✔
1241
                                 const std::string& required_keys,
1242
                                 const std::string& optional_keys) :
181✔
1243
      m_data(std::make_unique<Text_Based_Test_Data>(data_src, required_keys, optional_keys)) {}
181✔
1244

1245
Text_Based_Test::~Text_Based_Test() = default;
181✔
1246

1247
std::string Text_Based_Test::Text_Based_Test_Data::get_next_line() {
157,242✔
1248
   while(true) {
157,500✔
1249
      if(m_cur == nullptr || m_cur->good() == false) {
157,500✔
1250
         if(m_srcs.empty()) {
450✔
1251
            if(m_first) {
362✔
1252
               if(m_data_src.ends_with(".vec")) {
181✔
1253
                  m_srcs.push_back(Test::data_file(m_data_src));
338✔
1254
               } else {
1255
                  const auto fs = Test::files_in_data_dir(m_data_src);
12✔
1256
                  m_srcs.assign(fs.begin(), fs.end());
12✔
1257
                  if(m_srcs.empty()) {
12✔
1258
                     throw Test_Error("Error reading test data dir " + m_data_src);
×
1259
                  }
1260
               }
12✔
1261

1262
               m_first = false;
181✔
1263
            } else {
1264
               return "";  // done
181✔
1265
            }
1266
         }
1267

1268
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
357✔
1269
         m_cur_src_name = m_srcs[0];
269✔
1270

1271
#if defined(BOTAN_HAS_CPUID)
1272
         // Reinit cpuid on new file if needed
1273
         if(m_cpu_flags.empty() == false) {
269✔
1274
            m_cpu_flags.clear();
19✔
1275
            Botan::CPUID::initialize();
19✔
1276
         }
1277
#endif
1278

1279
         if(!m_cur->good()) {
269✔
1280
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
1281
         }
1282

1283
         m_srcs.pop_front();
269✔
1284
      }
1285

1286
      while(m_cur->good()) {
227,897✔
1287
         std::string line;
227,639✔
1288
         std::getline(*m_cur, line);
227,639✔
1289

1290
         if(line.empty()) {
227,639✔
1291
            continue;
55,310✔
1292
         }
1293

1294
         if(line[0] == '#') {
172,329✔
1295
            if(line.starts_with("#test ")) {
15,289✔
1296
               return line;
21✔
1297
            } else {
1298
               continue;
15,268✔
1299
            }
1300
         }
1301

1302
         return line;
157,040✔
1303
      }
227,639✔
1304
   }
1305
}
1306

1307
bool Text_Based_Test::Text_Based_Test_Data::known_key(const std::string& key) const {
156,235✔
1308
   return m_all_keys.contains(key);
156,235✔
1309
}
1310

1311
namespace {
1312

1313
// strips leading and trailing but not internal whitespace
1314
std::string strip_ws(const std::string& in) {
312,470✔
1315
   const char* whitespace = " ";
312,470✔
1316

1317
   const auto first_c = in.find_first_not_of(whitespace);
312,470✔
1318
   if(first_c == std::string::npos) {
312,470✔
1319
      return "";
1,033✔
1320
   }
1321

1322
   const auto last_c = in.find_last_not_of(whitespace);
311,437✔
1323

1324
   return in.substr(first_c, last_c - first_c + 1);
311,437✔
1325
}
1326

1327
std::vector<std::string> parse_cpuid_bits(const std::vector<std::string>& tok) {
21✔
1328
   std::vector<std::string> bits;
21✔
1329

1330
#if defined(BOTAN_HAS_CPUID)
1331
   for(size_t i = 1; i < tok.size(); ++i) {
106✔
1332
      if(auto bit = Botan::CPUID::bit_from_string(tok[i])) {
85✔
1333
         bits.push_back(bit->to_string());
98✔
1334
      }
1335
   }
1336
#else
1337
   BOTAN_UNUSED(tok);
1338
#endif
1339

1340
   return bits;
21✔
1341
}
×
1342

1343
}  // namespace
1344

1345
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) {
32,609✔
1346
   return false;
32,609✔
1347
}
1348

1349
std::vector<Test::Result> Text_Based_Test::run() {
181✔
1350
   std::vector<Test::Result> results;
181✔
1351

1352
   std::string header;
181✔
1353
   std::string header_or_name = m_data->initial_data_src_name();
181✔
1354
   VarMap vars;
181✔
1355
   size_t test_cnt = 0;
181✔
1356

1357
   while(true) {
157,242✔
1358
      const std::string line = m_data->get_next_line();
157,242✔
1359
      if(line.empty()) {
157,242✔
1360
         // EOF
1361
         break;
1362
      }
1363

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

1367
         if(pragma_tokens.empty()) {
21✔
1368
            throw Test_Error("Empty pragma found in " + m_data->current_source_name());
×
1369
         }
1370

1371
         if(pragma_tokens[0] != "cpuid") {
21✔
1372
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1373
         }
1374

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

1379
         m_data->set_cpu_flags(parse_cpuid_bits(pragma_tokens));
42✔
1380

1381
         continue;
21✔
1382
      } else if(line[0] == '#') {
157,061✔
1383
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1384
      }
1385

1386
      if(line[0] == '[' && line[line.size() - 1] == ']') {
157,040✔
1387
         header = line.substr(1, line.size() - 2);
805✔
1388
         header_or_name = header;
805✔
1389
         test_cnt = 0;
805✔
1390
         vars.clear();
805✔
1391
         continue;
805✔
1392
      }
1393

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

1396
      auto equal_i = line.find_first_of('=');
156,235✔
1397

1398
      if(equal_i == std::string::npos) {
156,235✔
1399
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1400
         continue;
×
1401
      }
1402

1403
      const std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
312,470✔
1404
      const std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
312,470✔
1405

1406
      if(!m_data->known_key(key)) {
156,235✔
1407
         auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key));
×
1408
         results.push_back(r);
×
1409
      }
×
1410

1411
      vars.add(key, val);
156,235✔
1412

1413
      if(key == m_data->output_key()) {
156,235✔
1414
         try {
48,388✔
1415
            for(const auto& req_key : m_data->required_keys()) {
245,554✔
1416
               if(!vars.has_key(req_key)) {
197,166✔
1417
                  auto r =
×
1418
                     Test::Result::Failure(header_or_name, Botan::fmt("{} missing required key {}", test_id, req_key));
×
1419
                  results.push_back(r);
×
1420
               }
×
1421
            }
1422

1423
            if(skip_this_test(header, vars)) {
48,388✔
1424
               continue;
139✔
1425
            }
1426

1427
            ++test_cnt;
48,249✔
1428

1429
            const uint64_t start = Test::timestamp();
48,249✔
1430

1431
            Test::Result result = run_one_test(header, vars);
48,249✔
1432
#if defined(BOTAN_HAS_CPUID)
1433
            if(!m_data->cpu_flags().empty()) {
48,249✔
1434
               for(const auto& cpuid_str : m_data->cpu_flags()) {
30,621✔
1435
                  if(const auto bit = Botan::CPUID::Feature::from_string(cpuid_str)) {
21,677✔
1436
                     if(Botan::CPUID::has(*bit)) {
21,677✔
1437
                        Botan::CPUID::clear_cpuid_bit(*bit);
16,577✔
1438
                        // now re-run the test
1439
                        result.merge(run_one_test(header, vars));
16,577✔
1440
                     }
1441
                  }
1442
               }
1443
               Botan::CPUID::initialize();
8,944✔
1444
            }
1445
#endif
1446
            result.set_ns_consumed(Test::timestamp() - start);
48,249✔
1447

1448
            if(result.tests_failed() > 0) {
48,249✔
1449
               std::ostringstream oss;
×
1450
               oss << "Test # " << test_cnt << " ";
×
1451
               if(!header.empty()) {
×
1452
                  oss << header << " ";
×
1453
               }
1454
               oss << "failed ";
×
1455

1456
               for(const auto& k : m_data->required_keys()) {
×
1457
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1458
               }
1459

1460
               result.test_note(oss.str());
×
1461
            }
×
1462
            results.push_back(result);
48,249✔
1463
         } catch(std::exception& e) {
48,249✔
1464
            std::ostringstream oss;
×
1465
            oss << "Test # " << test_cnt << " ";
×
1466
            if(!header.empty()) {
×
1467
               oss << header << " ";
×
1468
            }
1469

1470
            for(const auto& k : m_data->required_keys()) {
×
1471
               oss << k << "=" << vars.get_req_str(k) << " ";
×
1472
            }
1473

1474
            oss << "failed with exception '" << e.what() << "'";
×
1475

1476
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1477
         }
×
1478

1479
         if(clear_between_callbacks()) {
48,249✔
1480
            vars.clear();
189,572✔
1481
         }
1482
      }
1483
   }
157,339✔
1484

1485
   if(results.empty()) {
181✔
1486
      return results;
1487
   }
1488

1489
   try {
181✔
1490
      std::vector<Test::Result> final_tests = run_final_tests();
181✔
1491
      results.insert(results.end(), final_tests.begin(), final_tests.end());
181✔
1492
   } catch(std::exception& e) {
181✔
1493
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1494
   }
×
1495

1496
   return results;
1497
}
181✔
1498

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