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

randombit / botan / 27930394332

22 Jun 2026 02:29AM UTC coverage: 89.361% (-2.3%) from 91.664%
27930394332

push

github

randombit
Escape control chars in X509_Certificate::to_string

111792 of 125101 relevant lines covered (89.36%)

10818223.53 hits per line

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

80.34
/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;
459✔
59

60
Test::~Test() = default;
607✔
61

62
Test::Result::Result(std::string_view who) : m_who(who), m_timestamp(Test::timestamp()) {}
83,675✔
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) {
128,735✔
71
   if(who() != other.who()) {
128,735✔
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;
128,662✔
81
   }
82

83
   m_timestamp = std::min(m_timestamp, other.m_timestamp);
128,735✔
84
   m_ns_taken += other.m_ns_taken;
128,735✔
85
   m_tests_passed += other.m_tests_passed;
128,735✔
86
   m_fail_log.insert(m_fail_log.end(), other.m_fail_log.begin(), other.m_fail_log.end());
128,735✔
87
   m_log.insert(m_log.end(), other.m_log.begin(), other.m_log.end());
128,735✔
88
}
128,735✔
89

90
void Test::Result::start_timer() {
1,037✔
91
   if(m_started == 0) {
1,037✔
92
      m_started = Test::timestamp();
2,074✔
93
   }
94
}
1,037✔
95

96
void Test::Result::end_timer() {
1,064✔
97
   if(m_started > 0) {
1,064✔
98
      m_ns_taken += Test::timestamp() - m_started;
2,072✔
99
      m_started = 0;
1,036✔
100
   }
101
}
1,064✔
102

103
void Test::Result::test_note(std::string_view note, std::span<const uint8_t> context) {
12✔
104
   return test_note(note, Botan::hex_encode(context));
24✔
105
}
106

107
void Test::Result::test_note(std::string_view note, std::string_view context) {
2,147✔
108
   m_log.emplace_back(Botan::fmt("{} {}: {}", who(), note, context));
2,147✔
109
}
2,147✔
110

111
void Test::Result::test_note(std::string_view note) {
644✔
112
   m_log.emplace_back(Botan::fmt("{} {}", who(), note));
644✔
113
}
644✔
114

115
void Test::Result::note_missing(std::string_view whatever_sv) {
290✔
116
   static std::set<std::string> s_already_seen;
290✔
117

118
   const std::string whatever(whatever_sv);
290✔
119
   if(!s_already_seen.contains(whatever)) {
290✔
120
      test_note(Botan::fmt("Skipping tests due to missing {}", whatever));
11✔
121
      s_already_seen.insert(whatever);
290✔
122
   }
123
}
290✔
124

125
void Test::Result::require(std::string_view what, bool expr) {
323✔
126
   if(!test_is_true(what, expr)) {
323✔
127
      throw Test_Aborted(Botan::fmt("Test aborted, because required condition was not met: {}", what));
×
128
   }
129
}
323✔
130

131
Test::Result::ThrowExpectations::~ThrowExpectations() {
119,446✔
132
   BOTAN_ASSERT_NOMSG(m_consumed);
119,446✔
133
}
232,482✔
134

135
void Test::Result::ThrowExpectations::assert_that_success_is_not_expected() const {
113,036✔
136
   BOTAN_ASSERT_NOMSG(!m_expect_success);
112,817✔
137
}
112,817✔
138

139
Test::Result::ThrowExpectations& Test::Result::ThrowExpectations::expect_success() {
1,654✔
140
   BOTAN_ASSERT_NOMSG(!m_expected_message && !m_expected_exception_check_fn);
1,654✔
141
   m_expect_success = true;
1,654✔
142
   return *this;
1,654✔
143
}
144

145
Test::Result::ThrowExpectations& Test::Result::ThrowExpectations::expect_message(std::string_view message) {
219✔
146
   assert_that_success_is_not_expected();
219✔
147
   m_expected_message = message;
219✔
148
   return *this;
219✔
149
}
150

151
bool Test::Result::ThrowExpectations::check(std::string_view test_name, Test::Result& result) {
119,446✔
152
   m_consumed = true;
119,446✔
153

154
   try {
119,446✔
155
      m_fn();
119,446✔
156
      if(!m_expect_success) {
1,655✔
157
         return result.test_failure(Botan::fmt("{} failed to throw expected exception", test_name));
2✔
158
      }
159
   } catch(const std::exception& ex) {
117,791✔
160
      if(m_expect_success) {
117,789✔
161
         return result.test_failure(Botan::fmt("{} threw unexpected exception: {}", test_name, ex.what()));
1✔
162
      }
163
      if(m_expected_exception_check_fn && !m_expected_exception_check_fn(std::current_exception())) {
343,422✔
164
         return result.test_failure(Botan::fmt("{} threw unexpected exception: {}", test_name, ex.what()));
2✔
165
      }
166
      if(m_expected_message.has_value()) {
117,786✔
167
         const std::string ex_msg = std::string(ex.what());
216✔
168

169
         // TODO(C++23) std::string::contains
170
         if(ex_msg.find(m_expected_message.value()) == std::string::npos) {
216✔
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_msg));
175
         }
176
      }
216✔
177
   } catch(...) {
117,791✔
178
      if(m_expect_success || m_expected_exception_check_fn || m_expected_message.has_value()) {
2✔
179
         return result.test_failure(Botan::fmt("{} threw unexpected unknown exception", test_name));
1✔
180
      }
181
   }
2✔
182

183
   return result.test_success();
119,439✔
184
}
185

186
bool Test::Result::test_throws(std::string_view what, std::function<void()> fn) {
4,771✔
187
   return ThrowExpectations(std::move(fn)).check(what, *this);
14,313✔
188
}
189

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

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

198
bool Test::Result::test_success(std::string_view note) {
3,918,907✔
199
   if(Test::options().log_success()) {
3,918,891✔
200
      test_note(note);
×
201
   }
202
   ++m_tests_passed;
3,918,907✔
203
   return true;
119,439✔
204
}
205

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

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

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

218
bool Test::Result::test_failure(const char* err) {
×
219
   return test_failure(std::string_view(err));
×
220
}
221

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

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

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

235
namespace {
236

237
bool same_contents(std::span<const uint8_t> x, std::span<const uint8_t> y) {
349,851✔
238
   if(x.size() != y.size()) {
1,445✔
239
      return false;
240
   }
241
   if(x.empty()) {
349,850✔
242
      return true;
243
   }
244

245
   return std::memcmp(x.data(), y.data(), x.size()) == 0;
348,056✔
246
}
247

248
}  // namespace
249

250
bool Test::Result::test_bin_ne(std::string_view what,
3,358✔
251
                               std::span<const uint8_t> produced,
252
                               std::span<const uint8_t> expected) {
253
   if(produced.size() == expected.size() && same_contents(produced, expected)) {
4,803✔
254
      return test_failure(Botan::fmt("{} {} produced matching bytes", who(), what));
1✔
255
   }
256
   return test_success();
3,357✔
257
}
258

259
bool Test::Result::test_bin_eq(std::string_view what,
617✔
260
                               std::span<const uint8_t> produced,
261
                               std::string_view expected_hex) {
262
   const std::vector<uint8_t> expected = Botan::hex_decode(expected_hex);
617✔
263
   return test_bin_eq(what, produced, expected);
617✔
264
}
617✔
265

266
bool Test::Result::test_bin_eq(std::string_view what,
348,406✔
267
                               std::span<const uint8_t> produced,
268
                               std::span<const uint8_t> expected) {
269
   if(same_contents(produced, expected)) {
695,017✔
270
      return test_success();
348,405✔
271
   }
272

273
   std::ostringstream err;
1✔
274

275
   err << who();
1✔
276

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

279
   if(produced.size() != expected.size()) {
1✔
280
      err << " produced " << produced.size() << " bytes expected " << expected.size();
1✔
281
   }
282

283
   std::vector<uint8_t> xor_diff(std::min(produced.size(), expected.size()));
2✔
284
   size_t bytes_different = 0;
1✔
285

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

293
   err << "\nProduced: " << Botan::hex_encode(produced) << "\nExpected: " << Botan::hex_encode(expected);
1✔
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) {
39,448✔
303
   if(produced.empty()) {
39,448✔
304
      return test_failure(what, "was empty");
1✔
305
   } else {
306
      return test_success();
39,447✔
307
   }
308
}
309

310
bool Test::Result::test_str_eq(std::string_view what, std::string_view produced, std::string_view expected) {
78,479✔
311
   if(produced == expected) {
78,479✔
312
      return test_success();
78,479✔
313
   } else {
314
      return test_failure(Botan::fmt("Assertion failure in {} {}: '{}' == '{}'", who(), what, produced, expected));
×
315
   }
316
}
317

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

326
bool Test::Result::test_i16_eq(std::string_view what, int16_t produced, int16_t expected) {
1,025✔
327
   return test_i32_eq(what, produced, expected);
1,025✔
328
}
329

330
bool Test::Result::test_i32_eq(std::string_view what, int32_t produced, int32_t expected) {
1,026✔
331
   if(produced == expected) {
1,026✔
332
      return test_success();
1,026✔
333
   } else {
334
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} == {}", who(), what, produced, expected));
×
335
   }
336
}
337

338
bool Test::Result::test_u8_eq(uint8_t produced, uint8_t expected) {
214✔
339
   return test_sz_eq("comparison", produced, expected);
214✔
340
}
341

342
bool Test::Result::test_u8_eq(std::string_view what, uint8_t produced, uint8_t expected) {
163,038✔
343
   return test_sz_eq(what, produced, expected);
163,038✔
344
}
345

346
bool Test::Result::test_u16_eq(uint16_t produced, uint16_t expected) {
40✔
347
   return test_sz_eq("comparison", produced, expected);
40✔
348
}
349

350
bool Test::Result::test_u16_eq(std::string_view what, uint16_t produced, uint16_t expected) {
66,790✔
351
   return test_sz_eq(what, produced, expected);
66,790✔
352
}
353

354
bool Test::Result::test_u32_eq(uint32_t produced, uint32_t expected) {
16✔
355
   return test_sz_eq("comparison", produced, expected);
16✔
356
}
357

358
bool Test::Result::test_u32_eq(std::string_view what, uint32_t produced, uint32_t expected) {
4,221✔
359
   return test_sz_eq(what, produced, expected);
4,221✔
360
}
361

362
bool Test::Result::test_u64_eq(uint64_t produced, uint64_t expected) {
13✔
363
   return test_u64_eq("comparison", produced, expected);
13✔
364
}
365

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

374
bool Test::Result::test_u64_lt(std::string_view what, uint64_t produced, uint64_t expected) {
2✔
375
   if(produced < expected) {
2✔
376
      return test_success();
2✔
377
   } else {
378
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} < {}", who(), what, produced, expected));
×
379
   }
380
}
381

382
bool Test::Result::test_sz_eq(std::string_view what, size_t produced, size_t expected) {
311,566✔
383
   if(produced == expected) {
311,566✔
384
      return test_success();
311,565✔
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_ne(std::string_view what, size_t produced, size_t expected) {
119✔
391
   if(produced != expected) {
119✔
392
      return test_success();
118✔
393
   } else {
394
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} != {}", who(), what, produced, expected));
1✔
395
   }
396
}
397

398
bool Test::Result::test_sz_lt(std::string_view what, size_t produced, size_t expected) {
5,639✔
399
   if(produced < expected) {
5,639✔
400
      return test_success();
5,638✔
401
   } else {
402
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} < {}", who(), what, produced, expected));
1✔
403
   }
404
}
405

406
bool Test::Result::test_sz_lte(std::string_view what, size_t produced, size_t expected) {
1,021,636✔
407
   if(produced <= expected) {
1,021,636✔
408
      return test_success();
1,021,635✔
409
   } else {
410
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} <= {}", who(), what, produced, expected));
1✔
411
   }
412
}
413

414
bool Test::Result::test_sz_gt(std::string_view what, size_t produced, size_t expected) {
30,149✔
415
   if(produced > expected) {
30,149✔
416
      return test_success();
30,149✔
417
   } else {
418
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} > {}", who(), what, produced, expected));
×
419
   }
420
}
421

422
bool Test::Result::test_sz_gte(std::string_view what, size_t produced, size_t expected) {
1,141,359✔
423
   if(produced >= expected) {
1,141,359✔
424
      return test_success();
1,141,358✔
425
   } else {
426
      return test_failure(Botan::fmt("Assertion failure in {} {}: {} >= {}", who(), what, produced, expected));
1✔
427
   }
428
}
429

430
bool Test::Result::test_opt_u8_eq(std::string_view what,
1,215✔
431
                                  std::optional<uint8_t> produced,
432
                                  std::optional<uint8_t> expected) {
433
   if(produced.has_value() and !expected.has_value()) {
1,215✔
434
      return test_failure(Botan::fmt("Assertion {} produced value {} but nullopt was expected", what, *produced));
×
435
   } else if(!produced.has_value() && expected.has_value()) {
1,215✔
436
      return test_failure(Botan::fmt("Assertion {} produced nullopt but {} was expected", what, *expected));
×
437
   } else if(produced.has_value() && expected.has_value()) {
1,215✔
438
      return test_u8_eq(what, *produced, *expected);
10✔
439
   } else {
440
      return test_success();
1,205✔
441
   }
442
}
443

444
bool Test::Result::test_opt_u16_eq(std::string_view what,
15✔
445
                                   std::optional<uint16_t> produced,
446
                                   std::optional<uint16_t> expected) {
447
   if(produced.has_value() and !expected.has_value()) {
15✔
448
      return test_failure(Botan::fmt("Assertion {} produced value {} but nullopt was expected", what, *produced));
×
449
   } else if(!produced.has_value() && expected.has_value()) {
15✔
450
      return test_failure(Botan::fmt("Assertion {} produced nullopt but {} was expected", what, *expected));
×
451
   } else if(produced.has_value() && expected.has_value()) {
15✔
452
      return test_u16_eq(what, *produced, *expected);
7✔
453
   } else {
454
      return test_success();
8✔
455
   }
456
}
457

458
bool Test::Result::test_opt_u32_eq(std::string_view what,
×
459
                                   std::optional<uint32_t> produced,
460
                                   std::optional<uint32_t> expected) {
461
   if(produced.has_value() and !expected.has_value()) {
×
462
      return test_failure(Botan::fmt("Assertion {} produced value {} but nullopt was expected", what, *produced));
×
463
   } else if(!produced.has_value() && expected.has_value()) {
×
464
      return test_failure(Botan::fmt("Assertion {} produced nullopt but {} was expected", what, *expected));
×
465
   } else if(produced.has_value() && expected.has_value()) {
×
466
      return test_u32_eq(what, *produced, *expected);
×
467
   } else {
468
      return test_success();
×
469
   }
470
}
471

472
bool Test::Result::test_opt_u64_eq(std::string_view what,
23✔
473
                                   std::optional<uint64_t> produced,
474
                                   std::optional<uint64_t> expected) {
475
   if(produced.has_value() and !expected.has_value()) {
23✔
476
      return test_failure(Botan::fmt("Assertion {} produced value {} but nullopt was expected", what, *produced));
×
477
   } else if(!produced.has_value() && expected.has_value()) {
23✔
478
      return test_failure(Botan::fmt("Assertion {} produced nullopt but {} was expected", what, *expected));
×
479
   } else if(produced.has_value() && expected.has_value()) {
23✔
480
      return test_u64_eq(what, *produced, *expected);
23✔
481
   } else {
482
      return test_success();
×
483
   }
484
}
485

486
bool Test::Result::test_opt_str_eq(std::string_view what,
13✔
487
                                   std::optional<std::string> produced,
488
                                   std::optional<std::string> expected) {
489
   if(produced.has_value() and !expected.has_value()) {
13✔
490
      return test_failure(Botan::fmt("Assertion {} produced value {} but nullopt was expected", what, *produced));
×
491
   } else if(!produced.has_value() && expected.has_value()) {
13✔
492
      return test_failure(Botan::fmt("Assertion {} produced nullopt but {} was expected", what, *expected));
×
493
   } else if(produced.has_value() && expected.has_value()) {
13✔
494
      return test_str_eq(what, *produced, *expected);
13✔
495
   } else {
496
      return test_success();
×
497
   }
498
}
499

500
#if defined(BOTAN_HAS_BIGINT)
501
bool Test::Result::test_bn_eq(std::string_view what, const BigInt& produced, const BigInt& expected) {
252,706✔
502
   if(produced == expected) {
252,706✔
503
      return test_success();
252,705✔
504
   } else {
505
      std::ostringstream err;
1✔
506
      err << who() << " " << what << " produced " << produced << " != expected value " << expected;
1✔
507
      return test_failure(err.str());
1✔
508
   }
1✔
509
}
510

511
bool Test::Result::test_bn_ne(std::string_view what, const BigInt& produced, const BigInt& expected) {
97✔
512
   if(produced != expected) {
97✔
513
      return test_success();
96✔
514
   } else {
515
      std::ostringstream err;
1✔
516
      err << who() << " " << what << " produced " << produced << " prohibited value";
1✔
517
      return test_failure(err.str());
1✔
518
   }
1✔
519
}
520
#endif
521

522
bool Test::Result::test_bool_eq(std::string_view what, bool produced, bool expected) {
446,405✔
523
   if(produced == expected) {
446,405✔
524
      return test_success();
446,405✔
525
   } else {
526
      if(expected == true) {
×
527
         return test_failure(Botan::fmt("Assertion failure in {}, {} was unexpectedly false", who(), what));
×
528
      } else {
529
         return test_failure(Botan::fmt("Assertion failure in {}, {} was unexpectedly true", who(), what));
×
530
      }
531
   }
532
}
533

534
bool Test::Result::test_is_true(std::string_view what, bool produced) {
301,706✔
535
   return test_bool_eq(what, produced, true);
301,706✔
536
}
537

538
bool Test::Result::test_is_false(std::string_view what, bool produced) {
136,983✔
539
   return test_bool_eq(what, produced, false);
136,983✔
540
}
541

542
bool Test::Result::test_rc_ok(std::string_view func, int rc) {
2,912✔
543
   if(rc != 0) {
2,912✔
544
      std::ostringstream err;
1✔
545
      err << m_who << " " << func << " unexpectedly failed with error code " << rc;
1✔
546
      return test_failure(err.str());
1✔
547
   }
1✔
548

549
   return test_success();
2,911✔
550
}
551

552
bool Test::Result::test_rc_fail(std::string_view func, std::string_view why, int rc) {
26✔
553
   if(rc == 0) {
26✔
554
      std::ostringstream err;
1✔
555
      err << m_who << " call to " << func << " unexpectedly succeeded expecting failure because " << why;
1✔
556
      return test_failure(err.str());
1✔
557
   }
1✔
558

559
   return test_success();
25✔
560
}
561

562
bool Test::Result::test_rc_init(std::string_view func, int rc) {
121✔
563
   if(rc == 0) {
121✔
564
      return test_success();
121✔
565
   } else {
566
      std::ostringstream msg;
×
567
      msg << m_who;
×
568
      msg << " " << func;
×
569

570
      // -40 is BOTAN_FFI_ERROR_NOT_IMPLEMENTED
571
      if(rc == -40) {
×
572
         msg << " returned not implemented";
×
573
      } else {
574
         msg << " unexpectedly failed with error code " << rc;
×
575
      }
576

577
      if(rc == -40) {
×
578
         this->test_note(msg.str());
×
579
      } else {
580
         this->test_failure(msg.str());
×
581
      }
582
      return false;
×
583
   }
×
584
}
585

586
bool Test::Result::test_rc(std::string_view func, int rc, int expected) {
450✔
587
   if(expected != rc) {
450✔
588
      std::ostringstream err;
1✔
589
      err << m_who;
1✔
590
      err << " call to " << func << " unexpectedly returned " << rc;
1✔
591
      err << " but expecting " << expected;
1✔
592
      return test_failure(err.str());
1✔
593
   }
1✔
594

595
   return test_success();
449✔
596
}
597

598
void Test::initialize(std::string test_name, CodeLocation location) {
459✔
599
   m_test_name = std::move(test_name);
459✔
600
   m_registration_location = location;
459✔
601
}
459✔
602

603
Botan::RandomNumberGenerator& Test::rng() const {
465,171✔
604
   if(!m_test_rng) {
465,171✔
605
      m_test_rng = Test::new_rng(m_test_name);
148✔
606
   }
607

608
   return *m_test_rng;
465,171✔
609
}
610

611
std::optional<std::string> Test::supported_ec_group_name(std::vector<std::string> preferred_groups) {
151✔
612
#if defined(BOTAN_HAS_ECC_GROUP)
613
   if(preferred_groups.empty()) {
151✔
614
      preferred_groups = {
149✔
615
         "secp256r1",
616
         "brainpool256r1",
617
         "secp384r1",
618
         "brainpool384r1",
619
         "secp521r1",
620
         "brainpool512r1",
621
      };
1,192✔
622
   }
623

624
   for(const auto& group : preferred_groups) {
151✔
625
      if(Botan::EC_Group::supports_named_group(group)) {
151✔
626
         return group;
151✔
627
      }
628
   }
629
#else
630
   BOTAN_UNUSED(preferred_groups);
631
#endif
632

633
   return std::nullopt;
×
634
}
298✔
635

636
std::vector<uint8_t> Test::mutate_vec(const std::vector<uint8_t>& v,
97,316✔
637
                                      Botan::RandomNumberGenerator& rng,
638
                                      bool maybe_resize,
639
                                      size_t min_offset) {
640
   std::vector<uint8_t> r = v;
97,316✔
641

642
   if(maybe_resize && (r.empty() || rng.next_byte() < 32)) {
110,954✔
643
      // TODO: occasionally truncate, insert at random index
644
      const size_t add = 1 + (rng.next_byte() % 16);
2,159✔
645
      r.resize(r.size() + add);
2,159✔
646
      rng.randomize(&r[r.size() - add], add);
2,159✔
647
   }
648

649
   if(r.size() > min_offset) {
97,316✔
650
      const size_t offset = std::max<size_t>(min_offset, rng.next_byte() % r.size());
95,778✔
651
      const uint8_t perturb = rng.next_nonzero_byte();
95,778✔
652
      r[offset] ^= perturb;
95,778✔
653
   }
654

655
   return r;
97,316✔
656
}
×
657

658
std::vector<std::string> Test::possible_providers(const std::string& /*alg*/) {
×
659
   return Test::provider_filter({"base"});
×
660
}
661

662
//static
663
std::string Test::format_time(uint64_t nanoseconds) {
1,506✔
664
   std::ostringstream o;
1,506✔
665

666
   if(nanoseconds > 1000000000) {
1,506✔
667
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000000.0 << " sec";
162✔
668
   } else {
669
      o << std::setprecision(2) << std::fixed << nanoseconds / 1000000.0 << " msec";
1,344✔
670
   }
671

672
   return o.str();
3,012✔
673
}
1,506✔
674

675
// TODO: this should move to `StdoutReporter`
676
std::string Test::Result::result_string() const {
3,069✔
677
   const bool verbose = Test::options().verbose();
3,069✔
678

679
   if(tests_run() == 0 && !verbose) {
3,069✔
680
      return "";
26✔
681
   }
682

683
   std::ostringstream report;
3,043✔
684

685
   report << who() << " ran ";
3,043✔
686

687
   if(tests_run() == 0) {
3,043✔
688
      report << "ZERO";
×
689
   } else {
690
      report << tests_run();
3,043✔
691
   }
692
   report << " tests";
3,043✔
693

694
   if(m_ns_taken > 0) {
3,043✔
695
      report << " in " << format_time(m_ns_taken);
3,010✔
696
   }
697

698
   if(tests_failed() > 0) {
3,043✔
699
      report << " " << tests_failed() << " FAILED";
24✔
700
   } else {
701
      report << " all ok";
3,019✔
702
   }
703

704
   report << "\n";
3,043✔
705

706
   for(size_t i = 0; i != m_fail_log.size(); ++i) {
3,067✔
707
      report << "Failure " << (i + 1) << ": " << m_fail_log[i];
24✔
708
      if(m_where) {
24✔
709
         report << " (at " << m_where->path << ":" << m_where->line << ")";
×
710
      }
711
      report << "\n";
24✔
712
   }
713

714
   if(!m_fail_log.empty() || tests_run() == 0 || verbose) {
3,043✔
715
      for(size_t i = 0; i != m_log.size(); ++i) {
24✔
716
         report << "Note " << (i + 1) << ": " << m_log[i] << "\n";
×
717
      }
718
   }
719

720
   return report.str();
3,043✔
721
}
3,043✔
722

723
namespace {
724

725
class Test_Registry {
726
   public:
727
      static Test_Registry& instance() {
1,405✔
728
         static Test_Registry registry;
1,406✔
729
         return registry;
1,405✔
730
      }
731

732
      void register_test(const std::string& category,
459✔
733
                         const std::string& name,
734
                         bool smoke_test,
735
                         bool needs_serialization,
736
                         std::function<std::unique_ptr<Test>()> maker_fn) {
737
         if(m_tests.contains(name)) {
459✔
738
            throw Test_Error("Duplicate registration of test '" + name + "'");
×
739
         }
740

741
         if(m_tests.contains(category)) {
459✔
742
            throw Test_Error("'" + category + "' cannot be used as category, test exists");
×
743
         }
744

745
         if(m_categories.contains(name)) {
459✔
746
            throw Test_Error("'" + name + "' cannot be used as test name, category exists");
×
747
         }
748

749
         if(smoke_test) {
459✔
750
            m_smoke_tests.push_back(name);
10✔
751
         }
752

753
         if(needs_serialization) {
459✔
754
            m_mutexed_tests.push_back(name);
22✔
755
         }
756

757
         m_tests.emplace(name, std::move(maker_fn));
459✔
758
         m_categories.emplace(category, name);
459✔
759
      }
459✔
760

761
      std::unique_ptr<Test> get_test(const std::string& test_name) const {
459✔
762
         auto i = m_tests.find(test_name);
459✔
763
         if(i != m_tests.end()) {
459✔
764
            return i->second();
459✔
765
         }
766
         return nullptr;
×
767
      }
768

769
      std::vector<std::string> registered_tests() const {
×
770
         std::vector<std::string> s;
×
771
         s.reserve(m_tests.size());
×
772
         for(auto&& i : m_tests) {
×
773
            s.push_back(i.first);
×
774
         }
775
         return s;
×
776
      }
×
777

778
      std::vector<std::string> registered_test_categories() const {
×
779
         std::set<std::string> s;
×
780
         for(auto&& i : m_categories) {
×
781
            s.insert(i.first);
×
782
         }
783
         return std::vector<std::string>(s.begin(), s.end());
×
784
      }
×
785

786
      std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
1✔
787
                                                       const std::vector<std::string>& to_be_skipped) {
788
         std::vector<std::string> result;
1✔
789

790
         std::set<std::string> to_be_skipped_set(to_be_skipped.begin(), to_be_skipped.end());
1✔
791
         // TODO: this is O(n^2), but we have a relatively small number of tests.
792
         auto insert_if_not_exists_and_not_skipped = [&](const std::string& test_name) {
460✔
793
            if(!Botan::value_exists(result, test_name) && !to_be_skipped_set.contains(test_name)) {
918✔
794
               result.push_back(test_name);
449✔
795
            }
796
         };
460✔
797

798
         if(requested.empty()) {
1✔
799
            /*
800
            If nothing was requested on the command line, run everything. First
801
            run the "essentials" to smoke test, then everything else in
802
            alphabetical order.
803
            */
804
            result = m_smoke_tests;
1✔
805
            for(const auto& [test_name, _] : m_tests) {
460✔
806
               insert_if_not_exists_and_not_skipped(test_name);
459✔
807
            }
808
         } else {
809
            for(const auto& r : requested) {
×
810
               if(m_tests.contains(r)) {
×
811
                  insert_if_not_exists_and_not_skipped(r);
×
812
               } else if(auto elems = m_categories.equal_range(r); elems.first != m_categories.end()) {
×
813
                  for(; elems.first != elems.second; ++elems.first) {
×
814
                     insert_if_not_exists_and_not_skipped(elems.first->second);
×
815
                  }
816
               } else {
817
                  throw Test_Error("Unknown test suite or category: " + r);
×
818
               }
819
            }
820
         }
821

822
         return result;
1✔
823
      }
1✔
824

825
      bool needs_serialization(const std::string& test_name) const {
486✔
826
         return Botan::value_exists(m_mutexed_tests, test_name);
27✔
827
      }
828

829
   private:
830
      Test_Registry() = default;
1✔
831

832
   private:
833
      std::map<std::string, std::function<std::unique_ptr<Test>()>> m_tests;
834
      std::multimap<std::string, std::string> m_categories;
835
      std::vector<std::string> m_smoke_tests;
836
      std::vector<std::string> m_mutexed_tests;
837
};
838

839
}  // namespace
840

841
// static Test:: functions
842

843
//static
844
void Test::register_test(const std::string& category,
459✔
845
                         const std::string& name,
846
                         bool smoke_test,
847
                         bool needs_serialization,
848
                         std::function<std::unique_ptr<Test>()> maker_fn) {
849
   Test_Registry::instance().register_test(category, name, smoke_test, needs_serialization, std::move(maker_fn));
918✔
850
}
459✔
851

852
//static
853
uint64_t Test::timestamp() {
182,544✔
854
   auto now = std::chrono::system_clock::now().time_since_epoch();
182,544✔
855
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
2,073✔
856
}
857

858
//static
859
std::vector<Test::Result> Test::flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists) {
4✔
860
   std::vector<Test::Result> results;
4✔
861
   for(auto& result_list : result_lists) {
26✔
862
      for(auto& result : result_list) {
71✔
863
         results.emplace_back(std::move(result));
49✔
864
      }
865
   }
866
   return results;
4✔
867
}
×
868

869
//static
870
std::vector<std::string> Test::registered_tests() {
×
871
   return Test_Registry::instance().registered_tests();
×
872
}
873

874
//static
875
std::vector<std::string> Test::registered_test_categories() {
×
876
   return Test_Registry::instance().registered_test_categories();
×
877
}
878

879
//static
880
std::unique_ptr<Test> Test::get_test(const std::string& test_name) {
459✔
881
   return Test_Registry::instance().get_test(test_name);
459✔
882
}
883

884
//static
885
bool Test::test_needs_serialization(const std::string& test_name) {
459✔
886
   return Test_Registry::instance().needs_serialization(test_name);
459✔
887
}
888

889
//static
890
std::vector<std::string> Test::filter_registered_tests(const std::vector<std::string>& requested,
1✔
891
                                                       const std::vector<std::string>& to_be_skipped) {
892
   return Test_Registry::instance().filter_registered_tests(requested, to_be_skipped);
1✔
893
}
894

895
//static
896
std::string Test::temp_file_name(const std::string& basename) {
21✔
897
   // TODO add a --tmp-dir option to the tests to specify where these files go
898

899
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
900

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

904
   const int fd = ::mkstemp(mkstemp_basename.data());
21✔
905

906
   // error
907
   if(fd < 0) {
21✔
908
      return "";
×
909
   }
910

911
   ::close(fd);
21✔
912

913
   return mkstemp_basename;
21✔
914
#else
915
   // For now just create the temp in the current working directory
916
   return basename;
917
#endif
918
}
21✔
919

920
bool Test::copy_file(const std::string& from, const std::string& to) {
1✔
921
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(__cpp_lib_filesystem)
922
   std::error_code ec;  // don't throw, just return false on error
1✔
923
   return std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
1✔
924
#else
925
   // TODO: implement fallbacks to POSIX or WIN32
926
   // ... but then again: it's 2023 and we're using C++20 :o)
927
   BOTAN_UNUSED(from, to);
928
   throw Botan::No_Filesystem_Access();
929
#endif
930
}
931

932
std::string Test::read_data_file(const std::string& path) {
39✔
933
   const std::string fsname = Test::data_file(path);
39✔
934
   std::ifstream file(fsname.c_str());
39✔
935
   if(!file.good()) {
39✔
936
      throw Test_Error("Error reading from " + fsname);
×
937
   }
938

939
   return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
78✔
940
}
39✔
941

942
std::vector<uint8_t> Test::read_binary_data_file(const std::string& path) {
41✔
943
   const std::string fsname = Test::data_file(path);
41✔
944
   std::ifstream file(fsname.c_str(), std::ios::binary);
41✔
945
   if(!file.good()) {
41✔
946
      throw Test_Error("Error reading from " + fsname);
×
947
   }
948

949
   std::vector<uint8_t> contents;
41✔
950

951
   while(file.good()) {
89✔
952
      std::vector<uint8_t> buf(4096);
48✔
953
      file.read(reinterpret_cast<char*>(buf.data()), buf.size());
48✔
954
      const size_t got = static_cast<size_t>(file.gcount());
48✔
955

956
      if(got == 0 && file.eof()) {
48✔
957
         break;
958
      }
959

960
      contents.insert(contents.end(), buf.data(), buf.data() + got);
48✔
961
   }
48✔
962

963
   return contents;
82✔
964
}
41✔
965

966
// static member variables of Test
967

968
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
969
Test_Options Test::m_opts;
970
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
971
std::string Test::m_test_rng_seed;
972

973
//static
974
void Test::set_test_options(const Test_Options& opts) {
1✔
975
   m_opts = opts;
1✔
976
}
1✔
977

978
namespace {
979

980
/*
981
* This is a fast, simple, deterministic PRNG that's used for running
982
* the tests. It is not intended to be cryptographically secure.
983
*/
984
class Testsuite_RNG final : public Botan::RandomNumberGenerator {
9✔
985
   public:
986
      std::string name() const override { return "Testsuite_RNG"; }
×
987

988
      void clear() override { m_x = 0; }
×
989

990
      bool accepts_input() const override { return true; }
×
991

992
      bool is_seeded() const override { return true; }
277,750✔
993

994
      void fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) override {
9,998,766✔
995
         for(const auto byte : input) {
9,998,766✔
996
            mix(byte);
×
997
         }
998

999
         for(auto& byte : output) {
72,535,894✔
1000
            byte = mix();
62,537,128✔
1001
         }
1002
      }
9,998,766✔
1003

1004
      Testsuite_RNG(std::string_view seed, std::string_view test_name) : m_x(0) {
902✔
1005
         for(const char c : seed) {
27,060✔
1006
            this->mix(static_cast<uint8_t>(c));
26,158✔
1007
         }
1008
         for(const char c : test_name) {
37,479✔
1009
            this->mix(static_cast<uint8_t>(c));
36,577✔
1010
         }
1011
      }
902✔
1012

1013
   private:
1014
      uint8_t mix(uint8_t input = 0) {
62,599,863✔
1015
         m_x ^= input;
62,599,863✔
1016
         m_x *= 0xF2E16957;
62,599,863✔
1017
         m_x += 0xE50B590F;
62,599,863✔
1018
         return static_cast<uint8_t>(m_x >> 27);
62,599,863✔
1019
      }
1020

1021
      uint64_t m_x;
1022
};
1023

1024
}  // namespace
1025

1026
//static
1027
void Test::set_test_rng_seed(std::span<const uint8_t> seed, size_t epoch) {
1✔
1028
   m_test_rng_seed = Botan::fmt("seed={} epoch={}", Botan::hex_encode(seed), epoch);
1✔
1029
}
1✔
1030

1031
//static
1032
std::unique_ptr<Botan::RandomNumberGenerator> Test::new_rng(std::string_view test_name) {
893✔
1033
   return std::make_unique<Testsuite_RNG>(m_test_rng_seed, test_name);
893✔
1034
}
1035

1036
//static
1037
std::shared_ptr<Botan::RandomNumberGenerator> Test::new_shared_rng(std::string_view test_name) {
9✔
1038
   return std::make_shared<Testsuite_RNG>(m_test_rng_seed, test_name);
9✔
1039
}
1040

1041
//static
1042
std::string Test::data_file(const std::string& file) {
1,126✔
1043
   return options().data_dir() + "/" + file;
2,252✔
1044
}
1045

1046
//static
1047
std::string Test::data_file(std::string_view subdir, std::string_view filename) {
4✔
1048
   if(subdir.empty() || filename.empty()) {
4✔
1049
      throw Test_Error("Empty subdir or filename in Test::data_file");
×
1050
   }
1051
   return Botan::fmt("{}/{}/{}", options().data_dir(), subdir, filename);
4✔
1052
}
1053

1054
//static
1055
std::string Test::data_dir(const std::string& subdir) {
1✔
1056
   return options().data_dir() + "/" + subdir;
2✔
1057
}
1058

1059
//static
1060
std::vector<std::string> Test::files_in_data_dir(const std::string& subdir) {
394✔
1061
   auto fs = Botan::get_files_recursive(options().data_dir() + "/" + subdir);
1,182✔
1062
   if(fs.empty()) {
394✔
1063
      throw Test_Error("Test::files_in_data_dir encountered empty subdir " + subdir);
×
1064
   }
1065
   return fs;
394✔
1066
}
×
1067

1068
//static
1069
std::string Test::data_file_as_temporary_copy(const std::string& what) {
1✔
1070
   auto tmp_basename = what;
1✔
1071
   std::replace(tmp_basename.begin(), tmp_basename.end(), '/', '_');
1✔
1072
   auto temp_file = temp_file_name("tmp-" + tmp_basename);
1✔
1073
   if(temp_file.empty()) {
1✔
1074
      return "";
×
1075
   }
1076
   if(!Test::copy_file(data_file(what), temp_file)) {
1✔
1077
      return "";
×
1078
   }
1079
   return temp_file;
1✔
1080
}
1✔
1081

1082
//static
1083
std::vector<std::string> Test::provider_filter(const std::vector<std::string>& providers) {
49,595✔
1084
   if(m_opts.provider().empty()) {
49,595✔
1085
      return providers;
49,595✔
1086
   }
1087
   for(auto&& provider : providers) {
×
1088
      if(provider == m_opts.provider()) {
×
1089
         return std::vector<std::string>{provider};
×
1090
      }
1091
   }
1092
   return std::vector<std::string>{};
×
1093
}
×
1094

1095
std::string Test::random_password(Botan::RandomNumberGenerator& rng) {
222✔
1096
   const size_t len = 1 + rng.next_byte() % 32;
222✔
1097
   return Botan::hex_encode(rng.random_vec(len));
444✔
1098
}
1099

1100
size_t Test::random_index(Botan::RandomNumberGenerator& rng, size_t max) {
8,062✔
1101
   return Botan::load_be(rng.random_array<8>()) % max;
8,062✔
1102
}
1103

1104
void VarMap::clear() {
34,355✔
1105
   m_vars.clear();
×
1106
}
×
1107

1108
namespace {
1109

1110
bool varmap_pair_lt(const std::pair<std::string, std::string>& kv, std::string_view k) {
1,690,541✔
1111
   return kv.first < k;
1,690,541✔
1112
}
1113

1114
}  // namespace
1115

1116
bool VarMap::has_key(std::string_view key) const {
213,569✔
1117
   return get_opt_var(key).has_value();
213,569✔
1118
}
1119

1120
void VarMap::add(std::string_view key, std::string_view value) {
156,221✔
1121
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
156,221✔
1122

1123
   if(i != m_vars.end() && i->first == key) {
163,440✔
1124
      i->second = value;
44,673✔
1125
   } else {
1126
      m_vars.emplace(i, key, value);
111,548✔
1127
   }
1128
}
156,221✔
1129

1130
std::optional<std::string> VarMap::get_opt_var(std::string_view key) const {
293,660✔
1131
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
293,660✔
1132

1133
   if(i != m_vars.end() && i->first == key) {
295,544✔
1134
      return i->second;
241,107✔
1135
   } else {
1136
      return {};
52,553✔
1137
   }
1138
}
1139

1140
const std::string& VarMap::get_req_var(std::string_view key) const {
261,655✔
1141
   auto i = std::lower_bound(m_vars.begin(), m_vars.end(), key, varmap_pair_lt);
261,655✔
1142

1143
   if(i != m_vars.end() && i->first == key) {
261,655✔
1144
      return i->second;
261,655✔
1145
   } else {
1146
      throw Test_Error(Botan::fmt("Test missing variable '{}'", key));
×
1147
   }
1148
}
1149

1150
std::string VarMap::get_req_str(std::string_view key) const {
53,359✔
1151
   return std::string(get_req_var(key));
53,359✔
1152
}
1153

1154
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(std::string_view key) const {
12✔
1155
   const auto& var = get_req_var(key);
12✔
1156

1157
   std::vector<std::vector<uint8_t>> bin_list;
12✔
1158

1159
   for(auto&& part : Botan::split_on(var, ',')) {
62✔
1160
      try {
50✔
1161
         bin_list.push_back(Botan::hex_decode(part));
100✔
1162
      } catch(std::exception& e) {
×
1163
         std::ostringstream oss;
×
1164
         oss << "Bad input '" << part << "'"
×
1165
             << " in binary list key " << key << " - " << e.what();
×
1166
         throw Test_Error(oss.str());
×
1167
      }
×
1168
   }
12✔
1169

1170
   return bin_list;
12✔
1171
}
×
1172

1173
std::vector<uint8_t> VarMap::get_req_bin(std::string_view key) const {
164,984✔
1174
   const auto& var = get_req_var(key);
164,984✔
1175

1176
   try {
164,984✔
1177
      return Botan::hex_decode(var);
164,984✔
1178
   } catch(std::exception& e) {
×
1179
      throw Test_Error(Botan::fmt("Bad hex input '{}' for key '{}' err '{}'", var, key, e.what()));
×
1180
   }
×
1181
}
1182

1183
std::string VarMap::get_opt_str(std::string_view key, std::string_view def_value) const {
14,468✔
1184
   if(auto v = get_opt_var(key)) {
14,468✔
1185
      return *v;
14,547✔
1186
   } else {
1187
      return std::string(def_value);
28,778✔
1188
   }
14,468✔
1189
}
1190

1191
bool VarMap::get_req_bool(std::string_view key) const {
74✔
1192
   const auto& var = get_req_var(key);
74✔
1193

1194
   if(var == "true") {
74✔
1195
      return true;
1196
   } else if(var == "false") {
34✔
1197
      return false;
1198
   } else {
1199
      throw Test_Error(Botan::fmt("Invalid boolean '{}' for key '{}'", var, key));
×
1200
   }
1201
}
1202

1203
size_t VarMap::get_req_sz(std::string_view key) const {
4,653✔
1204
   return Botan::to_u32bit(get_req_var(key));
4,653✔
1205
}
1206

1207
uint8_t VarMap::get_req_u8(std::string_view key) const {
17✔
1208
   const size_t s = this->get_req_sz(key);
17✔
1209
   if(s > 256) {
17✔
1210
      throw Test_Error(Botan::fmt("Invalid value for '{}' expected uint8_t but got '{}'", key, s));
×
1211
   }
1212
   return static_cast<uint8_t>(s);
17✔
1213
}
1214

1215
uint32_t VarMap::get_req_u32(std::string_view key) const {
14✔
1216
   return static_cast<uint32_t>(get_req_sz(key));
14✔
1217
}
1218

1219
uint64_t VarMap::get_req_u64(std::string_view key) const {
17✔
1220
   const auto& var = get_req_var(key);
17✔
1221
   if(const auto val = Botan::parse_u64(var)) {
17✔
1222
      return *val;
17✔
1223
   } else {
1224
      throw Test_Error(Botan::fmt("Invalid u64 value '{}' for key '{}'", var, key));
×
1225
   }
1226
}
1227

1228
size_t VarMap::get_opt_sz(std::string_view key, const size_t def_value) const {
13,884✔
1229
   if(auto v = get_opt_var(key)) {
13,884✔
1230
      return Botan::to_u32bit(*v);
12,261✔
1231
   } else {
1232
      return def_value;
1233
   }
13,884✔
1234
}
1235

1236
uint64_t VarMap::get_opt_u64(std::string_view key, const uint64_t def_value) const {
4,363✔
1237
   if(auto var = get_opt_var(key)) {
4,363✔
1238
      if(const auto val = Botan::parse_u64(*var)) {
1,053✔
1239
         return *val;
1,053✔
1240
      } else {
1241
         throw Test_Error(Botan::fmt("Invalid u64 value '{}' for key '{}'", *var, key));
×
1242
      }
1243
   } else {
1244
      return def_value;
1245
   }
4,363✔
1246
}
1247

1248
std::vector<uint8_t> VarMap::get_opt_bin(std::string_view key) const {
47,296✔
1249
   if(auto v = get_opt_var(key)) {
47,296✔
1250
      try {
17,835✔
1251
         return Botan::hex_decode(*v);
17,835✔
1252
      } catch(std::exception&) {
×
1253
         throw Test_Error(Botan::fmt("Invalid hex for key '{}' got '{}'", key, *v));
×
1254
      }
×
1255
   } else {
1256
      return {};
29,461✔
1257
   };
47,296✔
1258
}
1259

1260
#if defined(BOTAN_HAS_BIGINT)
1261
Botan::BigInt VarMap::get_req_bn(std::string_view key) const {
38,556✔
1262
   const auto& var = get_req_var(key);
38,556✔
1263

1264
   try {
38,556✔
1265
      return Botan::BigInt(var);
38,556✔
1266
   } catch(std::exception&) {
×
1267
      throw Test_Error(Botan::fmt("Invalid BigInt for key '{}' got '{}'", key, var));
×
1268
   }
×
1269
}
1270

1271
Botan::BigInt VarMap::get_opt_bn(std::string_view key, const Botan::BigInt& def_value) const {
80✔
1272
   if(auto v = get_opt_var(key)) {
80✔
1273
      try {
56✔
1274
         return Botan::BigInt(*v);
56✔
1275
      } catch(std::exception&) {
×
1276
         throw Test_Error(Botan::fmt("Invalid BigInt for key '{}' got '{}'", key, *v));
×
1277
      }
×
1278
   } else {
1279
      return def_value;
24✔
1280
   }
80✔
1281
}
1282
#endif
1283

1284
class Text_Based_Test::Text_Based_Test_Data {
1285
   public:
1286
      Text_Based_Test_Data(const std::string& data_src,
194✔
1287
                           const std::string& required_keys_str,
1288
                           const std::string& optional_keys_str) :
194✔
1289
            m_data_src(data_src) {
388✔
1290
         if(required_keys_str.empty()) {
194✔
1291
            throw Test_Error("Invalid test spec");
×
1292
         }
1293

1294
         m_required_keys = Botan::split_on(required_keys_str, ',');
194✔
1295
         std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
194✔
1296

1297
         m_all_keys.insert(m_required_keys.begin(), m_required_keys.end());
194✔
1298
         m_all_keys.insert(optional_keys.begin(), optional_keys.end());
194✔
1299
         m_output_key = m_required_keys.at(m_required_keys.size() - 1);
194✔
1300
      }
194✔
1301

1302
      std::string get_next_line();
1303

1304
      const std::string& current_source_name() const { return m_cur_src_name; }
×
1305

1306
      bool known_key(const std::string& key) const;
1307

1308
      const std::vector<std::string>& required_keys() const { return m_required_keys; }
48,536✔
1309

1310
      const std::string& output_key() const { return m_output_key; }
156,221✔
1311

1312
      const std::vector<std::string>& cpu_flags() const { return m_cpu_flags; }
48,395✔
1313

1314
      void set_cpu_flags(std::vector<std::string> flags) { m_cpu_flags = std::move(flags); }
27✔
1315

1316
      const std::string& initial_data_src_name() const { return m_data_src; }
194✔
1317

1318
   private:
1319
      std::string m_data_src;
1320
      std::vector<std::string> m_required_keys;
1321
      std::unordered_set<std::string> m_all_keys;
1322
      std::string m_output_key;
1323

1324
      bool m_first = true;
1325
      std::unique_ptr<std::istream> m_cur;
1326
      std::string m_cur_src_name;
1327
      std::deque<std::string> m_srcs;
1328
      std::vector<std::string> m_cpu_flags;
1329
};
1330

1331
Text_Based_Test::Text_Based_Test(const std::string& data_src,
194✔
1332
                                 const std::string& required_keys,
1333
                                 const std::string& optional_keys) :
194✔
1334
      m_data(std::make_unique<Text_Based_Test_Data>(data_src, required_keys, optional_keys)) {}
194✔
1335

1336
Text_Based_Test::~Text_Based_Test() = default;
194✔
1337

1338
std::string Text_Based_Test::Text_Based_Test_Data::get_next_line() {
157,279✔
1339
   while(true) {
157,553✔
1340
      if(m_cur == nullptr || m_cur->good() == false) {
157,553✔
1341
         if(m_srcs.empty()) {
478✔
1342
            if(m_first) {
388✔
1343
               if(m_data_src.ends_with(".vec")) {
194✔
1344
                  m_srcs.push_back(Test::data_file(m_data_src));
364✔
1345
               } else {
1346
                  const auto fs = Test::files_in_data_dir(m_data_src);
12✔
1347
                  m_srcs.assign(fs.begin(), fs.end());
12✔
1348
                  if(m_srcs.empty()) {
12✔
1349
                     throw Test_Error("Error reading test data dir " + m_data_src);
×
1350
                  }
1351
               }
12✔
1352

1353
               m_first = false;
194✔
1354
            } else {
1355
               return "";  // done
194✔
1356
            }
1357
         }
1358

1359
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
374✔
1360
         m_cur_src_name = m_srcs[0];
284✔
1361

1362
#if defined(BOTAN_HAS_CPUID)
1363
         // Reinit cpuid on new file if needed
1364
         if(m_cpu_flags.empty() == false) {
284✔
1365
            m_cpu_flags.clear();
23✔
1366
            Botan::CPUID::initialize();
23✔
1367
         }
1368
#endif
1369

1370
         if(!m_cur->good()) {
284✔
1371
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
1372
         }
1373

1374
         m_srcs.pop_front();
284✔
1375
      }
1376

1377
      while(m_cur->good()) {
228,410✔
1378
         std::string line;
228,136✔
1379
         std::getline(*m_cur, line);
228,136✔
1380

1381
         if(line.empty()) {
228,136✔
1382
            continue;
55,404✔
1383
         }
1384

1385
         if(line[0] == '#') {
172,732✔
1386
            if(line.starts_with("#test ")) {
15,674✔
1387
               return line;
27✔
1388
            } else {
1389
               continue;
15,647✔
1390
            }
1391
         }
1392

1393
         return line;
157,058✔
1394
      }
228,136✔
1395
   }
1396
}
1397

1398
bool Text_Based_Test::Text_Based_Test_Data::known_key(const std::string& key) const {
156,221✔
1399
   return m_all_keys.contains(key);
156,221✔
1400
}
1401

1402
namespace {
1403

1404
// strips leading and trailing but not internal whitespace
1405
std::string strip_ws(const std::string& in) {
312,442✔
1406
   const char* whitespace = " ";
312,442✔
1407

1408
   const auto first_c = in.find_first_not_of(whitespace);
312,442✔
1409
   if(first_c == std::string::npos) {
312,442✔
1410
      return "";
1,084✔
1411
   }
1412

1413
   const auto last_c = in.find_last_not_of(whitespace);
311,358✔
1414

1415
   return in.substr(first_c, last_c - first_c + 1);
311,358✔
1416
}
1417

1418
std::vector<std::string> parse_cpuid_bits(const std::vector<std::string>& tok) {
27✔
1419
   std::vector<std::string> bits;
27✔
1420

1421
#if defined(BOTAN_HAS_CPUID)
1422
   for(size_t i = 1; i < tok.size(); ++i) {
129✔
1423
      if(auto bit = Botan::CPUID::bit_from_string(tok[i])) {
102✔
1424
         bits.push_back(bit->to_string());
124✔
1425
      }
1426
   }
1427
#else
1428
   BOTAN_UNUSED(tok);
1429
#endif
1430

1431
   return bits;
27✔
1432
}
×
1433

1434
}  // namespace
1435

1436
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) {
32,739✔
1437
   return false;
32,739✔
1438
}
1439

1440
std::vector<Test::Result> Text_Based_Test::run() {
194✔
1441
   std::vector<Test::Result> results;
194✔
1442

1443
   std::string header;
194✔
1444
   std::string header_or_name = m_data->initial_data_src_name();
194✔
1445
   VarMap vars;
194✔
1446
   size_t test_cnt = 0;
194✔
1447

1448
   while(true) {
157,279✔
1449
      const std::string line = m_data->get_next_line();
157,279✔
1450
      if(line.empty()) {
157,279✔
1451
         // EOF
1452
         break;
1453
      }
1454

1455
      if(line.starts_with("#test ")) {
157,085✔
1456
         std::vector<std::string> pragma_tokens = Botan::split_on(line.substr(6), ' ');
27✔
1457

1458
         if(pragma_tokens.empty()) {
27✔
1459
            throw Test_Error("Empty pragma found in " + m_data->current_source_name());
×
1460
         }
1461

1462
         if(pragma_tokens[0] != "cpuid") {
27✔
1463
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1464
         }
1465

1466
         if(!Test_Registry::instance().needs_serialization(this->test_name())) {
54✔
1467
            throw Test_Error(Botan::fmt("'{}' used cpuid control but is not serialized", this->test_name()));
×
1468
         }
1469

1470
         m_data->set_cpu_flags(parse_cpuid_bits(pragma_tokens));
54✔
1471

1472
         continue;
27✔
1473
      } else if(line[0] == '#') {
157,085✔
1474
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_data->current_source_name());
×
1475
      }
1476

1477
      if(line[0] == '[' && line[line.size() - 1] == ']') {
157,058✔
1478
         header = line.substr(1, line.size() - 2);
837✔
1479
         header_or_name = header;
837✔
1480
         test_cnt = 0;
837✔
1481
         vars.clear();
837✔
1482
         continue;
837✔
1483
      }
1484

1485
      const std::string test_id = "test " + std::to_string(test_cnt);
312,442✔
1486

1487
      auto equal_i = line.find_first_of('=');
156,221✔
1488

1489
      if(equal_i == std::string::npos) {
156,221✔
1490
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1491
         continue;
×
1492
      }
1493

1494
      const std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
312,442✔
1495
      const std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
312,442✔
1496

1497
      if(!m_data->known_key(key)) {
156,221✔
1498
         auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key));
×
1499
         results.push_back(r);
×
1500
      }
×
1501

1502
      vars.add(key, val);
156,221✔
1503

1504
      if(key == m_data->output_key()) {
156,221✔
1505
         try {
48,536✔
1506
            for(const auto& req_key : m_data->required_keys()) {
245,679✔
1507
               if(!vars.has_key(req_key)) {
197,143✔
1508
                  auto r =
×
1509
                     Test::Result::Failure(header_or_name, Botan::fmt("{} missing required key {}", test_id, req_key));
×
1510
                  results.push_back(r);
×
1511
               }
×
1512
            }
1513

1514
            if(skip_this_test(header, vars)) {
48,536✔
1515
               continue;
141✔
1516
            }
1517

1518
            ++test_cnt;
48,395✔
1519

1520
            const uint64_t start = Test::timestamp();
48,395✔
1521

1522
            Test::Result result = run_one_test(header, vars);
48,395✔
1523
#if defined(BOTAN_HAS_CPUID)
1524
            if(!m_data->cpu_flags().empty()) {
48,395✔
1525
               for(const auto& cpuid_str : m_data->cpu_flags()) {
34,682✔
1526
                  if(const auto bit = Botan::CPUID::Feature::from_string(cpuid_str)) {
23,851✔
1527
                     if(Botan::CPUID::has(*bit)) {
23,851✔
1528
                        Botan::CPUID::clear_cpuid_bit(*bit);
17,531✔
1529
                        // now re-run the test
1530
                        result.merge(run_one_test(header, vars));
17,531✔
1531
                     }
1532
                  }
1533
               }
1534
               Botan::CPUID::initialize();
10,831✔
1535
            }
1536
#endif
1537
            result.set_ns_consumed(Test::timestamp() - start);
48,395✔
1538

1539
            if(result.tests_failed() > 0) {
48,395✔
1540
               std::ostringstream oss;
×
1541
               oss << "Test # " << test_cnt << " ";
×
1542
               if(!header.empty()) {
×
1543
                  oss << header << " ";
×
1544
               }
1545
               oss << "failed ";
×
1546

1547
               for(const auto& k : m_data->required_keys()) {
×
1548
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1549
               }
1550

1551
               result.test_note(oss.str());
×
1552
            }
×
1553
            results.push_back(result);
48,395✔
1554
         } catch(std::exception& e) {
48,395✔
1555
            std::ostringstream oss;
×
1556
            oss << "Test # " << test_cnt << " ";
×
1557
            if(!header.empty()) {
×
1558
               oss << header << " ";
×
1559
            }
1560

1561
            for(const auto& k : m_data->required_keys()) {
×
1562
               oss << k << "=" << vars.get_req_str(k) << " ";
×
1563
            }
1564

1565
            oss << "failed with exception '" << e.what() << "'";
×
1566

1567
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1568
         }
×
1569

1570
         if(clear_between_callbacks()) {
48,395✔
1571
            vars.clear();
189,598✔
1572
         }
1573
      }
1574
   }
157,367✔
1575

1576
   if(results.empty()) {
194✔
1577
      return results;
1578
   }
1579

1580
   try {
194✔
1581
      std::vector<Test::Result> final_tests = run_final_tests();
194✔
1582
      results.insert(results.end(), final_tests.begin(), final_tests.end());
194✔
1583
   } catch(std::exception& e) {
194✔
1584
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1585
   }
×
1586

1587
   return results;
1588
}
194✔
1589

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