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

randombit / botan / 22034777194

15 Feb 2026 11:21AM UTC coverage: 89.999% (-0.001%) from 90.0%
22034777194

Pull #5338

github

web-flow
Merge 8493f6ee7 into 2993205af
Pull Request #5338: Rename and cleanup tests.h comparators for strings

102267 of 113631 relevant lines covered (90.0%)

11490211.35 hits per line

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

79.58
/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,129✔
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,767✔
71
   if(who() != other.who()) {
126,767✔
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,694✔
81
   }
82

83
   m_timestamp = std::min(m_timestamp, other.m_timestamp);
126,767✔
84
   m_ns_taken += other.m_ns_taken;
126,767✔
85
   m_tests_passed += other.m_tests_passed;
126,767✔
86
   m_fail_log.insert(m_fail_log.end(), other.m_fail_log.begin(), other.m_fail_log.end());
126,767✔
87
   m_log.insert(m_log.end(), other.m_log.begin(), other.m_log.end());
126,767✔
88
}
126,767✔
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(!test_bool_eq(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,290✔
198
   if(Test::options().log_success()) {
3,620,274✔
199
      test_note(note);
×
200
   }
201
   ++m_tests_passed;
3,620,290✔
202
   return true;
397,224✔
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(const char* err) {
×
218
   return test_failure(std::string_view(err));
×
219
}
220

221
bool Test::Result::test_failure(std::string_view err) {
1✔
222
   return test_failure(std::string(err));
1✔
223
}
224

225
bool Test::Result::test_failure(std::string err) {
25✔
226
   m_fail_log.push_back(std::move(err));
25✔
227

228
   if(Test::options().abort_on_first_fail() && m_who != "Failing Test") {
25✔
229
      std::abort();
×
230
   }
231
   return false;
25✔
232
}
233

234
namespace {
235

236
bool same_contents(const uint8_t x[], const uint8_t y[], size_t len) {
292,394✔
237
   return (len == 0) ? true : std::memcmp(x, y, len) == 0;
290,963✔
238
}
239

240
}  // namespace
241

242
bool Test::Result::test_ne(std::string_view what,
3,411✔
243
                           const uint8_t produced[],
244
                           size_t produced_len,
245
                           const uint8_t expected[],
246
                           size_t expected_len) {
247
   if(produced_len == expected_len && same_contents(produced, expected, expected_len)) {
3,411✔
248
      return test_failure(Botan::fmt("{} {} produced matching bytes", who(), what));
2✔
249
   }
250
   return test_success();
3,409✔
251
}
252

253
bool Test::Result::test_eq(std::string_view what, std::span<const uint8_t> produced, const char* expected_hex) {
471✔
254
   const std::vector<uint8_t> expected = Botan::hex_decode(expected_hex);
471✔
255
   return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
471✔
256
}
471✔
257

258
bool Test::Result::test_eq(const char* producer,
290,975✔
259
                           std::string_view what,
260
                           const uint8_t produced[],
261
                           size_t produced_size,
262
                           const uint8_t expected[],
263
                           size_t expected_size) {
264
   if(produced_size == expected_size && same_contents(produced, expected, expected_size)) {
290,975✔
265
      return test_success();
290,974✔
266
   }
267

268
   std::ostringstream err;
1✔
269

270
   err << who();
1✔
271

272
   if(producer != nullptr) {
1✔
273
      err << " producer '" << producer << "'";
×
274
   }
275

276
   err << " unexpected result for " << what;
1✔
277

278
   if(produced_size != expected_size) {
1✔
279
      err << " produced " << produced_size << " bytes expected " << expected_size;
1✔
280
   }
281

282
   std::vector<uint8_t> xor_diff(std::min(produced_size, expected_size));
2✔
283
   size_t bytes_different = 0;
1✔
284

285
   for(size_t i = 0; i != xor_diff.size(); ++i) {
4✔
286
      xor_diff[i] = produced[i] ^ expected[i];
3✔
287
      if(xor_diff[i] > 0) {
3✔
288
         bytes_different++;
3✔
289
      }
290
   }
291

292
   err << "\nProduced: " << Botan::hex_encode(produced, produced_size)
1✔
293
       << "\nExpected: " << Botan::hex_encode(expected, expected_size);
3✔
294

295
   if(bytes_different > 0) {
1✔
296
      err << "\nXOR Diff: " << Botan::hex_encode(xor_diff);
1✔
297
   }
298

299
   return test_failure(err.str());
1✔
300
}
1✔
301

302
bool Test::Result::test_str_not_empty(std::string_view what, std::string_view produced) {
38,841✔
303
   if(produced.empty()) {
38,841✔
304
      return test_failure(what, "was empty");
1✔
305
   } else {
306
      return test_success();
38,840✔
307
   }
308
}
309

310
bool Test::Result::test_str_eq(std::string_view what, std::string_view produced, std::string_view expected) {
76,819✔
311
   return test_is_eq(what, produced, expected);
76,819✔
312
}
313

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

322
bool Test::Result::test_u8_eq(uint8_t produced, uint8_t expected) {
214✔
323
   return test_sz_eq("comparison", produced, expected);
214✔
324
}
325

326
bool Test::Result::test_u8_eq(std::string_view what, uint8_t produced, uint8_t expected) {
46,571✔
327
   return test_sz_eq(what, produced, expected);
46,571✔
328
}
329

330
bool Test::Result::test_u16_eq(uint16_t produced, uint16_t expected) {
36✔
331
   return test_sz_eq("comparison", produced, expected);
36✔
332
}
333

334
bool Test::Result::test_u16_eq(std::string_view what, uint16_t produced, uint16_t expected) {
65,560✔
335
   return test_sz_eq(what, produced, expected);
65,560✔
336
}
337

338
bool Test::Result::test_u32_eq(uint32_t produced, uint32_t expected) {
12✔
339
   return test_sz_eq("comparison", produced, expected);
12✔
340
}
341

342
bool Test::Result::test_u32_eq(std::string_view what, uint32_t produced, uint32_t expected) {
4,133✔
343
   return test_sz_eq(what, produced, expected);
4,133✔
344
}
345

346
bool Test::Result::test_u64_eq(uint64_t produced, uint64_t expected) {
8✔
347
   return test_u64_eq("comparison", produced, expected);
8✔
348
}
349

350
bool Test::Result::test_u64_eq(std::string_view what, uint64_t produced, uint64_t expected) {
1,238✔
351
   if(produced == expected) {
1,238✔
352
      return test_success();
1,238✔
353
   } else {
354
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} == {}", who(), what, produced, expected));
×
355
   }
356
}
357

358
bool Test::Result::test_sz_eq(std::string_view what, size_t produced, size_t expected) {
193,505✔
359
   if(produced == expected) {
193,505✔
360
      return test_success();
193,504✔
361
   } else {
362
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} == {}", who(), what, produced, expected));
1✔
363
   }
364
}
365

366
bool Test::Result::test_sz_ne(std::string_view what, size_t produced, size_t expected) {
119✔
367
   if(produced != expected) {
119✔
368
      return test_success();
118✔
369
   } else {
370
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} != {}", who(), what, produced, expected));
1✔
371
   }
372
}
373

374
bool Test::Result::test_sz_lt(std::string_view what, size_t produced, size_t expected) {
5,639✔
375
   if(produced < expected) {
5,639✔
376
      return test_success();
5,638✔
377
   } else {
378
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} < {}", who(), what, produced, expected));
1✔
379
   }
380
}
381

382
bool Test::Result::test_sz_lte(std::string_view what, size_t produced, size_t expected) {
1,021,636✔
383
   if(produced <= expected) {
1,021,636✔
384
      return test_success();
1,021,635✔
385
   } else {
386
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} <= {}", who(), what, produced, expected));
1✔
387
   }
388
}
389

390
bool Test::Result::test_sz_gt(std::string_view what, size_t produced, size_t expected) {
29,981✔
391
   if(produced > expected) {
29,981✔
392
      return test_success();
29,981✔
393
   } else {
394
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} > {}", who(), what, produced, expected));
×
395
   }
396
}
397

398
bool Test::Result::test_sz_gte(std::string_view what, size_t produced, size_t expected) {
1,142,439✔
399
   if(produced >= expected) {
1,142,439✔
400
      return test_success();
1,142,438✔
401
   } else {
402
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} >= {}", who(), what, produced, expected));
1✔
403
   }
404
}
405

406
bool Test::Result::test_opt_u8_eq(std::string_view what, std::optional<uint8_t> a, std::optional<uint8_t> b) {
1,215✔
407
   if(a.has_value() != b.has_value()) {
1,215✔
408
      std::ostringstream err;
×
409
      err << m_who << " " << what << " only one of a/b was nullopt";
×
410
      return test_failure(err.str());
×
411
   } else if(a.has_value() && b.has_value()) {
1,215✔
412
      return test_u8_eq(what, a.value(), b.value());
10✔
413
   } else {
414
      // both nullopt
415
      return test_success();
1,205✔
416
   }
417
}
418

419
#if defined(BOTAN_HAS_BIGINT)
420
bool Test::Result::test_eq(std::string_view what, const BigInt& produced, const BigInt& expected) {
252,630✔
421
   return test_is_eq(what, produced, expected);
252,630✔
422
}
423

424
bool Test::Result::test_ne(std::string_view what, const BigInt& produced, const BigInt& expected) {
97✔
425
   if(produced != expected) {
97✔
426
      return test_success();
96✔
427
   }
428

429
   std::ostringstream err;
1✔
430
   err << who() << " " << what << " produced " << produced << " prohibited value";
1✔
431
   return test_failure(err.str());
1✔
432
}
1✔
433
#endif
434

435
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
436
bool Test::Result::test_eq(std::string_view what, const Botan::EC_Point& a, const Botan::EC_Point& b) {
3,248✔
437
   //return test_is_eq(what, a, b);
438
   if(a == b) {
3,248✔
439
      return test_success();
3,248✔
440
   }
441

442
   std::ostringstream err;
×
443
   err << who() << " " << what << " a=(" << a.get_affine_x() << "," << a.get_affine_y() << ")"
×
444
       << " b=(" << b.get_affine_x() << "," << b.get_affine_y();
×
445
   return test_failure(err.str());
×
446
}
×
447
#endif
448

449
bool Test::Result::test_bool_eq(std::string_view what, bool produced, bool expected) {
370,186✔
450
   if(produced == expected) {
370,186✔
451
      return test_success();
370,186✔
452
   } else {
453
      if(expected == true) {
×
454
         return test_failure(Botan::fmt("Assertion failure in {}, {} was unexpectedly false", who(), what));
×
455
      } else {
456
         return test_failure(Botan::fmt("Assertion failure in {}, {} was unexpectedly true", who(), what));
×
457
      }
458
   }
459
}
460

461
bool Test::Result::test_is_true(std::string_view what, bool produced) {
236,325✔
462
   return test_bool_eq(what, produced, true);
236,325✔
463
}
464

465
bool Test::Result::test_is_false(std::string_view what, bool produced) {
125,961✔
466
   return test_bool_eq(what, produced, false);
125,961✔
467
}
468

469
bool Test::Result::test_rc_ok(std::string_view func, int rc) {
2,810✔
470
   if(rc != 0) {
2,810✔
471
      std::ostringstream err;
1✔
472
      err << m_who << " " << func << " unexpectedly failed with error code " << rc;
1✔
473
      return test_failure(err.str());
1✔
474
   }
1✔
475

476
   return test_success();
2,809✔
477
}
478

479
bool Test::Result::test_rc_fail(std::string_view func, std::string_view why, int rc) {
26✔
480
   if(rc == 0) {
26✔
481
      std::ostringstream err;
1✔
482
      err << m_who << " call to " << func << " unexpectedly succeeded expecting failure because " << why;
1✔
483
      return test_failure(err.str());
1✔
484
   }
1✔
485

486
   return test_success();
25✔
487
}
488

489
bool Test::Result::test_rc_init(std::string_view func, int rc) {
117✔
490
   if(rc == 0) {
117✔
491
      return test_success();
117✔
492
   } else {
493
      std::ostringstream msg;
×
494
      msg << m_who;
×
495
      msg << " " << func;
×
496

497
      // -40 is BOTAN_FFI_ERROR_NOT_IMPLEMENTED
498
      if(rc == -40) {
×
499
         msg << " returned not implemented";
×
500
      } else {
501
         msg << " unexpectedly failed with error code " << rc;
×
502
      }
503

504
      if(rc == -40) {
×
505
         this->test_note(msg.str());
×
506
      } else {
507
         this->test_failure(msg.str());
×
508
      }
509
      return false;
×
510
   }
×
511
}
512

513
bool Test::Result::test_rc(std::string_view func, int expected, int rc) {
416✔
514
   if(expected != rc) {
416✔
515
      std::ostringstream err;
1✔
516
      err << m_who;
1✔
517
      err << " call to " << func << " unexpectedly returned " << rc;
1✔
518
      err << " but expecting " << expected;
1✔
519
      return test_failure(err.str());
1✔
520
   }
1✔
521

522
   return test_success();
415✔
523
}
524

525
void Test::initialize(std::string test_name, CodeLocation location) {
419✔
526
   m_test_name = std::move(test_name);
419✔
527
   m_registration_location = location;
419✔
528
}
419✔
529

530
Botan::RandomNumberGenerator& Test::rng() const {
464,752✔
531
   if(!m_test_rng) {
464,752✔
532
      m_test_rng = Test::new_rng(m_test_name);
145✔
533
   }
534

535
   return *m_test_rng;
464,752✔
536
}
537

538
std::optional<std::string> Test::supported_ec_group_name(std::vector<std::string> preferred_groups) {
151✔
539
#if defined(BOTAN_HAS_ECC_GROUP)
540
   if(preferred_groups.empty()) {
151✔
541
      preferred_groups = {
149✔
542
         "secp256r1",
543
         "brainpool256r1",
544
         "secp384r1",
545
         "brainpool384r1",
546
         "secp521r1",
547
         "brainpool512r1",
548
      };
1,192✔
549
   }
550

551
   for(const auto& group : preferred_groups) {
151✔
552
      if(Botan::EC_Group::supports_named_group(group)) {
151✔
553
         return group;
151✔
554
      }
555
   }
556
#else
557
   BOTAN_UNUSED(preferred_groups);
558
#endif
559

560
   return std::nullopt;
×
561
}
298✔
562

563
std::vector<uint8_t> Test::mutate_vec(const std::vector<uint8_t>& v,
96,742✔
564
                                      Botan::RandomNumberGenerator& rng,
565
                                      bool maybe_resize,
566
                                      size_t min_offset) {
567
   std::vector<uint8_t> r = v;
96,742✔
568

569
   if(maybe_resize && (r.empty() || rng.next_byte() < 32)) {
110,321✔
570
      // TODO: occasionally truncate, insert at random index
571
      const size_t add = 1 + (rng.next_byte() % 16);
2,133✔
572
      r.resize(r.size() + add);
2,133✔
573
      rng.randomize(&r[r.size() - add], add);
2,133✔
574
   }
575

576
   if(r.size() > min_offset) {
96,742✔
577
      const size_t offset = std::max<size_t>(min_offset, rng.next_byte() % r.size());
95,204✔
578
      const uint8_t perturb = rng.next_nonzero_byte();
95,204✔
579
      r[offset] ^= perturb;
95,204✔
580
   }
581

582
   return r;
96,742✔
583
}
×
584

585
std::vector<std::string> Test::possible_providers(const std::string& /*alg*/) {
×
586
   return Test::provider_filter({"base"});
×
587
}
588

589
//static
590
std::string Test::format_time(uint64_t nanoseconds) {
1,470✔
591
   std::ostringstream o;
1,470✔
592

593
   if(nanoseconds > 1000000000) {
1,470✔
594
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000000.0 << " sec";
153✔
595
   } else {
596
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000.0 << " msec";
1,317✔
597
   }
598

599
   return o.str();
2,940✔
600
}
1,470✔
601

602
// TODO: this should move to `StdoutReporter`
603
std::string Test::Result::result_string() const {
2,541✔
604
   const bool verbose = Test::options().verbose();
2,541✔
605

606
   if(tests_run() == 0 && !verbose) {
2,541✔
607
      return "";
20✔
608
   }
609

610
   std::ostringstream report;
2,521✔
611

612
   report << who() << " ran ";
2,521✔
613

614
   if(tests_run() == 0) {
2,521✔
615
      report << "ZERO";
×
616
   } else {
617
      report << tests_run();
2,521✔
618
   }
619
   report << " tests";
2,521✔
620

621
   if(m_ns_taken > 0) {
2,521✔
622
      report << " in " << format_time(m_ns_taken);
2,938✔
623
   }
624

625
   if(tests_failed() > 0) {
2,521✔
626
      report << " " << tests_failed() << " FAILED";
25✔
627
   } else {
628
      report << " all ok";
2,496✔
629
   }
630

631
   report << "\n";
2,521✔
632

633
   for(size_t i = 0; i != m_fail_log.size(); ++i) {
2,546✔
634
      report << "Failure " << (i + 1) << ": " << m_fail_log[i];
25✔
635
      if(m_where) {
25✔
636
         report << " (at " << m_where->path << ":" << m_where->line << ")";
×
637
      }
638
      report << "\n";
25✔
639
   }
640

641
   if(!m_fail_log.empty() || tests_run() == 0 || verbose) {
2,521✔
642
      for(size_t i = 0; i != m_log.size(); ++i) {
25✔
643
         report << "Note " << (i + 1) << ": " << m_log[i] << "\n";
×
644
      }
645
   }
646

647
   return report.str();
2,521✔
648
}
2,521✔
649

650
namespace {
651

652
class Test_Registry {
653
   public:
654
      static Test_Registry& instance() {
1,279✔
655
         static Test_Registry registry;
1,280✔
656
         return registry;
1,279✔
657
      }
658

659
      void register_test(const std::string& category,
419✔
660
                         const std::string& name,
661
                         bool smoke_test,
662
                         bool needs_serialization,
663
                         std::function<std::unique_ptr<Test>()> maker_fn) {
664
         if(m_tests.contains(name)) {
419✔
665
            throw Test_Error("Duplicate registration of test '" + name + "'");
×
666
         }
667

668
         if(m_tests.contains(category)) {
419✔
669
            throw Test_Error("'" + category + "' cannot be used as category, test exists");
×
670
         }
671

672
         if(m_categories.contains(name)) {
419✔
673
            throw Test_Error("'" + name + "' cannot be used as test name, category exists");
×
674
         }
675

676
         if(smoke_test) {
419✔
677
            m_smoke_tests.push_back(name);
10✔
678
         }
679

680
         if(needs_serialization) {
419✔
681
            m_mutexed_tests.push_back(name);
21✔
682
         }
683

684
         m_tests.emplace(name, std::move(maker_fn));
419✔
685
         m_categories.emplace(category, name);
419✔
686
      }
419✔
687

688
      std::unique_ptr<Test> get_test(const std::string& test_name) const {
419✔
689
         auto i = m_tests.find(test_name);
419✔
690
         if(i != m_tests.end()) {
419✔
691
            return i->second();
419✔
692
         }
693
         return nullptr;
×
694
      }
695

696
      std::vector<std::string> registered_tests() const {
×
697
         std::vector<std::string> s;
×
698
         s.reserve(m_tests.size());
×
699
         for(auto&& i : m_tests) {
×
700
            s.push_back(i.first);
×
701
         }
702
         return s;
×
703
      }
×
704

705
      std::vector<std::string> registered_test_categories() const {
×
706
         std::set<std::string> s;
×
707
         for(auto&& i : m_categories) {
×
708
            s.insert(i.first);
×
709
         }
710
         return std::vector<std::string>(s.begin(), s.end());
×
711
      }
×
712

713
      std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
1✔
714
                                                       const std::vector<std::string>& to_be_skipped) {
715
         std::vector<std::string> result;
1✔
716

717
         std::set<std::string> to_be_skipped_set(to_be_skipped.begin(), to_be_skipped.end());
1✔
718
         // TODO: this is O(n^2), but we have a relatively small number of tests.
719
         auto insert_if_not_exists_and_not_skipped = [&](const std::string& test_name) {
420✔
720
            if(!Botan::value_exists(result, test_name) && !to_be_skipped_set.contains(test_name)) {
838✔
721
               result.push_back(test_name);
409✔
722
            }
723
         };
420✔
724

725
         if(requested.empty()) {
1✔
726
            /*
727
            If nothing was requested on the command line, run everything. First
728
            run the "essentials" to smoke test, then everything else in
729
            alphabetical order.
730
            */
731
            result = m_smoke_tests;
1✔
732
            for(const auto& [test_name, _] : m_tests) {
420✔
733
               insert_if_not_exists_and_not_skipped(test_name);
419✔
734
            }
735
         } else {
736
            for(const auto& r : requested) {
×
737
               if(m_tests.contains(r)) {
×
738
                  insert_if_not_exists_and_not_skipped(r);
×
739
               } else if(auto elems = m_categories.equal_range(r); elems.first != m_categories.end()) {
×
740
                  for(; elems.first != elems.second; ++elems.first) {
×
741
                     insert_if_not_exists_and_not_skipped(elems.first->second);
×
742
                  }
743
               } else {
744
                  throw Test_Error("Unknown test suite or category: " + r);
×
745
               }
746
            }
747
         }
748

749
         return result;
1✔
750
      }
1✔
751

752
      bool needs_serialization(const std::string& test_name) const {
440✔
753
         return Botan::value_exists(m_mutexed_tests, test_name);
21✔
754
      }
755

756
   private:
757
      Test_Registry() = default;
1✔
758

759
   private:
760
      std::map<std::string, std::function<std::unique_ptr<Test>()>> m_tests;
761
      std::multimap<std::string, std::string> m_categories;
762
      std::vector<std::string> m_smoke_tests;
763
      std::vector<std::string> m_mutexed_tests;
764
};
765

766
}  // namespace
767

768
// static Test:: functions
769

770
//static
771
void Test::register_test(const std::string& category,
419✔
772
                         const std::string& name,
773
                         bool smoke_test,
774
                         bool needs_serialization,
775
                         std::function<std::unique_ptr<Test>()> maker_fn) {
776
   Test_Registry::instance().register_test(category, name, smoke_test, needs_serialization, std::move(maker_fn));
838✔
777
}
419✔
778

779
//static
780
uint64_t Test::timestamp() {
180,022✔
781
   auto now = std::chrono::system_clock::now().time_since_epoch();
180,022✔
782
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
2,383✔
783
}
784

785
//static
786
std::vector<Test::Result> Test::flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists) {
4✔
787
   std::vector<Test::Result> results;
4✔
788
   for(auto& result_list : result_lists) {
26✔
789
      for(auto& result : result_list) {
71✔
790
         results.emplace_back(std::move(result));
49✔
791
      }
792
   }
793
   return results;
4✔
794
}
×
795

796
//static
797
std::vector<std::string> Test::registered_tests() {
×
798
   return Test_Registry::instance().registered_tests();
×
799
}
800

801
//static
802
std::vector<std::string> Test::registered_test_categories() {
×
803
   return Test_Registry::instance().registered_test_categories();
×
804
}
805

806
//static
807
std::unique_ptr<Test> Test::get_test(const std::string& test_name) {
419✔
808
   return Test_Registry::instance().get_test(test_name);
419✔
809
}
810

811
//static
812
bool Test::test_needs_serialization(const std::string& test_name) {
419✔
813
   return Test_Registry::instance().needs_serialization(test_name);
419✔
814
}
815

816
//static
817
std::vector<std::string> Test::filter_registered_tests(const std::vector<std::string>& requested,
1✔
818
                                                       const std::vector<std::string>& to_be_skipped) {
819
   return Test_Registry::instance().filter_registered_tests(requested, to_be_skipped);
1✔
820
}
821

822
//static
823
std::string Test::temp_file_name(const std::string& basename) {
21✔
824
   // TODO add a --tmp-dir option to the tests to specify where these files go
825

826
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
827

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

831
   const int fd = ::mkstemp(mkstemp_basename.data());
21✔
832

833
   // error
834
   if(fd < 0) {
21✔
835
      return "";
×
836
   }
837

838
   ::close(fd);
21✔
839

840
   return mkstemp_basename;
21✔
841
#else
842
   // For now just create the temp in the current working directory
843
   return basename;
844
#endif
845
}
21✔
846

847
bool Test::copy_file(const std::string& from, const std::string& to) {
1✔
848
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(__cpp_lib_filesystem)
849
   std::error_code ec;  // don't throw, just return false on error
1✔
850
   return std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
1✔
851
#else
852
   // TODO: implement fallbacks to POSIX or WIN32
853
   // ... but then again: it's 2023 and we're using C++20 :o)
854
   BOTAN_UNUSED(from, to);
855
   throw Botan::No_Filesystem_Access();
856
#endif
857
}
858

859
std::string Test::read_data_file(const std::string& path) {
38✔
860
   const std::string fsname = Test::data_file(path);
38✔
861
   std::ifstream file(fsname.c_str());
38✔
862
   if(!file.good()) {
38✔
863
      throw Test_Error("Error reading from " + fsname);
×
864
   }
865

866
   return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
76✔
867
}
38✔
868

869
std::vector<uint8_t> Test::read_binary_data_file(const std::string& path) {
34✔
870
   const std::string fsname = Test::data_file(path);
34✔
871
   std::ifstream file(fsname.c_str(), std::ios::binary);
34✔
872
   if(!file.good()) {
34✔
873
      throw Test_Error("Error reading from " + fsname);
×
874
   }
875

876
   std::vector<uint8_t> contents;
34✔
877

878
   while(file.good()) {
74✔
879
      std::vector<uint8_t> buf(4096);
40✔
880
      file.read(reinterpret_cast<char*>(buf.data()), buf.size());
40✔
881
      const size_t got = static_cast<size_t>(file.gcount());
40✔
882

883
      if(got == 0 && file.eof()) {
40✔
884
         break;
885
      }
886

887
      contents.insert(contents.end(), buf.data(), buf.data() + got);
40✔
888
   }
40✔
889

890
   return contents;
68✔
891
}
34✔
892

893
// static member variables of Test
894

895
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
896
Test_Options Test::m_opts;
897
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
898
std::string Test::m_test_rng_seed;
899

900
//static
901
void Test::set_test_options(const Test_Options& opts) {
1✔
902
   m_opts = opts;
1✔
903
}
1✔
904

905
namespace {
906

907
/*
908
* This is a fast, simple, deterministic PRNG that's used for running
909
* the tests. It is not intended to be cryptographically secure.
910
*/
911
class Testsuite_RNG final : public Botan::RandomNumberGenerator {
8✔
912
   public:
913
      std::string name() const override { return "Testsuite_RNG"; }
×
914

915
      void clear() override { m_x = 0; }
×
916

917
      bool accepts_input() const override { return true; }
×
918

919
      bool is_seeded() const override { return true; }
277,043✔
920

921
      void fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) override {
10,329,687✔
922
         for(const auto byte : input) {
10,329,687✔
923
            mix(byte);
×
924
         }
925

926
         for(auto& byte : output) {
73,867,954✔
927
            byte = mix();
63,538,267✔
928
         }
929
      }
10,329,687✔
930

931
      Testsuite_RNG(std::string_view seed, std::string_view test_name) : m_x(0) {
276✔
932
         for(const char c : seed) {
8,280✔
933
            this->mix(static_cast<uint8_t>(c));
8,004✔
934
         }
935
         for(const char c : test_name) {
5,578✔
936
            this->mix(static_cast<uint8_t>(c));
5,302✔
937
         }
938
      }
276✔
939

940
   private:
941
      uint8_t mix(uint8_t input = 0) {
63,551,573✔
942
         m_x ^= input;
63,551,573✔
943
         m_x *= 0xF2E16957;
63,551,573✔
944
         m_x += 0xE50B590F;
63,551,573✔
945
         return static_cast<uint8_t>(m_x >> 27);
63,551,573✔
946
      }
947

948
      uint64_t m_x;
949
};
950

951
}  // namespace
952

953
//static
954
void Test::set_test_rng_seed(std::span<const uint8_t> seed, size_t epoch) {
1✔
955
   m_test_rng_seed = Botan::fmt("seed={} epoch={}", Botan::hex_encode(seed), epoch);
1✔
956
}
1✔
957

958
//static
959
std::unique_ptr<Botan::RandomNumberGenerator> Test::new_rng(std::string_view test_name) {
268✔
960
   return std::make_unique<Testsuite_RNG>(m_test_rng_seed, test_name);
268✔
961
}
962

963
//static
964
std::shared_ptr<Botan::RandomNumberGenerator> Test::new_shared_rng(std::string_view test_name) {
8✔
965
   return std::make_shared<Testsuite_RNG>(m_test_rng_seed, test_name);
8✔
966
}
967

968
//static
969
std::string Test::data_file(const std::string& file) {
773✔
970
   return options().data_dir() + "/" + file;
1,546✔
971
}
972

973
//static
974
std::string Test::data_dir(const std::string& subdir) {
1✔
975
   return options().data_dir() + "/" + subdir;
2✔
976
}
977

978
//static
979
std::vector<std::string> Test::files_in_data_dir(const std::string& subdir) {
393✔
980
   auto fs = Botan::get_files_recursive(options().data_dir() + "/" + subdir);
1,179✔
981
   if(fs.empty()) {
393✔
982
      throw Test_Error("Test::files_in_data_dir encountered empty subdir " + subdir);
×
983
   }
984
   return fs;
393✔
985
}
×
986

987
//static
988
std::string Test::data_file_as_temporary_copy(const std::string& what) {
1✔
989
   auto tmp_basename = what;
1✔
990
   std::replace(tmp_basename.begin(), tmp_basename.end(), '/', '_');
1✔
991
   auto temp_file = temp_file_name("tmp-" + tmp_basename);
1✔
992
   if(temp_file.empty()) {
1✔
993
      return "";
×
994
   }
995
   if(!Test::copy_file(data_file(what), temp_file)) {
1✔
996
      return "";
×
997
   }
998
   return temp_file;
1✔
999
}
1✔
1000

1001
//static
1002
std::vector<std::string> Test::provider_filter(const std::vector<std::string>& providers) {
49,025✔
1003
   if(m_opts.provider().empty()) {
49,025✔
1004
      return providers;
49,025✔
1005
   }
1006
   for(auto&& provider : providers) {
×
1007
      if(provider == m_opts.provider()) {
×
1008
         return std::vector<std::string>{provider};
×
1009
      }
1010
   }
1011
   return std::vector<std::string>{};
×
1012
}
×
1013

1014
std::string Test::random_password(Botan::RandomNumberGenerator& rng) {
222✔
1015
   const size_t len = 1 + rng.next_byte() % 32;
222✔
1016
   return Botan::hex_encode(rng.random_vec(len));
444✔
1017
}
1018

1019
size_t Test::random_index(Botan::RandomNumberGenerator& rng, size_t max) {
8,062✔
1020
   return Botan::load_be(rng.random_array<8>()) % max;
8,062✔
1021
}
1022

1023
void VarMap::clear() {
34,284✔
1024
   m_vars.clear();
×
1025
}
×
1026

1027
namespace {
1028

1029
bool varmap_pair_lt(const std::pair<std::string, std::string>& kv, const std::string& k) {
1,713,672✔
1030
   return kv.first < k;
1,713,672✔
1031
}
1032

1033
}  // namespace
1034

1035
void VarMap::add(const std::string& key, const std::string& value) {
156,244✔
1036
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
156,244✔
1037

1038
   if(i != m_vars.end() && i->first == key) {
156,244✔
1039
      i->second = value;
44,405✔
1040
   } else {
1041
      m_vars.emplace(i, key, value);
111,839✔
1042
   }
1043
}
156,244✔
1044

1045
std::optional<std::string> VarMap::get_var(const std::string& key) const {
568,470✔
1046
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
568,470✔
1047

1048
   if(i != m_vars.end() && i->first == key) {
568,470✔
1049
      return i->second;
498,609✔
1050
   } else {
1051
      return {};
69,861✔
1052
   }
1053
}
1054

1055
bool VarMap::has_key(const std::string& key) const {
213,583✔
1056
   return get_var(key).has_value();
213,583✔
1057
}
1058

1059
std::string VarMap::get_req_str(const std::string& key) const {
259,638✔
1060
   auto var = get_var(key);
259,638✔
1061
   if(var) {
259,638✔
1062
      return *var;
519,276✔
1063
   } else {
1064
      throw Test_Error("Test missing variable " + key);
×
1065
   }
1066
}
259,638✔
1067

1068
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(const std::string& key) const {
12✔
1069
   const auto var = get_req_str(key);
12✔
1070

1071
   std::vector<std::vector<uint8_t>> bin_list;
12✔
1072

1073
   for(auto&& part : Botan::split_on(var, ',')) {
62✔
1074
      try {
50✔
1075
         bin_list.push_back(Botan::hex_decode(part));
100✔
1076
      } catch(std::exception& e) {
×
1077
         std::ostringstream oss;
×
1078
         oss << "Bad input '" << part << "'"
×
1079
             << " in binary list key " << key << " - " << e.what();
×
1080
         throw Test_Error(oss.str());
×
1081
      }
×
1082
   }
12✔
1083

1084
   return bin_list;
12✔
1085
}
12✔
1086

1087
std::vector<uint8_t> VarMap::get_req_bin(const std::string& key) const {
163,720✔
1088
   const auto var = get_req_str(key);
163,720✔
1089

1090
   try {
163,720✔
1091
      if(var.starts_with("0x")) {
163,720✔
1092
         if(var.size() % 2 == 0) {
×
1093
            return Botan::hex_decode(var.substr(2));
×
1094
         } else {
1095
            std::string z = var;
×
1096
            std::swap(z[0], z[1]);  // swap 0x to x0 then remove x
×
1097
            return Botan::hex_decode(z.substr(1));
×
1098
         }
×
1099
      } else {
1100
         return Botan::hex_decode(var);
163,720✔
1101
      }
1102
   } catch(std::exception& e) {
×
1103
      std::ostringstream oss;
×
1104
      oss << "Bad input '" << var << "'"
×
1105
          << " for key " << key << " - " << e.what();
×
1106
      throw Test_Error(oss.str());
×
1107
   }
×
1108
}
163,720✔
1109

1110
std::string VarMap::get_opt_str(const std::string& key, const std::string& def_value) const {
14,378✔
1111
   if(auto v = get_var(key)) {
14,378✔
1112
      return *v;
57✔
1113
   } else {
1114
      return def_value;
28,699✔
1115
   }
14,378✔
1116
}
1117

1118
bool VarMap::get_req_bool(const std::string& key) const {
39✔
1119
   const auto var = get_req_str(key);
39✔
1120

1121
   if(var == "true") {
39✔
1122
      return true;
1123
   } else if(var == "false") {
23✔
1124
      return false;
1125
   } else {
1126
      throw Test_Error("Invalid boolean for key '" + key + "' value '" + var + "'");
×
1127
   }
1128
}
39✔
1129

1130
size_t VarMap::get_req_sz(const std::string& key) const {
4,547✔
1131
   return Botan::to_u32bit(get_req_str(key));
4,547✔
1132
}
1133

1134
uint8_t VarMap::get_req_u8(const std::string& key) const {
17✔
1135
   const size_t s = this->get_req_sz(key);
17✔
1136
   if(s > 256) {
17✔
1137
      throw Test_Error("Invalid " + key + " expected uint8_t got " + std::to_string(s));
×
1138
   }
1139
   return static_cast<uint8_t>(s);
17✔
1140
}
1141

1142
uint32_t VarMap::get_req_u32(const std::string& key) const {
14✔
1143
   return static_cast<uint32_t>(get_req_sz(key));
14✔
1144
}
1145

1146
uint64_t VarMap::get_req_u64(const std::string& key) const {
17✔
1147
   const auto var = get_req_str(key);
17✔
1148
   try {
17✔
1149
      return std::stoull(var);
17✔
1150
   } catch(std::exception&) {
×
1151
      throw Test_Error("Invalid u64 value '" + var + "'");
×
1152
   }
×
1153
}
17✔
1154

1155
size_t VarMap::get_opt_sz(const std::string& key, const size_t def_value) const {
31,382✔
1156
   if(auto v = get_var(key)) {
31,382✔
1157
      return Botan::to_u32bit(*v);
12,244✔
1158
   } else {
1159
      return def_value;
1160
   }
31,382✔
1161
}
1162

1163
uint64_t VarMap::get_opt_u64(const std::string& key, const uint64_t def_value) const {
3,538✔
1164
   if(auto v = get_var(key)) {
3,538✔
1165
      try {
641✔
1166
         return std::stoull(*v);
3,538✔
1167
      } catch(std::exception&) {
×
1168
         throw Test_Error("Invalid u64 value '" + *v + "'");
×
1169
      }
×
1170
   } else {
1171
      return def_value;
1172
   }
3,538✔
1173
}
×
1174

1175
std::vector<uint8_t> VarMap::get_opt_bin(const std::string& key) const {
45,871✔
1176
   if(auto v = get_var(key)) {
45,871✔
1177
      try {
16,134✔
1178
         return Botan::hex_decode(*v);
16,134✔
1179
      } catch(std::exception&) {
×
1180
         throw Test_Error("Test invalid hex input '" + *v + "'" + +" for key " + key);
×
1181
      }
×
1182
   } else {
1183
      return {};
29,737✔
1184
   };
45,871✔
1185
}
×
1186

1187
#if defined(BOTAN_HAS_BIGINT)
1188
Botan::BigInt VarMap::get_req_bn(const std::string& key) const {
38,502✔
1189
   const auto var = get_req_str(key);
38,502✔
1190

1191
   try {
38,502✔
1192
      return Botan::BigInt(var);
38,502✔
1193
   } catch(std::exception&) {
×
1194
      throw Test_Error("Test invalid bigint input '" + var + "' for key " + key);
×
1195
   }
×
1196
}
38,502✔
1197

1198
Botan::BigInt VarMap::get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const {
80✔
1199
   if(auto v = get_var(key)) {
80✔
1200
      try {
56✔
1201
         return Botan::BigInt(*v);
56✔
1202
      } catch(std::exception&) {
×
1203
         throw Test_Error("Test invalid bigint input '" + *v + "' for key " + key);
×
1204
      }
×
1205
   } else {
1206
      return def_value;
24✔
1207
   }
80✔
1208
}
×
1209
#endif
1210

1211
class Text_Based_Test::Text_Based_Test_Data {
1212
   public:
1213
      Text_Based_Test_Data(const std::string& data_src,
181✔
1214
                           const std::string& required_keys_str,
1215
                           const std::string& optional_keys_str) :
181✔
1216
            m_data_src(data_src) {
362✔
1217
         if(required_keys_str.empty()) {
181✔
1218
            throw Test_Error("Invalid test spec");
×
1219
         }
1220

1221
         m_required_keys = Botan::split_on(required_keys_str, ',');
181✔
1222
         std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
181✔
1223

1224
         m_all_keys.insert(m_required_keys.begin(), m_required_keys.end());
181✔
1225
         m_all_keys.insert(optional_keys.begin(), optional_keys.end());
181✔
1226
         m_output_key = m_required_keys.at(m_required_keys.size() - 1);
181✔
1227
      }
181✔
1228

1229
      std::string get_next_line();
1230

1231
      const std::string& current_source_name() const { return m_cur_src_name; }
×
1232

1233
      bool known_key(const std::string& key) const;
1234

1235
      const std::vector<std::string>& required_keys() const { return m_required_keys; }
48,391✔
1236

1237
      const std::string& output_key() const { return m_output_key; }
156,244✔
1238

1239
      const std::vector<std::string>& cpu_flags() const { return m_cpu_flags; }
48,252✔
1240

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

1243
      const std::string& initial_data_src_name() const { return m_data_src; }
181✔
1244

1245
   private:
1246
      std::string m_data_src;
1247
      std::vector<std::string> m_required_keys;
1248
      std::unordered_set<std::string> m_all_keys;
1249
      std::string m_output_key;
1250

1251
      bool m_first = true;
1252
      std::unique_ptr<std::istream> m_cur;
1253
      std::string m_cur_src_name;
1254
      std::deque<std::string> m_srcs;
1255
      std::vector<std::string> m_cpu_flags;
1256
};
1257

1258
Text_Based_Test::Text_Based_Test(const std::string& data_src,
181✔
1259
                                 const std::string& required_keys,
1260
                                 const std::string& optional_keys) :
181✔
1261
      m_data(std::make_unique<Text_Based_Test_Data>(data_src, required_keys, optional_keys)) {}
181✔
1262

1263
Text_Based_Test::~Text_Based_Test() = default;
181✔
1264

1265
std::string Text_Based_Test::Text_Based_Test_Data::get_next_line() {
157,251✔
1266
   while(true) {
157,509✔
1267
      if(m_cur == nullptr || m_cur->good() == false) {
157,509✔
1268
         if(m_srcs.empty()) {
450✔
1269
            if(m_first) {
362✔
1270
               if(m_data_src.ends_with(".vec")) {
181✔
1271
                  m_srcs.push_back(Test::data_file(m_data_src));
338✔
1272
               } else {
1273
                  const auto fs = Test::files_in_data_dir(m_data_src);
12✔
1274
                  m_srcs.assign(fs.begin(), fs.end());
12✔
1275
                  if(m_srcs.empty()) {
12✔
1276
                     throw Test_Error("Error reading test data dir " + m_data_src);
×
1277
                  }
1278
               }
12✔
1279

1280
               m_first = false;
181✔
1281
            } else {
1282
               return "";  // done
181✔
1283
            }
1284
         }
1285

1286
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
357✔
1287
         m_cur_src_name = m_srcs[0];
269✔
1288

1289
#if defined(BOTAN_HAS_CPUID)
1290
         // Reinit cpuid on new file if needed
1291
         if(m_cpu_flags.empty() == false) {
269✔
1292
            m_cpu_flags.clear();
19✔
1293
            Botan::CPUID::initialize();
19✔
1294
         }
1295
#endif
1296

1297
         if(!m_cur->good()) {
269✔
1298
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
1299
         }
1300

1301
         m_srcs.pop_front();
269✔
1302
      }
1303

1304
      while(m_cur->good()) {
227,909✔
1305
         std::string line;
227,651✔
1306
         std::getline(*m_cur, line);
227,651✔
1307

1308
         if(line.empty()) {
227,651✔
1309
            continue;
55,313✔
1310
         }
1311

1312
         if(line[0] == '#') {
172,338✔
1313
            if(line.starts_with("#test ")) {
15,289✔
1314
               return line;
21✔
1315
            } else {
1316
               continue;
15,268✔
1317
            }
1318
         }
1319

1320
         return line;
157,049✔
1321
      }
227,651✔
1322
   }
1323
}
1324

1325
bool Text_Based_Test::Text_Based_Test_Data::known_key(const std::string& key) const {
156,244✔
1326
   return m_all_keys.contains(key);
156,244✔
1327
}
1328

1329
namespace {
1330

1331
// strips leading and trailing but not internal whitespace
1332
std::string strip_ws(const std::string& in) {
312,488✔
1333
   const char* whitespace = " ";
312,488✔
1334

1335
   const auto first_c = in.find_first_not_of(whitespace);
312,488✔
1336
   if(first_c == std::string::npos) {
312,488✔
1337
      return "";
1,034✔
1338
   }
1339

1340
   const auto last_c = in.find_last_not_of(whitespace);
311,454✔
1341

1342
   return in.substr(first_c, last_c - first_c + 1);
311,454✔
1343
}
1344

1345
std::vector<std::string> parse_cpuid_bits(const std::vector<std::string>& tok) {
21✔
1346
   std::vector<std::string> bits;
21✔
1347

1348
#if defined(BOTAN_HAS_CPUID)
1349
   for(size_t i = 1; i < tok.size(); ++i) {
106✔
1350
      if(auto bit = Botan::CPUID::bit_from_string(tok[i])) {
85✔
1351
         bits.push_back(bit->to_string());
98✔
1352
      }
1353
   }
1354
#else
1355
   BOTAN_UNUSED(tok);
1356
#endif
1357

1358
   return bits;
21✔
1359
}
×
1360

1361
}  // namespace
1362

1363
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) {
32,612✔
1364
   return false;
32,612✔
1365
}
1366

1367
std::vector<Test::Result> Text_Based_Test::run() {
181✔
1368
   std::vector<Test::Result> results;
181✔
1369

1370
   std::string header;
181✔
1371
   std::string header_or_name = m_data->initial_data_src_name();
181✔
1372
   VarMap vars;
181✔
1373
   size_t test_cnt = 0;
181✔
1374

1375
   while(true) {
157,251✔
1376
      const std::string line = m_data->get_next_line();
157,251✔
1377
      if(line.empty()) {
157,251✔
1378
         // EOF
1379
         break;
1380
      }
1381

1382
      if(line.starts_with("#test ")) {
157,070✔
1383
         std::vector<std::string> pragma_tokens = Botan::split_on(line.substr(6), ' ');
21✔
1384

1385
         if(pragma_tokens.empty()) {
21✔
1386
            throw Test_Error("Empty pragma found in " + m_data->current_source_name());
×
1387
         }
1388

1389
         if(pragma_tokens[0] != "cpuid") {
21✔
1390
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1391
         }
1392

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

1397
         m_data->set_cpu_flags(parse_cpuid_bits(pragma_tokens));
42✔
1398

1399
         continue;
21✔
1400
      } else if(line[0] == '#') {
157,070✔
1401
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1402
      }
1403

1404
      if(line[0] == '[' && line[line.size() - 1] == ']') {
157,049✔
1405
         header = line.substr(1, line.size() - 2);
805✔
1406
         header_or_name = header;
805✔
1407
         test_cnt = 0;
805✔
1408
         vars.clear();
805✔
1409
         continue;
805✔
1410
      }
1411

1412
      const std::string test_id = "test " + std::to_string(test_cnt);
312,488✔
1413

1414
      auto equal_i = line.find_first_of('=');
156,244✔
1415

1416
      if(equal_i == std::string::npos) {
156,244✔
1417
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1418
         continue;
×
1419
      }
1420

1421
      const std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
312,488✔
1422
      const std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
312,488✔
1423

1424
      if(!m_data->known_key(key)) {
156,244✔
1425
         auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key));
×
1426
         results.push_back(r);
×
1427
      }
×
1428

1429
      vars.add(key, val);
156,244✔
1430

1431
      if(key == m_data->output_key()) {
156,244✔
1432
         try {
48,391✔
1433
            for(const auto& req_key : m_data->required_keys()) {
245,566✔
1434
               if(!vars.has_key(req_key)) {
197,175✔
1435
                  auto r =
×
1436
                     Test::Result::Failure(header_or_name, Botan::fmt("{} missing required key {}", test_id, req_key));
×
1437
                  results.push_back(r);
×
1438
               }
×
1439
            }
1440

1441
            if(skip_this_test(header, vars)) {
48,391✔
1442
               continue;
139✔
1443
            }
1444

1445
            ++test_cnt;
48,252✔
1446

1447
            const uint64_t start = Test::timestamp();
48,252✔
1448

1449
            Test::Result result = run_one_test(header, vars);
48,252✔
1450
#if defined(BOTAN_HAS_CPUID)
1451
            if(!m_data->cpu_flags().empty()) {
48,252✔
1452
               for(const auto& cpuid_str : m_data->cpu_flags()) {
30,633✔
1453
                  if(const auto bit = Botan::CPUID::Feature::from_string(cpuid_str)) {
21,686✔
1454
                     if(Botan::CPUID::has(*bit)) {
21,686✔
1455
                        Botan::CPUID::clear_cpuid_bit(*bit);
16,577✔
1456
                        // now re-run the test
1457
                        result.merge(run_one_test(header, vars));
16,577✔
1458
                     }
1459
                  }
1460
               }
1461
               Botan::CPUID::initialize();
8,947✔
1462
            }
1463
#endif
1464
            result.set_ns_consumed(Test::timestamp() - start);
48,252✔
1465

1466
            if(result.tests_failed() > 0) {
48,252✔
1467
               std::ostringstream oss;
×
1468
               oss << "Test # " << test_cnt << " ";
×
1469
               if(!header.empty()) {
×
1470
                  oss << header << " ";
×
1471
               }
1472
               oss << "failed ";
×
1473

1474
               for(const auto& k : m_data->required_keys()) {
×
1475
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1476
               }
1477

1478
               result.test_note(oss.str());
×
1479
            }
×
1480
            results.push_back(result);
48,252✔
1481
         } catch(std::exception& e) {
48,252✔
1482
            std::ostringstream oss;
×
1483
            oss << "Test # " << test_cnt << " ";
×
1484
            if(!header.empty()) {
×
1485
               oss << header << " ";
×
1486
            }
1487

1488
            for(const auto& k : m_data->required_keys()) {
×
1489
               oss << k << "=" << vars.get_req_str(k) << " ";
×
1490
            }
1491

1492
            oss << "failed with exception '" << e.what() << "'";
×
1493

1494
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1495
         }
×
1496

1497
         if(clear_between_callbacks()) {
48,252✔
1498
            vars.clear();
189,584✔
1499
         }
1500
      }
1501
   }
157,348✔
1502

1503
   if(results.empty()) {
181✔
1504
      return results;
1505
   }
1506

1507
   try {
181✔
1508
      std::vector<Test::Result> final_tests = run_final_tests();
181✔
1509
      results.insert(results.end(), final_tests.begin(), final_tests.end());
181✔
1510
   } catch(std::exception& e) {
181✔
1511
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1512
   }
×
1513

1514
   return results;
1515
}
181✔
1516

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