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

randombit / botan / 21989216571

13 Feb 2026 01:49PM UTC coverage: 90.07% (+0.004%) from 90.066%
21989216571

Pull #5327

github

web-flow
Merge 0e74fc899 into 2640927f7
Pull Request #5327: Various cleanups for tests.h

102221 of 113490 relevant lines covered (90.07%)

11420666.65 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::Test() = default;
419✔
57

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

60
Test::Result::Result(std::string_view who) : m_who(who), m_timestamp(Test::timestamp()) {}
81,123✔
61

62
Test::Result::Result(std::string_view who, const std::vector<Result>& downstream_results) : Result(who) {
14✔
63
   for(const auto& result : downstream_results) {
82✔
64
      merge(result, true /* ignore non-matching test names */);
68✔
65
   }
66
}
14✔
67

68
void Test::Result::merge(const Result& other, bool ignore_test_name) {
126,759✔
69
   if(who() != other.who()) {
126,759✔
70
      if(!ignore_test_name) {
73✔
71
         throw Test_Error("Merging tests from different sources");
×
72
      }
73

74
      // When deliberately merging results with different names, the code location is
75
      // likely inconsistent and must be discarded.
76
      m_where.reset();
73✔
77
   } else {
78
      m_where = other.m_where;
126,686✔
79
   }
80

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

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

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

101
void Test::Result::test_note(std::string_view who, std::span<const uint8_t> data) {
12✔
102
   const std::string hex = Botan::hex_encode(data);
12✔
103
   return test_note(who, hex.c_str());
12✔
104
}
12✔
105

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

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

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

127
bool Test::Result::ThrowExpectations::check(const std::string& test_name, Test::Result& result) {
67,783✔
128
   m_consumed = true;
67,783✔
129

130
   try {
67,783✔
131
      m_fn();
67,783✔
132
      if(!m_expect_success) {
1,646✔
133
         return result.test_failure(test_name + " failed to throw expected exception");
2✔
134
      }
135
   } catch(const std::exception& ex) {
66,137✔
136
      if(m_expect_success) {
66,135✔
137
         return result.test_failure(test_name + " threw unexpected exception: " + ex.what());
2✔
138
      }
139
      if(m_expected_exception_check_fn && !m_expected_exception_check_fn(std::current_exception())) {
190,230✔
140
         return result.test_failure(test_name + " threw unexpected exception: " + ex.what());
4✔
141
      }
142
      if(m_expected_message.has_value() && m_expected_message.value() != ex.what()) {
66,132✔
143
         return result.test_failure(test_name + " threw exception with unexpected message (expected: '" +
3✔
144
                                    m_expected_message.value() + "', got: '" + ex.what() + "')");
6✔
145
      }
146
   } catch(...) {
66,137✔
147
      if(m_expect_success || m_expected_exception_check_fn || m_expected_message.has_value()) {
2✔
148
         return result.test_failure(test_name + " threw unexpected unknown exception");
1✔
149
      }
150
   }
2✔
151

152
   return result.test_success(test_name + " behaved as expected");
135,552✔
153
}
154

155
bool Test::Result::test_throws(const std::string& what, const std::function<void()>& fn) {
3,916✔
156
   return ThrowExpectations(fn).check(what, *this);
7,832✔
157
}
158

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

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

167
bool Test::Result::test_success(std::string_view note) {
3,620,258✔
168
   if(Test::options().log_success()) {
3,620,258✔
169
      test_note(note);
×
170
   }
171
   ++m_tests_passed;
3,620,258✔
172
   return true;
775,703✔
173
}
174

175
bool Test::Result::test_failure(std::string_view what, std::string_view error) {
1✔
176
   return test_failure(Botan::fmt("{} {} with error {}", who(), what, error));
1✔
177
}
178

179
void Test::Result::test_failure(std::string_view what, const uint8_t buf[], size_t buf_len) {
×
180
   return test_failure(what, {buf, buf_len});
×
181
}
182

183
void Test::Result::test_failure(std::string_view what, std::span<const uint8_t> context) {
1✔
184
   test_failure(Botan::fmt("{} {} with value {}", who(), what, Botan::hex_encode(context)));
1✔
185
}
1✔
186

187
bool Test::Result::test_failure(std::string_view err) {
25✔
188
   m_fail_log.push_back(std::string(err));
25✔
189

190
   if(Test::options().abort_on_first_fail() && m_who != "Failing Test") {
25✔
191
      std::abort();
×
192
   }
193
   return false;
25✔
194
}
195

196
namespace {
197

198
bool same_contents(const uint8_t x[], const uint8_t y[], size_t len) {
292,412✔
199
   return (len == 0) ? true : std::memcmp(x, y, len) == 0;
290,981✔
200
}
201

202
}  // namespace
203

204
bool Test::Result::test_ne(const std::string& what,
3,407✔
205
                           const uint8_t produced[],
206
                           size_t produced_len,
207
                           const uint8_t expected[],
208
                           size_t expected_len) {
209
   if(produced_len == expected_len && same_contents(produced, expected, expected_len)) {
3,407✔
210
      return test_failure(who() + ": " + what + " produced matching");
6✔
211
   }
212
   return test_success();
3,405✔
213
}
214

215
bool Test::Result::test_eq(const std::string& what, std::span<const uint8_t> produced, const char* expected_hex) {
453✔
216
   const std::vector<uint8_t> expected = Botan::hex_decode(expected_hex);
453✔
217
   return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
453✔
218
}
453✔
219

220
bool Test::Result::test_eq(const char* producer,
290,963✔
221
                           const std::string& what,
222
                           const uint8_t produced[],
223
                           size_t produced_size,
224
                           const uint8_t expected[],
225
                           size_t expected_size) {
226
   if(produced_size == expected_size && same_contents(produced, expected, expected_size)) {
290,963✔
227
      return test_success();
290,962✔
228
   }
229

230
   std::ostringstream err;
1✔
231

232
   err << who();
1✔
233

234
   if(producer != nullptr) {
1✔
235
      err << " producer '" << producer << "'";
×
236
   }
237

238
   err << " unexpected result for " << what;
1✔
239

240
   if(produced_size != expected_size) {
1✔
241
      err << " produced " << produced_size << " bytes expected " << expected_size;
1✔
242
   }
243

244
   std::vector<uint8_t> xor_diff(std::min(produced_size, expected_size));
2✔
245
   size_t bytes_different = 0;
1✔
246

247
   for(size_t i = 0; i != xor_diff.size(); ++i) {
4✔
248
      xor_diff[i] = produced[i] ^ expected[i];
3✔
249
      if(xor_diff[i] > 0) {
3✔
250
         bytes_different++;
3✔
251
      }
252
   }
253

254
   err << "\nProduced: " << Botan::hex_encode(produced, produced_size)
1✔
255
       << "\nExpected: " << Botan::hex_encode(expected, expected_size);
3✔
256

257
   if(bytes_different > 0) {
1✔
258
      err << "\nXOR Diff: " << Botan::hex_encode(xor_diff);
1✔
259
   }
260

261
   return test_failure(err.str());
1✔
262
}
1✔
263

264
bool Test::Result::test_is_nonempty(const std::string& what_is_it, const std::string& to_examine) {
38,829✔
265
   if(to_examine.empty()) {
38,829✔
266
      return test_failure(what_is_it + " was empty");
1✔
267
   }
268
   return test_success();
38,828✔
269
}
270

271
bool Test::Result::test_eq(const std::string& what, const std::string& produced, const std::string& expected) {
76,783✔
272
   return test_is_eq(what, produced, expected);
76,783✔
273
}
274

275
bool Test::Result::test_eq(const std::string& what, const char* produced, const char* expected) {
29✔
276
   return test_is_eq(what, std::string(produced), std::string(expected));
29✔
277
}
278

279
bool Test::Result::test_eq(const std::string& what, size_t produced, size_t expected) {
146,710✔
280
   return test_is_eq(what, produced, expected);
146,710✔
281
}
282

283
bool Test::Result::test_eq_sz(const std::string& what, size_t produced, size_t expected) {
45,789✔
284
   return test_is_eq(what, produced, expected);
45,789✔
285
}
286

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

295
   return test_success();
5,638✔
296
}
297

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

305
   return test_success();
1,021,635✔
306
}
307

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

317
   return test_success();
1,142,429✔
318
}
319

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

329
   return test_success();
22,373✔
330
}
331

332
bool Test::Result::test_ne(const std::string& what, const std::string& str1, const std::string& str2) {
26✔
333
   if(str1 != str2) {
26✔
334
      return test_success(str1 + " != " + str2);
50✔
335
   }
336

337
   return test_failure(who() + " " + what + " produced matching strings " + str1);
4✔
338
}
339

340
bool Test::Result::test_ne(const std::string& what, size_t produced, size_t expected) {
119✔
341
   if(produced != expected) {
119✔
342
      return test_success();
118✔
343
   }
344

345
   std::ostringstream err;
1✔
346
   err << who() << " " << what << " produced " << produced << " unexpected value";
1✔
347
   return test_failure(err.str());
1✔
348
}
1✔
349

350
#if defined(BOTAN_HAS_BIGINT)
351
bool Test::Result::test_eq(const std::string& what, const BigInt& produced, const BigInt& expected) {
252,631✔
352
   return test_is_eq(what, produced, expected);
252,631✔
353
}
354

355
bool Test::Result::test_ne(const std::string& what, const BigInt& produced, const BigInt& expected) {
97✔
356
   if(produced != expected) {
97✔
357
      return test_success();
96✔
358
   }
359

360
   std::ostringstream err;
1✔
361
   err << who() << " " << what << " produced " << produced << " prohibited value";
1✔
362
   return test_failure(err.str());
1✔
363
}
1✔
364
#endif
365

366
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
367
bool Test::Result::test_eq(const std::string& what, const Botan::EC_Point& a, const Botan::EC_Point& b) {
3,248✔
368
   //return test_is_eq(what, a, b);
369
   if(a == b) {
3,248✔
370
      return test_success();
3,248✔
371
   }
372

373
   std::ostringstream err;
×
374
   err << who() << " " << what << " a=(" << a.get_affine_x() << "," << a.get_affine_y() << ")"
×
375
       << " b=(" << b.get_affine_x() << "," << b.get_affine_y();
×
376
   return test_failure(err.str());
×
377
}
×
378
#endif
379

380
bool Test::Result::test_eq(const std::string& what, bool produced, bool expected) {
378,485✔
381
   return test_is_eq(what, produced, expected);
378,485✔
382
}
383

384
bool Test::Result::test_rc_ok(const std::string& func, int rc) {
2,810✔
385
   if(rc != 0) {
2,810✔
386
      std::ostringstream err;
1✔
387
      err << m_who << " " << func << " unexpectedly failed with error code " << rc;
1✔
388
      return test_failure(err.str());
1✔
389
   }
1✔
390

391
   return test_success();
2,809✔
392
}
393

394
bool Test::Result::test_rc_fail(const std::string& func, const std::string& why, int rc) {
26✔
395
   if(rc == 0) {
26✔
396
      std::ostringstream err;
1✔
397
      err << m_who << " call to " << func << " unexpectedly succeeded expecting failure because " << why;
1✔
398
      return test_failure(err.str());
1✔
399
   }
1✔
400

401
   return test_success();
25✔
402
}
403

404
bool Test::Result::test_rc_init(const std::string& func, int rc) {
117✔
405
   if(rc == 0) {
117✔
406
      return test_success();
117✔
407
   } else {
408
      std::ostringstream msg;
×
409
      msg << m_who;
×
410
      msg << " " << func;
×
411

412
      // -40 is BOTAN_FFI_ERROR_NOT_IMPLEMENTED
413
      if(rc == -40) {
×
414
         msg << " returned not implemented";
×
415
      } else {
416
         msg << " unexpectedly failed with error code " << rc;
×
417
      }
418

419
      if(rc == -40) {
×
420
         this->test_note(msg.str());
×
421
      } else {
422
         this->test_failure(msg.str());
×
423
      }
424
      return false;
×
425
   }
×
426
}
427

428
bool Test::Result::test_rc(const std::string& func, int expected, int rc) {
416✔
429
   if(expected != rc) {
416✔
430
      std::ostringstream err;
1✔
431
      err << m_who;
1✔
432
      err << " call to " << func << " unexpectedly returned " << rc;
1✔
433
      err << " but expecting " << expected;
1✔
434
      return test_failure(err.str());
1✔
435
   }
1✔
436

437
   return test_success();
415✔
438
}
439

440
void Test::initialize(std::string test_name, CodeLocation location) {
419✔
441
   m_test_name = std::move(test_name);
419✔
442
   m_registration_location = location;
419✔
443
}
419✔
444

445
Botan::RandomNumberGenerator& Test::rng() const {
464,975✔
446
   if(!m_test_rng) {
464,975✔
447
      m_test_rng = Test::new_rng(m_test_name);
145✔
448
   }
449

450
   return *m_test_rng;
464,975✔
451
}
452

453
std::optional<std::string> Test::supported_ec_group_name(std::vector<std::string> preferred_groups) {
151✔
454
#if defined(BOTAN_HAS_ECC_GROUP)
455
   if(preferred_groups.empty()) {
151✔
456
      preferred_groups = {
149✔
457
         "secp256r1",
458
         "brainpool256r1",
459
         "secp384r1",
460
         "brainpool384r1",
461
         "secp521r1",
462
         "brainpool512r1",
463
      };
1,192✔
464
   }
465

466
   for(const auto& group : preferred_groups) {
151✔
467
      if(Botan::EC_Group::supports_named_group(group)) {
151✔
468
         return group;
151✔
469
      }
470
   }
471
#else
472
   BOTAN_UNUSED(preferred_groups);
473
#endif
474

475
   return std::nullopt;
×
476
}
298✔
477

478
std::vector<uint8_t> Test::mutate_vec(const std::vector<uint8_t>& v,
96,742✔
479
                                      Botan::RandomNumberGenerator& rng,
480
                                      bool maybe_resize,
481
                                      size_t min_offset) {
482
   std::vector<uint8_t> r = v;
96,742✔
483

484
   if(maybe_resize && (r.empty() || rng.next_byte() < 32)) {
110,318✔
485
      // TODO: occasionally truncate, insert at random index
486
      const size_t add = 1 + (rng.next_byte() % 16);
2,121✔
487
      r.resize(r.size() + add);
2,121✔
488
      rng.randomize(&r[r.size() - add], add);
2,121✔
489
   }
490

491
   if(r.size() > min_offset) {
96,742✔
492
      const size_t offset = std::max<size_t>(min_offset, rng.next_byte() % r.size());
95,204✔
493
      const uint8_t perturb = rng.next_nonzero_byte();
95,204✔
494
      r[offset] ^= perturb;
95,204✔
495
   }
496

497
   return r;
96,742✔
498
}
×
499

500
std::vector<std::string> Test::possible_providers(const std::string& /*alg*/) {
×
501
   return Test::provider_filter({"base"});
×
502
}
503

504
//static
505
std::string Test::format_time(uint64_t nanoseconds) {
1,470✔
506
   std::ostringstream o;
1,470✔
507

508
   if(nanoseconds > 1000000000) {
1,470✔
509
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000000.0 << " sec";
163✔
510
   } else {
511
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000.0 << " msec";
1,307✔
512
   }
513

514
   return o.str();
2,940✔
515
}
1,470✔
516

517
// TODO: this should move to `StdoutReporter`
518
std::string Test::Result::result_string() const {
2,540✔
519
   const bool verbose = Test::options().verbose();
2,540✔
520

521
   if(tests_run() == 0 && !verbose) {
2,540✔
522
      return "";
20✔
523
   }
524

525
   std::ostringstream report;
2,520✔
526

527
   report << who() << " ran ";
2,520✔
528

529
   if(tests_run() == 0) {
2,520✔
530
      report << "ZERO";
×
531
   } else {
532
      report << tests_run();
2,520✔
533
   }
534
   report << " tests";
2,520✔
535

536
   if(m_ns_taken > 0) {
2,520✔
537
      report << " in " << format_time(m_ns_taken);
2,938✔
538
   }
539

540
   if(tests_failed() > 0) {
2,520✔
541
      report << " " << tests_failed() << " FAILED";
25✔
542
   } else {
543
      report << " all ok";
2,495✔
544
   }
545

546
   report << "\n";
2,520✔
547

548
   for(size_t i = 0; i != m_fail_log.size(); ++i) {
2,545✔
549
      report << "Failure " << (i + 1) << ": " << m_fail_log[i];
25✔
550
      if(m_where) {
25✔
551
         report << " (at " << m_where->path << ":" << m_where->line << ")";
×
552
      }
553
      report << "\n";
25✔
554
   }
555

556
   if(!m_fail_log.empty() || tests_run() == 0 || verbose) {
2,520✔
557
      for(size_t i = 0; i != m_log.size(); ++i) {
25✔
558
         report << "Note " << (i + 1) << ": " << m_log[i] << "\n";
×
559
      }
560
   }
561

562
   return report.str();
2,520✔
563
}
2,520✔
564

565
namespace {
566

567
class Test_Registry {
568
   public:
569
      static Test_Registry& instance() {
1,279✔
570
         static Test_Registry registry;
1,280✔
571
         return registry;
1,279✔
572
      }
573

574
      void register_test(const std::string& category,
419✔
575
                         const std::string& name,
576
                         bool smoke_test,
577
                         bool needs_serialization,
578
                         std::function<std::unique_ptr<Test>()> maker_fn) {
579
         if(m_tests.contains(name)) {
419✔
580
            throw Test_Error("Duplicate registration of test '" + name + "'");
×
581
         }
582

583
         if(m_tests.contains(category)) {
419✔
584
            throw Test_Error("'" + category + "' cannot be used as category, test exists");
×
585
         }
586

587
         if(m_categories.contains(name)) {
419✔
588
            throw Test_Error("'" + name + "' cannot be used as test name, category exists");
×
589
         }
590

591
         if(smoke_test) {
419✔
592
            m_smoke_tests.push_back(name);
10✔
593
         }
594

595
         if(needs_serialization) {
419✔
596
            m_mutexed_tests.push_back(name);
21✔
597
         }
598

599
         m_tests.emplace(name, std::move(maker_fn));
419✔
600
         m_categories.emplace(category, name);
419✔
601
      }
419✔
602

603
      std::unique_ptr<Test> get_test(const std::string& test_name) const {
419✔
604
         auto i = m_tests.find(test_name);
419✔
605
         if(i != m_tests.end()) {
419✔
606
            return i->second();
419✔
607
         }
608
         return nullptr;
×
609
      }
610

611
      std::vector<std::string> registered_tests() const {
×
612
         std::vector<std::string> s;
×
613
         s.reserve(m_tests.size());
×
614
         for(auto&& i : m_tests) {
×
615
            s.push_back(i.first);
×
616
         }
617
         return s;
×
618
      }
×
619

620
      std::vector<std::string> registered_test_categories() const {
×
621
         std::set<std::string> s;
×
622
         for(auto&& i : m_categories) {
×
623
            s.insert(i.first);
×
624
         }
625
         return std::vector<std::string>(s.begin(), s.end());
×
626
      }
×
627

628
      std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
1✔
629
                                                       const std::vector<std::string>& to_be_skipped) {
630
         std::vector<std::string> result;
1✔
631

632
         std::set<std::string> to_be_skipped_set(to_be_skipped.begin(), to_be_skipped.end());
1✔
633
         // TODO: this is O(n^2), but we have a relatively small number of tests.
634
         auto insert_if_not_exists_and_not_skipped = [&](const std::string& test_name) {
420✔
635
            if(!Botan::value_exists(result, test_name) && !to_be_skipped_set.contains(test_name)) {
838✔
636
               result.push_back(test_name);
409✔
637
            }
638
         };
420✔
639

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

664
         return result;
1✔
665
      }
1✔
666

667
      bool needs_serialization(const std::string& test_name) const {
440✔
668
         return Botan::value_exists(m_mutexed_tests, test_name);
21✔
669
      }
670

671
   private:
672
      Test_Registry() = default;
1✔
673

674
   private:
675
      std::map<std::string, std::function<std::unique_ptr<Test>()>> m_tests;
676
      std::multimap<std::string, std::string> m_categories;
677
      std::vector<std::string> m_smoke_tests;
678
      std::vector<std::string> m_mutexed_tests;
679
};
680

681
}  // namespace
682

683
// static Test:: functions
684

685
//static
686
void Test::register_test(const std::string& category,
419✔
687
                         const std::string& name,
688
                         bool smoke_test,
689
                         bool needs_serialization,
690
                         std::function<std::unique_ptr<Test>()> maker_fn) {
691
   Test_Registry::instance().register_test(category, name, smoke_test, needs_serialization, std::move(maker_fn));
838✔
692
}
419✔
693

694
//static
695
uint64_t Test::timestamp() {
180,010✔
696
   auto now = std::chrono::system_clock::now().time_since_epoch();
180,010✔
697
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
2,383✔
698
}
699

700
//static
701
std::vector<Test::Result> Test::flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists) {
4✔
702
   std::vector<Test::Result> results;
4✔
703
   for(auto& result_list : result_lists) {
26✔
704
      for(auto& result : result_list) {
71✔
705
         results.emplace_back(std::move(result));
49✔
706
      }
707
   }
708
   return results;
4✔
709
}
×
710

711
//static
712
std::vector<std::string> Test::registered_tests() {
×
713
   return Test_Registry::instance().registered_tests();
×
714
}
715

716
//static
717
std::vector<std::string> Test::registered_test_categories() {
×
718
   return Test_Registry::instance().registered_test_categories();
×
719
}
720

721
//static
722
std::unique_ptr<Test> Test::get_test(const std::string& test_name) {
419✔
723
   return Test_Registry::instance().get_test(test_name);
419✔
724
}
725

726
//static
727
bool Test::test_needs_serialization(const std::string& test_name) {
419✔
728
   return Test_Registry::instance().needs_serialization(test_name);
419✔
729
}
730

731
//static
732
std::vector<std::string> Test::filter_registered_tests(const std::vector<std::string>& requested,
1✔
733
                                                       const std::vector<std::string>& to_be_skipped) {
734
   return Test_Registry::instance().filter_registered_tests(requested, to_be_skipped);
1✔
735
}
736

737
//static
738
std::string Test::temp_file_name(const std::string& basename) {
21✔
739
   // TODO add a --tmp-dir option to the tests to specify where these files go
740

741
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
742

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

746
   const int fd = ::mkstemp(mkstemp_basename.data());
21✔
747

748
   // error
749
   if(fd < 0) {
21✔
750
      return "";
×
751
   }
752

753
   ::close(fd);
21✔
754

755
   return mkstemp_basename;
21✔
756
#else
757
   // For now just create the temp in the current working directory
758
   return basename;
759
#endif
760
}
21✔
761

762
bool Test::copy_file(const std::string& from, const std::string& to) {
1✔
763
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(__cpp_lib_filesystem)
764
   std::error_code ec;  // don't throw, just return false on error
1✔
765
   return std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
1✔
766
#else
767
   // TODO: implement fallbacks to POSIX or WIN32
768
   // ... but then again: it's 2023 and we're using C++20 :o)
769
   BOTAN_UNUSED(from, to);
770
   throw Botan::No_Filesystem_Access();
771
#endif
772
}
773

774
std::string Test::read_data_file(const std::string& path) {
38✔
775
   const std::string fsname = Test::data_file(path);
38✔
776
   std::ifstream file(fsname.c_str());
38✔
777
   if(!file.good()) {
38✔
778
      throw Test_Error("Error reading from " + fsname);
×
779
   }
780

781
   return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
76✔
782
}
38✔
783

784
std::vector<uint8_t> Test::read_binary_data_file(const std::string& path) {
34✔
785
   const std::string fsname = Test::data_file(path);
34✔
786
   std::ifstream file(fsname.c_str(), std::ios::binary);
34✔
787
   if(!file.good()) {
34✔
788
      throw Test_Error("Error reading from " + fsname);
×
789
   }
790

791
   std::vector<uint8_t> contents;
34✔
792

793
   while(file.good()) {
74✔
794
      std::vector<uint8_t> buf(4096);
40✔
795
      file.read(reinterpret_cast<char*>(buf.data()), buf.size());
40✔
796
      const size_t got = static_cast<size_t>(file.gcount());
40✔
797

798
      if(got == 0 && file.eof()) {
40✔
799
         break;
800
      }
801

802
      contents.insert(contents.end(), buf.data(), buf.data() + got);
40✔
803
   }
40✔
804

805
   return contents;
68✔
806
}
34✔
807

808
// static member variables of Test
809

810
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
811
Test_Options Test::m_opts;
812
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
813
std::string Test::m_test_rng_seed;
814

815
//static
816
void Test::set_test_options(const Test_Options& opts) {
1✔
817
   m_opts = opts;
1✔
818
}
1✔
819

820
namespace {
821

822
/*
823
* This is a fast, simple, deterministic PRNG that's used for running
824
* the tests. It is not intended to be cryptographically secure.
825
*/
826
class Testsuite_RNG final : public Botan::RandomNumberGenerator {
8✔
827
   public:
828
      std::string name() const override { return "Testsuite_RNG"; }
×
829

830
      void clear() override { m_x = 0; }
×
831

832
      bool accepts_input() const override { return true; }
×
833

834
      bool is_seeded() const override { return true; }
277,207✔
835

836
      void fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) override {
10,230,313✔
837
         for(const auto byte : input) {
10,230,313✔
838
            mix(byte);
×
839
         }
840

841
         for(auto& byte : output) {
73,422,033✔
842
            byte = mix();
63,191,720✔
843
         }
844
      }
10,230,313✔
845

846
      Testsuite_RNG(std::string_view seed, std::string_view test_name) : m_x(0) {
276✔
847
         for(const char c : seed) {
8,280✔
848
            this->mix(static_cast<uint8_t>(c));
8,004✔
849
         }
850
         for(const char c : test_name) {
5,578✔
851
            this->mix(static_cast<uint8_t>(c));
5,302✔
852
         }
853
      }
276✔
854

855
   private:
856
      uint8_t mix(uint8_t input = 0) {
63,205,026✔
857
         m_x ^= input;
63,205,026✔
858
         m_x *= 0xF2E16957;
63,205,026✔
859
         m_x += 0xE50B590F;
63,205,026✔
860
         return static_cast<uint8_t>(m_x >> 27);
63,205,026✔
861
      }
862

863
      uint64_t m_x;
864
};
865

866
}  // namespace
867

868
//static
869
void Test::set_test_rng_seed(std::span<const uint8_t> seed, size_t epoch) {
1✔
870
   m_test_rng_seed = Botan::fmt("seed={} epoch={}", Botan::hex_encode(seed), epoch);
1✔
871
}
1✔
872

873
//static
874
std::unique_ptr<Botan::RandomNumberGenerator> Test::new_rng(std::string_view test_name) {
268✔
875
   return std::make_unique<Testsuite_RNG>(m_test_rng_seed, test_name);
268✔
876
}
877

878
//static
879
std::shared_ptr<Botan::RandomNumberGenerator> Test::new_shared_rng(std::string_view test_name) {
8✔
880
   return std::make_shared<Testsuite_RNG>(m_test_rng_seed, test_name);
8✔
881
}
882

883
//static
884
std::string Test::data_file(const std::string& file) {
773✔
885
   return options().data_dir() + "/" + file;
1,546✔
886
}
887

888
//static
889
std::string Test::data_dir(const std::string& subdir) {
1✔
890
   return options().data_dir() + "/" + subdir;
2✔
891
}
892

893
//static
894
std::vector<std::string> Test::files_in_data_dir(const std::string& subdir) {
393✔
895
   auto fs = Botan::get_files_recursive(options().data_dir() + "/" + subdir);
1,179✔
896
   if(fs.empty()) {
393✔
897
      throw Test_Error("Test::files_in_data_dir encountered empty subdir " + subdir);
×
898
   }
899
   return fs;
393✔
900
}
×
901

902
//static
903
std::string Test::data_file_as_temporary_copy(const std::string& what) {
1✔
904
   auto tmp_basename = what;
1✔
905
   std::replace(tmp_basename.begin(), tmp_basename.end(), '/', '_');
1✔
906
   auto temp_file = temp_file_name("tmp-" + tmp_basename);
1✔
907
   if(temp_file.empty()) {
1✔
908
      return "";
×
909
   }
910
   if(!Test::copy_file(data_file(what), temp_file)) {
1✔
911
      return "";
×
912
   }
913
   return temp_file;
1✔
914
}
1✔
915

916
//static
917
std::vector<std::string> Test::provider_filter(const std::vector<std::string>& providers) {
49,022✔
918
   if(m_opts.provider().empty()) {
49,022✔
919
      return providers;
49,022✔
920
   }
921
   for(auto&& provider : providers) {
×
922
      if(provider == m_opts.provider()) {
×
923
         return std::vector<std::string>{provider};
×
924
      }
925
   }
926
   return std::vector<std::string>{};
×
927
}
×
928

929
std::string Test::random_password(Botan::RandomNumberGenerator& rng) {
222✔
930
   const size_t len = 1 + rng.next_byte() % 32;
222✔
931
   return Botan::hex_encode(rng.random_vec(len));
444✔
932
}
933

934
size_t Test::random_index(Botan::RandomNumberGenerator& rng, size_t max) {
8,062✔
935
   return Botan::load_be(rng.random_array<8>()) % max;
8,062✔
936
}
937

938
void VarMap::clear() {
34,281✔
939
   m_vars.clear();
×
940
}
×
941

942
namespace {
943

944
bool varmap_pair_lt(const std::pair<std::string, std::string>& kv, const std::string& k) {
1,713,618✔
945
   return kv.first < k;
1,713,618✔
946
}
947

948
}  // namespace
949

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

953
   if(i != m_vars.end() && i->first == key) {
156,235✔
954
      i->second = value;
44,405✔
955
   } else {
956
      m_vars.emplace(i, key, value);
111,830✔
957
   }
958
}
156,235✔
959

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

963
   if(i != m_vars.end() && i->first == key) {
568,446✔
964
      return i->second;
498,591✔
965
   } else {
966
      return {};
69,855✔
967
   }
968
}
969

970
bool VarMap::has_key(const std::string& key) const {
213,574✔
971
   return get_var(key).has_value();
213,574✔
972
}
973

974
std::string VarMap::get_req_str(const std::string& key) const {
259,629✔
975
   auto var = get_var(key);
259,629✔
976
   if(var) {
259,629✔
977
      return *var;
519,258✔
978
   } else {
979
      throw Test_Error("Test missing variable " + key);
×
980
   }
981
}
259,629✔
982

983
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(const std::string& key) const {
12✔
984
   const auto var = get_req_str(key);
12✔
985

986
   std::vector<std::vector<uint8_t>> bin_list;
12✔
987

988
   for(auto&& part : Botan::split_on(var, ',')) {
62✔
989
      try {
50✔
990
         bin_list.push_back(Botan::hex_decode(part));
100✔
991
      } catch(std::exception& e) {
×
992
         std::ostringstream oss;
×
993
         oss << "Bad input '" << part << "'"
×
994
             << " in binary list key " << key << " - " << e.what();
×
995
         throw Test_Error(oss.str());
×
996
      }
×
997
   }
12✔
998

999
   return bin_list;
12✔
1000
}
12✔
1001

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

1005
   try {
163,711✔
1006
      if(var.starts_with("0x")) {
163,711✔
1007
         if(var.size() % 2 == 0) {
×
1008
            return Botan::hex_decode(var.substr(2));
×
1009
         } else {
1010
            std::string z = var;
×
1011
            std::swap(z[0], z[1]);  // swap 0x to x0 then remove x
×
1012
            return Botan::hex_decode(z.substr(1));
×
1013
         }
×
1014
      } else {
1015
         return Botan::hex_decode(var);
163,711✔
1016
      }
1017
   } catch(std::exception& e) {
×
1018
      std::ostringstream oss;
×
1019
      oss << "Bad input '" << var << "'"
×
1020
          << " for key " << key << " - " << e.what();
×
1021
      throw Test_Error(oss.str());
×
1022
   }
×
1023
}
163,711✔
1024

1025
std::string VarMap::get_opt_str(const std::string& key, const std::string& def_value) const {
14,378✔
1026
   if(auto v = get_var(key)) {
14,378✔
1027
      return *v;
57✔
1028
   } else {
1029
      return def_value;
28,699✔
1030
   }
14,378✔
1031
}
1032

1033
bool VarMap::get_req_bool(const std::string& key) const {
39✔
1034
   const auto var = get_req_str(key);
39✔
1035

1036
   if(var == "true") {
39✔
1037
      return true;
1038
   } else if(var == "false") {
23✔
1039
      return false;
1040
   } else {
1041
      throw Test_Error("Invalid boolean for key '" + key + "' value '" + var + "'");
×
1042
   }
1043
}
39✔
1044

1045
size_t VarMap::get_req_sz(const std::string& key) const {
4,547✔
1046
   return Botan::to_u32bit(get_req_str(key));
4,547✔
1047
}
1048

1049
uint8_t VarMap::get_req_u8(const std::string& key) const {
17✔
1050
   const size_t s = this->get_req_sz(key);
17✔
1051
   if(s > 256) {
17✔
1052
      throw Test_Error("Invalid " + key + " expected uint8_t got " + std::to_string(s));
×
1053
   }
1054
   return static_cast<uint8_t>(s);
17✔
1055
}
1056

1057
uint32_t VarMap::get_req_u32(const std::string& key) const {
14✔
1058
   return static_cast<uint32_t>(get_req_sz(key));
14✔
1059
}
1060

1061
uint64_t VarMap::get_req_u64(const std::string& key) const {
17✔
1062
   const auto var = get_req_str(key);
17✔
1063
   try {
17✔
1064
      return std::stoull(var);
17✔
1065
   } catch(std::exception&) {
×
1066
      throw Test_Error("Invalid u64 value '" + var + "'");
×
1067
   }
×
1068
}
17✔
1069

1070
size_t VarMap::get_opt_sz(const std::string& key, const size_t def_value) const {
31,379✔
1071
   if(auto v = get_var(key)) {
31,379✔
1072
      return Botan::to_u32bit(*v);
12,244✔
1073
   } else {
1074
      return def_value;
1075
   }
31,379✔
1076
}
1077

1078
uint64_t VarMap::get_opt_u64(const std::string& key, const uint64_t def_value) const {
3,538✔
1079
   if(auto v = get_var(key)) {
3,538✔
1080
      try {
641✔
1081
         return std::stoull(*v);
3,538✔
1082
      } catch(std::exception&) {
×
1083
         throw Test_Error("Invalid u64 value '" + *v + "'");
×
1084
      }
×
1085
   } else {
1086
      return def_value;
1087
   }
3,538✔
1088
}
1089

1090
std::vector<uint8_t> VarMap::get_opt_bin(const std::string& key) const {
45,868✔
1091
   if(auto v = get_var(key)) {
45,868✔
1092
      try {
16,134✔
1093
         return Botan::hex_decode(*v);
16,134✔
1094
      } catch(std::exception&) {
×
1095
         throw Test_Error("Test invalid hex input '" + *v + "'" + +" for key " + key);
×
1096
      }
×
1097
   } else {
1098
      return {};
29,734✔
1099
   };
45,868✔
1100
}
1101

1102
#if defined(BOTAN_HAS_BIGINT)
1103
Botan::BigInt VarMap::get_req_bn(const std::string& key) const {
38,502✔
1104
   const auto var = get_req_str(key);
38,502✔
1105

1106
   try {
38,502✔
1107
      return Botan::BigInt(var);
38,502✔
1108
   } catch(std::exception&) {
×
1109
      throw Test_Error("Test invalid bigint input '" + var + "' for key " + key);
×
1110
   }
×
1111
}
38,502✔
1112

1113
Botan::BigInt VarMap::get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const {
80✔
1114
   if(auto v = get_var(key)) {
80✔
1115
      try {
56✔
1116
         return Botan::BigInt(*v);
56✔
1117
      } catch(std::exception&) {
×
1118
         throw Test_Error("Test invalid bigint input '" + *v + "' for key " + key);
×
1119
      }
×
1120
   } else {
1121
      return def_value;
24✔
1122
   }
80✔
1123
}
1124
#endif
1125

1126
class Text_Based_Test::Text_Based_Test_Data {
1127
   public:
1128
      Text_Based_Test_Data(const std::string& data_src,
181✔
1129
                           const std::string& required_keys_str,
1130
                           const std::string& optional_keys_str) :
181✔
1131
            m_data_src(data_src) {
362✔
1132
         if(required_keys_str.empty()) {
181✔
1133
            throw Test_Error("Invalid test spec");
×
1134
         }
1135

1136
         m_required_keys = Botan::split_on(required_keys_str, ',');
181✔
1137
         std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
181✔
1138

1139
         m_all_keys.insert(m_required_keys.begin(), m_required_keys.end());
181✔
1140
         m_all_keys.insert(optional_keys.begin(), optional_keys.end());
181✔
1141
         m_output_key = m_required_keys.at(m_required_keys.size() - 1);
181✔
1142
      }
181✔
1143

1144
      std::string get_next_line();
1145

1146
      const std::string& current_source_name() const { return m_cur_src_name; }
×
1147

1148
      bool known_key(const std::string& key) const;
1149

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

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

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

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

1158
      const std::string& initial_data_src_name() const { return m_data_src; }
181✔
1159

1160
   private:
1161
      std::string m_data_src;
1162
      std::vector<std::string> m_required_keys;
1163
      std::unordered_set<std::string> m_all_keys;
1164
      std::string m_output_key;
1165

1166
      bool m_first = true;
1167
      std::unique_ptr<std::istream> m_cur;
1168
      std::string m_cur_src_name;
1169
      std::deque<std::string> m_srcs;
1170
      std::vector<std::string> m_cpu_flags;
1171
};
1172

1173
Text_Based_Test::Text_Based_Test(const std::string& data_src,
181✔
1174
                                 const std::string& required_keys,
1175
                                 const std::string& optional_keys) :
181✔
1176
      m_data(std::make_unique<Text_Based_Test_Data>(data_src, required_keys, optional_keys)) {}
181✔
1177

1178
Text_Based_Test::~Text_Based_Test() = default;
181✔
1179

1180
std::string Text_Based_Test::Text_Based_Test_Data::get_next_line() {
157,242✔
1181
   while(true) {
157,500✔
1182
      if(m_cur == nullptr || m_cur->good() == false) {
157,500✔
1183
         if(m_srcs.empty()) {
450✔
1184
            if(m_first) {
362✔
1185
               if(m_data_src.ends_with(".vec")) {
181✔
1186
                  m_srcs.push_back(Test::data_file(m_data_src));
338✔
1187
               } else {
1188
                  const auto fs = Test::files_in_data_dir(m_data_src);
12✔
1189
                  m_srcs.assign(fs.begin(), fs.end());
12✔
1190
                  if(m_srcs.empty()) {
12✔
1191
                     throw Test_Error("Error reading test data dir " + m_data_src);
×
1192
                  }
1193
               }
12✔
1194

1195
               m_first = false;
181✔
1196
            } else {
1197
               return "";  // done
181✔
1198
            }
1199
         }
1200

1201
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
357✔
1202
         m_cur_src_name = m_srcs[0];
269✔
1203

1204
#if defined(BOTAN_HAS_CPUID)
1205
         // Reinit cpuid on new file if needed
1206
         if(m_cpu_flags.empty() == false) {
269✔
1207
            m_cpu_flags.clear();
19✔
1208
            Botan::CPUID::initialize();
19✔
1209
         }
1210
#endif
1211

1212
         if(!m_cur->good()) {
269✔
1213
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
1214
         }
1215

1216
         m_srcs.pop_front();
269✔
1217
      }
1218

1219
      while(m_cur->good()) {
227,897✔
1220
         std::string line;
227,639✔
1221
         std::getline(*m_cur, line);
227,639✔
1222

1223
         if(line.empty()) {
227,639✔
1224
            continue;
55,310✔
1225
         }
1226

1227
         if(line[0] == '#') {
172,329✔
1228
            if(line.starts_with("#test ")) {
15,289✔
1229
               return line;
21✔
1230
            } else {
1231
               continue;
15,268✔
1232
            }
1233
         }
1234

1235
         return line;
157,040✔
1236
      }
227,639✔
1237
   }
1238
}
1239

1240
bool Text_Based_Test::Text_Based_Test_Data::known_key(const std::string& key) const {
156,235✔
1241
   return m_all_keys.contains(key);
156,235✔
1242
}
1243

1244
namespace {
1245

1246
// strips leading and trailing but not internal whitespace
1247
std::string strip_ws(const std::string& in) {
312,470✔
1248
   const char* whitespace = " ";
312,470✔
1249

1250
   const auto first_c = in.find_first_not_of(whitespace);
312,470✔
1251
   if(first_c == std::string::npos) {
312,470✔
1252
      return "";
1,033✔
1253
   }
1254

1255
   const auto last_c = in.find_last_not_of(whitespace);
311,437✔
1256

1257
   return in.substr(first_c, last_c - first_c + 1);
311,437✔
1258
}
1259

1260
std::vector<std::string> parse_cpuid_bits(const std::vector<std::string>& tok) {
21✔
1261
   std::vector<std::string> bits;
21✔
1262

1263
#if defined(BOTAN_HAS_CPUID)
1264
   for(size_t i = 1; i < tok.size(); ++i) {
106✔
1265
      if(auto bit = Botan::CPUID::bit_from_string(tok[i])) {
85✔
1266
         bits.push_back(bit->to_string());
98✔
1267
      }
1268
   }
1269
#else
1270
   BOTAN_UNUSED(tok);
1271
#endif
1272

1273
   return bits;
21✔
1274
}
×
1275

1276
}  // namespace
1277

1278
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) {
32,609✔
1279
   return false;
32,609✔
1280
}
1281

1282
std::vector<Test::Result> Text_Based_Test::run() {
181✔
1283
   std::vector<Test::Result> results;
181✔
1284

1285
   std::string header;
181✔
1286
   std::string header_or_name = m_data->initial_data_src_name();
181✔
1287
   VarMap vars;
181✔
1288
   size_t test_cnt = 0;
181✔
1289

1290
   while(true) {
157,242✔
1291
      const std::string line = m_data->get_next_line();
157,242✔
1292
      if(line.empty()) {
157,242✔
1293
         // EOF
1294
         break;
1295
      }
1296

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

1300
         if(pragma_tokens.empty()) {
21✔
1301
            throw Test_Error("Empty pragma found in " + m_data->current_source_name());
×
1302
         }
1303

1304
         if(pragma_tokens[0] != "cpuid") {
21✔
1305
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1306
         }
1307

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

1312
         m_data->set_cpu_flags(parse_cpuid_bits(pragma_tokens));
42✔
1313

1314
         continue;
21✔
1315
      } else if(line[0] == '#') {
157,061✔
1316
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1317
      }
1318

1319
      if(line[0] == '[' && line[line.size() - 1] == ']') {
157,040✔
1320
         header = line.substr(1, line.size() - 2);
805✔
1321
         header_or_name = header;
805✔
1322
         test_cnt = 0;
805✔
1323
         vars.clear();
805✔
1324
         continue;
805✔
1325
      }
1326

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

1329
      auto equal_i = line.find_first_of('=');
156,235✔
1330

1331
      if(equal_i == std::string::npos) {
156,235✔
1332
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1333
         continue;
×
1334
      }
1335

1336
      const std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
312,470✔
1337
      const std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
312,470✔
1338

1339
      if(!m_data->known_key(key)) {
156,235✔
1340
         auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key));
×
1341
         results.push_back(r);
×
1342
      }
×
1343

1344
      vars.add(key, val);
156,235✔
1345

1346
      if(key == m_data->output_key()) {
156,235✔
1347
         try {
48,388✔
1348
            for(const auto& req_key : m_data->required_keys()) {
245,554✔
1349
               if(!vars.has_key(req_key)) {
197,166✔
1350
                  auto r =
×
1351
                     Test::Result::Failure(header_or_name, Botan::fmt("{} missing required key {}", test_id, req_key));
×
1352
                  results.push_back(r);
×
1353
               }
×
1354
            }
1355

1356
            if(skip_this_test(header, vars)) {
48,388✔
1357
               continue;
139✔
1358
            }
1359

1360
            ++test_cnt;
48,249✔
1361

1362
            const uint64_t start = Test::timestamp();
48,249✔
1363

1364
            Test::Result result = run_one_test(header, vars);
48,249✔
1365
#if defined(BOTAN_HAS_CPUID)
1366
            if(!m_data->cpu_flags().empty()) {
48,249✔
1367
               for(const auto& cpuid_str : m_data->cpu_flags()) {
30,621✔
1368
                  if(const auto bit = Botan::CPUID::Feature::from_string(cpuid_str)) {
21,677✔
1369
                     if(Botan::CPUID::has(*bit)) {
21,677✔
1370
                        Botan::CPUID::clear_cpuid_bit(*bit);
16,577✔
1371
                        // now re-run the test
1372
                        result.merge(run_one_test(header, vars));
16,577✔
1373
                     }
1374
                  }
1375
               }
1376
               Botan::CPUID::initialize();
8,944✔
1377
            }
1378
#endif
1379
            result.set_ns_consumed(Test::timestamp() - start);
48,249✔
1380

1381
            if(result.tests_failed() > 0) {
48,249✔
1382
               std::ostringstream oss;
×
1383
               oss << "Test # " << test_cnt << " ";
×
1384
               if(!header.empty()) {
×
1385
                  oss << header << " ";
×
1386
               }
1387
               oss << "failed ";
×
1388

1389
               for(const auto& k : m_data->required_keys()) {
×
1390
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1391
               }
1392

1393
               result.test_note(oss.str());
×
1394
            }
×
1395
            results.push_back(result);
48,249✔
1396
         } catch(std::exception& e) {
48,249✔
1397
            std::ostringstream oss;
×
1398
            oss << "Test # " << test_cnt << " ";
×
1399
            if(!header.empty()) {
×
1400
               oss << header << " ";
×
1401
            }
1402

1403
            for(const auto& k : m_data->required_keys()) {
×
1404
               oss << k << "=" << vars.get_req_str(k) << " ";
×
1405
            }
1406

1407
            oss << "failed with exception '" << e.what() << "'";
×
1408

1409
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1410
         }
×
1411

1412
         if(clear_between_callbacks()) {
48,249✔
1413
            vars.clear();
189,572✔
1414
         }
1415
      }
1416
   }
157,339✔
1417

1418
   if(results.empty()) {
181✔
1419
      return results;
1420
   }
1421

1422
   try {
181✔
1423
      std::vector<Test::Result> final_tests = run_final_tests();
181✔
1424
      results.insert(results.end(), final_tests.begin(), final_tests.end());
181✔
1425
   } catch(std::exception& e) {
181✔
1426
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1427
   }
×
1428

1429
   return results;
1430
}
181✔
1431

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