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

randombit / botan / 21768358452

06 Feb 2026 10:35PM UTC coverage: 90.064% (-0.003%) from 90.067%
21768358452

Pull #5289

github

web-flow
Merge f589db195 into 8ea0ca252
Pull Request #5289: Further misc header reductions, forward declarations, etc

102238 of 113517 relevant lines covered (90.06%)

11357432.36 hits per line

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

88.53
/src/tests/tests.h
1
/*
2
* (C) 2014,2015 Jack Lloyd
3
* (C) 2015 Simon Warta (Kullo GmbH)
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7

8
#ifndef BOTAN_TESTS_H_
9
#define BOTAN_TESTS_H_
10

11
/*
12
Warning: be very careful about adding any new includes here
13

14
Each include is parsed for every test file which can get quite expensive
15
*/
16

17
#include <botan/assert.h>
18
#include <botan/exceptn.h>
19
#include <botan/symkey.h>
20
#include <botan/types.h>
21
#include <functional>
22
#include <iosfwd>
23
#include <memory>
24
#include <optional>
25
#include <span>
26
#include <sstream>
27
#include <string>
28
#include <variant>
29
#include <vector>
30

31
namespace Botan {
32

33
class RandomNumberGenerator;
34

35
#if defined(BOTAN_HAS_BIGINT)
36
class BigInt;
37
#endif
38

39
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
40
class EC_Point;
41
#endif
42

43
}  // namespace Botan
44

45
namespace Botan_Tests {
46

47
#if defined(BOTAN_HAS_BIGINT)
48
using Botan::BigInt;
49
#endif
50

51
class Test_Error : public std::runtime_error {
52
   public:
53
      explicit Test_Error(const std::string& what) : std::runtime_error(what) {}
1✔
54
};
55

56
class Test_Aborted final : public Test_Error {
57
   public:
58
      explicit Test_Aborted(const std::string& what) : Test_Error(what) {}
×
59
};
60

61
class Test_Options {
62
   public:
63
      Test_Options() = default;
64

65
      Test_Options(const std::vector<std::string>& requested_tests,
1✔
66
                   const std::vector<std::string>& skip_tests,
67
                   const std::string& data_dir,
68
                   const std::string& pkcs11_lib,
69
                   const std::string& provider,
70
                   const std::string& tpm2_tcti_name,
71
                   const std::string& tpm2_tcti_conf,
72
                   size_t tpm2_persistent_rsa_handle,
73
                   size_t tpm2_persistent_ecc_handle,
74
                   const std::string& tpm2_persistent_auth_value,
75
                   const std::string& drbg_seed,
76
                   const std::string& xml_results_dir,
77
                   const std::vector<std::string>& report_properties,
78
                   size_t test_runs,
79
                   size_t test_threads,
80
                   bool verbose,
81
                   bool log_success,
82
                   bool run_online_tests,
83
                   bool run_long_tests,
84
                   bool run_memory_intensive_tests,
85
                   bool abort_on_first_fail,
86
                   bool no_stdout) :
1✔
87
            m_requested_tests(requested_tests),
1✔
88
            m_skip_tests(skip_tests),
1✔
89
            m_data_dir(data_dir),
1✔
90
            m_pkcs11_lib(pkcs11_lib),
1✔
91
            m_provider(provider),
1✔
92
            m_tpm2_tcti_name(tpm2_tcti_name),
1✔
93
            m_tpm2_tcti_conf(tpm2_tcti_conf),
1✔
94
            m_tpm2_persistent_rsa_handle(tpm2_persistent_rsa_handle),
1✔
95
            m_tpm2_persistent_ecc_handle(tpm2_persistent_ecc_handle),
1✔
96
            m_tpm2_persistent_auth_value(tpm2_persistent_auth_value),
1✔
97
            m_drbg_seed(drbg_seed),
1✔
98
            m_xml_results_dir(xml_results_dir),
1✔
99
            m_report_properties(report_properties),
1✔
100
            m_test_runs(test_runs),
1✔
101
            m_test_threads(test_threads),
1✔
102
            m_verbose(verbose),
1✔
103
            m_log_success(log_success),
1✔
104
            m_run_online_tests(run_online_tests),
1✔
105
            m_run_long_tests(run_long_tests),
1✔
106
            m_run_memory_intensive_tests(run_memory_intensive_tests),
1✔
107
            m_abort_on_first_fail(abort_on_first_fail),
1✔
108
            m_no_stdout(no_stdout) {}
1✔
109

110
      const std::vector<std::string>& requested_tests() const { return m_requested_tests; }
1✔
111

112
      const std::vector<std::string>& skip_tests() const { return m_skip_tests; }
1✔
113

114
      const std::string& data_dir() const { return m_data_dir; }
115

116
      const std::string& pkcs11_lib() const { return m_pkcs11_lib; }
3✔
117

118
      const std::string& provider() const { return m_provider; }
2✔
119

120
      const std::optional<std::string>& tpm2_tcti_name() const { return m_tpm2_tcti_name; }
121

122
      const std::optional<std::string>& tpm2_tcti_conf() const { return m_tpm2_tcti_conf; }
123

124
      uint32_t tpm2_persistent_rsa_handle() const { return static_cast<uint32_t>(m_tpm2_persistent_rsa_handle); }
2✔
125

126
      uint32_t tpm2_persistent_ecc_handle() const { return static_cast<uint32_t>(m_tpm2_persistent_ecc_handle); }
2✔
127

128
      const std::string& tpm2_persistent_auth_value() const { return m_tpm2_persistent_auth_value; }
129

130
      const std::string& drbg_seed() const { return m_drbg_seed; }
1✔
131

132
      const std::string& xml_results_dir() const { return m_xml_results_dir; }
1✔
133

134
      const std::vector<std::string>& report_properties() const { return m_report_properties; }
1✔
135

136
      size_t test_runs() const { return m_test_runs; }
4✔
137

138
      size_t test_threads() const { return m_test_threads; }
3✔
139

140
      bool log_success() const { return m_log_success; }
3,620,285✔
141

142
      bool run_online_tests() const { return m_run_online_tests; }
2✔
143

144
      bool run_long_tests() const { return m_run_long_tests; }
2,871✔
145

146
      bool run_memory_intensive_tests() const { return m_run_memory_intensive_tests; }
1✔
147

148
      bool abort_on_first_fail() const { return m_abort_on_first_fail; }
25✔
149

150
      bool no_stdout() const { return m_no_stdout; }
1✔
151

152
      bool verbose() const { return m_verbose; }
2,542✔
153

154
   private:
155
      std::vector<std::string> m_requested_tests;
156
      std::vector<std::string> m_skip_tests;
157
      std::string m_data_dir;
158
      std::string m_pkcs11_lib;
159
      std::string m_provider;
160
      std::optional<std::string> m_tpm2_tcti_name;
161
      std::optional<std::string> m_tpm2_tcti_conf;
162
      size_t m_tpm2_persistent_rsa_handle = 0;
163
      size_t m_tpm2_persistent_ecc_handle = 0;
164
      std::string m_tpm2_persistent_auth_value;
165
      std::string m_drbg_seed;
166
      std::string m_xml_results_dir;
167
      std::vector<std::string> m_report_properties;
168
      size_t m_test_runs = 0;
169
      size_t m_test_threads = 0;
170
      bool m_verbose = false;
171
      bool m_log_success = false;
172
      bool m_run_online_tests = false;
173
      bool m_run_long_tests = false;
174
      bool m_run_memory_intensive_tests = false;
175
      bool m_abort_on_first_fail = false;
176
      bool m_no_stdout = false;
177
};
178

179
namespace detail {
180

181
template <typename, typename = void>
182
constexpr bool has_Botan_to_string = false;
183
template <typename T>
184
constexpr bool has_Botan_to_string<T, std::void_t<decltype(Botan::to_string(std::declval<T>()))>> = true;
185

186
template <typename, typename = void>
187
constexpr bool has_std_to_string = false;
188
template <typename T>
189
constexpr bool has_std_to_string<T, std::void_t<decltype(std::to_string(std::declval<T>()))>> = true;
190

191
template <typename, typename = void>
192
constexpr bool has_ostream_operator = false;
193
template <typename T>
194
constexpr bool
195
   has_ostream_operator<T, std::void_t<decltype(operator<<(std::declval<std::ostringstream&>(), std::declval<T>()))>> =
196
      true;
197

198
template <typename T>
199
struct is_optional : std::false_type {};
200

201
template <typename T>
202
struct is_optional<std::optional<T>> : std::true_type {};
203

204
template <typename T>
205
constexpr bool is_optional_v = is_optional<T>::value;
206

207
}  // namespace detail
208

209
/**
210
 * A code location consisting of the source file path and a line
211
 */
212
struct CodeLocation {
213
      const char* path;
214
      unsigned int line;
215
};
216

217
/*
218
* A generic test which returns a set of results when run.
219
* The tests may not all have the same type (for example test
220
* "block" returns results for "AES-128" and "AES-256").
221
*
222
* For most test cases you want Text_Based_Test derived below
223
*/
224
class Test {
225
   public:
226
      /*
227
      * Some number of test results, all associated with who()
228
      */
229
      class Result final {
230
         public:
231
            explicit Result(std::string who);
232

233
            /**
234
             * This 'consolidation constructor' creates a single test result from
235
             * a vector of downstream test result objects.
236
             */
237
            Result(std::string who, const std::vector<Result>& downstream_results);
238

239
            size_t tests_passed() const { return m_tests_passed; }
12,590✔
240

241
            size_t tests_failed() const { return m_fail_log.size(); }
68,935✔
242

243
            size_t tests_run() const { return tests_passed() + tests_failed(); }
12,590✔
244

245
            bool any_results() const { return tests_run() > 0; }
246

247
            const std::string& who() const { return m_who; }
235,957✔
248

249
            const std::vector<std::string>& failures() const { return m_fail_log; }
2,516✔
250

251
            const std::vector<std::string>& notes() const { return m_log; }
2,516✔
252

253
            std::optional<uint64_t> elapsed_time() const {
2,516✔
254
               if(m_ns_taken == 0) {
2,516✔
255
                  return std::nullopt;
256
               } else {
257
                  return m_ns_taken;
1,473✔
258
               }
259
            }
260

261
            // Nanoseconds since epoch
262
            uint64_t timestamp() const { return m_timestamp; }
2,516✔
263

264
            std::string result_string() const;
265

266
            static Result Failure(const std::string& who, const std::string& what) {
1✔
267
               Result r(who);
1✔
268
               r.test_failure(what);
1✔
269
               return r;
1✔
270
            }
×
271

272
            static Result Note(const std::string& who, const std::string& what) {
×
273
               Result r(who);
×
274
               r.test_note(what);
×
275
               return r;
×
276
            }
×
277

278
            static Result OfExpectedFailure(bool expecting_failure, const Test::Result& result) {
279
               if(!expecting_failure) {
280
                  return result;
281
               }
282

283
               if(result.tests_failed() == 0) {
284
                  Result r = result;
285
                  r.test_failure("Expected this test to fail, but it did not");
286
                  return r;
287
               } else {
288
                  Result r(result.who());
289
                  r.test_note("Got expected failure");
290
                  return r;
291
               }
292
            }
293

294
            void merge(const Result& other, bool ignore_test_name = false);
295

296
            void test_note(const std::string& note, const char* extra = nullptr);
297

298
            void test_note(const std::string& who, std::span<const uint8_t> data);
299

300
            void note_missing(const std::string& whatever);
301

302
            bool test_success(const std::string& note = "");
303

304
            bool test_failure(const std::string& err);
305

306
            bool test_failure(const std::string& what, const std::string& error);
307

308
            void test_failure(const std::string& what, const uint8_t buf[], size_t buf_len);
309

310
            template <typename Alloc>
311
            void test_failure(const std::string& what, const std::vector<uint8_t, Alloc>& buf) {
1✔
312
               test_failure(what, buf.data(), buf.size());
1✔
313
            }
1✔
314

315
            bool confirm(const std::string& what, bool expr, bool expected = true) {
174,273✔
316
               return test_eq(what, expr, expected);
173,944✔
317
            }
318

319
            /**
320
             * Require a condition, throw Test_Aborted otherwise
321
             * Note: works best when combined with CHECK scopes!
322
             */
323
            void require(const std::string& what, bool expr, bool expected = true) {
329✔
324
               if(!confirm(what, expr, expected)) {
329✔
325
                  throw Test_Aborted("test aborted, because required condition was not met: " + what);
×
326
               }
327
            }
329✔
328

329
            template <typename T>
330
            bool test_is_eq(const T& produced, const T& expected) {
343✔
331
               return test_is_eq("comparison", produced, expected);
343✔
332
            }
333

334
            template <typename T>
335
            bool test_is_eq(const std::string& what, const T& produced, const T& expected) {
906,706✔
336
               std::ostringstream out;
906,706✔
337
               out << m_who << " " << what;
906,706✔
338

339
               if(produced == expected) {
906,697✔
340
                  out << " produced expected result";
906,704✔
341
                  return test_success(out.str());
906,704✔
342
               } else {
343
                  out << " produced unexpected result '" << to_string(produced) << "' expected '" << to_string(expected)
344
                      << "'";
7✔
345
                  return test_failure(out.str());
2✔
346
               }
347
            }
906,706✔
348

349
            template <typename T>
350
            bool test_not_null(const std::string& what, const T& ptr) {
1,735✔
351
               if(ptr == nullptr) {
1,735✔
352
                  return test_failure(what + " was null");
×
353
               } else {
354
                  return test_success(what + " was not null");
1,735✔
355
               }
356
            }
357

358
            template <typename T>
359
            bool test_not_nullopt(const std::string& what, const std::optional<T>& val) {
10✔
360
               if(val == std::nullopt) {
10✔
361
                  return test_failure(what + " was nullopt");
×
362
               } else {
363
                  return test_success(what + " was not nullopt");
10✔
364
               }
365
            }
366

367
            bool test_eq(const std::string& what, const char* produced, const char* expected);
368

369
            bool test_is_nonempty(const std::string& what_is_it, const std::string& to_examine);
370

371
            bool test_eq(const std::string& what, const std::string& produced, const std::string& expected);
372

373
            bool test_eq(const std::string& what, bool produced, bool expected);
374

375
            bool test_eq(const std::string& what, size_t produced, size_t expected);
376
            bool test_eq_sz(const std::string& what, size_t produced, size_t expected);
377

378
            bool test_eq(const std::string& what,
379
                         const Botan::OctetString& produced,
380
                         const Botan::OctetString& expected);
381

382
            template <typename I1, typename I2>
383
            bool test_int_eq(I1 x, I2 y, const char* what) {
59✔
384
               return test_eq(what, static_cast<size_t>(x), static_cast<size_t>(y));
59✔
385
            }
386

387
            template <typename I1, typename I2>
388
            bool test_int_eq(const std::string& what, I1 x, I2 y) {
5,192✔
389
               return test_eq(what, static_cast<size_t>(x), static_cast<size_t>(y));
5,192✔
390
            }
391

392
            template <typename T>
393
            bool test_eq(const std::string& what, const std::optional<T>& a, const std::optional<T>& b) {
1,215✔
394
               if(a.has_value() != b.has_value()) {
1,215✔
395
                  std::ostringstream err;
×
396
                  err << m_who << " " << what << " only one of a/b was nullopt";
×
397
                  return test_failure(err.str());
×
398
               } else if(a.has_value() && b.has_value()) {
1,215✔
399
                  return test_is_eq(what, a.value(), b.value());
10✔
400
               } else {
401
                  // both nullopt
402
                  return test_success();
1,205✔
403
               }
404
            }
405

406
            bool test_lt(const std::string& what, size_t produced, size_t expected);
407
            bool test_lte(const std::string& what, size_t produced, size_t expected);
408
            bool test_gt(const std::string& what, size_t produced, size_t expected);
409
            bool test_gte(const std::string& what, size_t produced, size_t expected);
410

411
            template <typename T>
412
            bool test_rc_ok(const std::string& func, T rc) {
2,846✔
413
               static_assert(std::is_integral_v<T>, "Integer required.");
414

415
               if(rc != 0) {
2,846✔
416
                  std::ostringstream err;
1✔
417
                  err << m_who;
1✔
418
                  err << " " << func;
1✔
419
                  err << " unexpectedly failed with error code " << rc;
1✔
420
                  return test_failure(err.str());
1✔
421
               }
1✔
422

423
               return test_success();
2,845✔
424
            }
425

426
            template <typename T>
427
            bool test_rc_fail(const std::string& func, const std::string& why, T rc) {
27✔
428
               static_assert(std::is_integral_v<T>, "Integer required.");
429

430
               if(rc == 0) {
27✔
431
                  std::ostringstream err;
1✔
432
                  err << m_who;
1✔
433
                  err << " call to " << func << " unexpectedly succeeded";
1✔
434
                  err << " expecting failure because " << why;
1✔
435
                  return test_failure(err.str());
1✔
436
               }
1✔
437

438
               return test_success();
26✔
439
            }
440

441
            bool test_rc(const std::string& func, int expected, int rc);
442

443
            bool test_rc_init(const std::string& func, int rc);
444

445
            bool test_ne(const std::string& what, size_t produced, size_t expected);
446

447
            bool test_ne(const std::string& what, const std::string& str1, const std::string& str2);
448

449
#if defined(BOTAN_HAS_BIGINT)
450
            bool test_eq(const std::string& what, const BigInt& produced, const BigInt& expected);
451
            bool test_ne(const std::string& what, const BigInt& produced, const BigInt& expected);
452
#endif
453

454
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
455
            bool test_eq(const std::string& what, const Botan::EC_Point& a, const Botan::EC_Point& b);
456
#endif
457

458
            bool test_eq(const char* producer,
459
                         const std::string& what,
460
                         const uint8_t produced[],
461
                         size_t produced_size,
462
                         const uint8_t expected[],
463
                         size_t expected_size);
464

465
            bool test_ne(const std::string& what,
466
                         const uint8_t produced[],
467
                         size_t produced_len,
468
                         const uint8_t expected[],
469
                         size_t expected_len);
470

471
            bool test_eq(const std::string& what,
131,306✔
472
                         std::span<const uint8_t> produced,
473
                         std::span<const uint8_t> expected) {
474
               return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
131,306✔
475
            }
476

477
            bool test_eq(const std::string& producer,
115,192✔
478
                         const std::string& what,
479
                         std::span<const uint8_t> produced,
480
                         std::span<const uint8_t> expected) {
481
               return test_eq(
115,192✔
482
                  producer.c_str(), what, produced.data(), produced.size(), expected.data(), expected.size());
115,192✔
483
            }
484

485
            bool test_eq(const std::string& what, std::span<const uint8_t> produced, const char* expected_hex);
486

487
            template <std::size_t N>
488
            bool test_eq(const std::string& what,
2,440✔
489
                         const std::array<uint8_t, N>& produced,
490
                         const std::array<uint8_t, N>& expected) {
491
               return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
2,440✔
492
            }
493

494
            bool test_ne(const std::string& what,
3,406✔
495
                         std::span<const uint8_t> produced,
496
                         std::span<const uint8_t> expected) {
497
               return test_ne(what, produced.data(), produced.size(), expected.data(), expected.size());
3,406✔
498
            }
499

500
         private:
501
            class ThrowExpectations {
502
               public:
503
                  explicit ThrowExpectations(std::function<void()> fn) : m_fn(std::move(fn)) {}
135,572✔
504

505
                  ThrowExpectations(const ThrowExpectations&) = delete;
506
                  ThrowExpectations& operator=(const ThrowExpectations&) = delete;
507
                  ThrowExpectations(ThrowExpectations&&) = default;
508
                  ThrowExpectations& operator=(ThrowExpectations&&) = default;
509

510
                  ~ThrowExpectations() { BOTAN_ASSERT_NOMSG(m_consumed); }
130,023✔
511

512
                  ThrowExpectations& expect_success() {
1,645✔
513
                     BOTAN_ASSERT_NOMSG(!m_expected_message && !m_expected_exception_check_fn);
1,645✔
514
                     m_expect_success = true;
1,645✔
515
                     return *this;
1,645✔
516
                  }
517

518
                  ThrowExpectations& expect_message(const std::string& message) {
189✔
519
                     BOTAN_ASSERT_NOMSG(!m_expect_success);
189✔
520
                     m_expected_message = message;
189✔
521
                     return *this;
189✔
522
                  }
523

524
                  template <typename ExT>
525
                  ThrowExpectations& expect_exception_type() {
62,048✔
526
                     BOTAN_ASSERT_NOMSG(!m_expect_success);
62,048✔
527
                     m_expected_exception_check_fn = [](const std::exception_ptr& e) {
124,096✔
528
                        try {
529
                           if(e) {
62,048✔
530
                              std::rethrow_exception(e);
124,096✔
531
                           }
532
                        } catch(const ExT&) {
62,048✔
533
                           return true;
534
                        } catch(...) {
2✔
535
                           return false;
536
                        }
537
                        return false;
538
                     };
539
                     return *this;
62,048✔
540
                  }
541

542
                  bool check(const std::string& test_name, Test::Result& result);
543

544
               private:
545
                  std::function<void()> m_fn;
546
                  std::optional<std::string> m_expected_message;
547
                  std::function<bool(std::exception_ptr)> m_expected_exception_check_fn;
548
                  bool m_expect_success = false;
549
                  bool m_consumed = false;
550
            };
551

552
         public:
553
            bool test_throws(const std::string& what, const std::function<void()>& fn);
554

555
            bool test_throws(const std::string& what, const std::string& expected, const std::function<void()>& fn);
556

557
            bool test_no_throw(const std::string& what, const std::function<void()>& fn);
558

559
            template <typename ExceptionT>
560
            bool test_throws(const std::string& what, const std::function<void()>& fn) {
62,033✔
561
               return ThrowExpectations(fn).expect_exception_type<ExceptionT>().check(what, *this);
124,066✔
562
            }
563

564
            template <typename ExceptionT>
565
            bool test_throws(const std::string& what, const std::string& expected, const std::function<void()>& fn) {
15✔
566
               return ThrowExpectations(fn).expect_exception_type<ExceptionT>().expect_message(expected).check(what,
30✔
567
                                                                                                               *this);
15✔
568
            }
569

570
            void set_ns_consumed(uint64_t ns) { m_ns_taken = ns; }
48,251✔
571

572
            void start_timer();
573
            void end_timer();
574

575
            void set_code_location(CodeLocation where) { m_where = where; }
50,692✔
576

577
            const std::optional<CodeLocation>& code_location() const { return m_where; }
53,208✔
578

579
         private:
580
            template <typename T>
581
            std::string to_string(const T& v) {
2✔
582
               if constexpr(detail::is_optional_v<T>) {
583
                  return (v.has_value()) ? to_string(v.value()) : std::string("std::nullopt");
×
584
               } else if constexpr(detail::has_Botan_to_string<T>) {
585
                  return Botan::to_string(v);
586
               } else if constexpr(detail::has_ostream_operator<T>) {
587
                  std::ostringstream oss;
2✔
588
                  oss << v;
2✔
589
                  return oss.str();
2✔
590
               } else if constexpr(detail::has_std_to_string<T>) {
2✔
591
                  return std::to_string(v);
2✔
592
               } else {
593
                  return "<?>";
×
594
               }
595
            }
596

597
         private:
598
            std::string m_who;
599
            std::optional<CodeLocation> m_where;
600
            uint64_t m_timestamp;
601
            uint64_t m_started = 0;
602
            uint64_t m_ns_taken = 0;
603
            size_t m_tests_passed = 0;
604
            std::vector<std::string> m_fail_log;
605
            std::vector<std::string> m_log;
606
      };
607

608
      virtual ~Test();
609

610
      Test();
611
      Test(const Test& other) = delete;
612
      Test(Test&& other) = default;
613
      Test& operator=(const Test& other) = delete;
614
      Test& operator=(Test&& other) = delete;
615

616
      virtual std::vector<Test::Result> run() = 0;
617

618
      virtual std::vector<std::string> possible_providers(const std::string& alg);
619

620
      void initialize(std::string test_name, CodeLocation location);
621

622
      const std::string& test_name() const { return m_test_name; }
23✔
623

624
      Botan::RandomNumberGenerator& rng() const;
625

626
      /**
627
       * Use this if a test needs some supported EC group but it is not relevant
628
       * which one exactly. This tries to find a commonly used group that is
629
       * both supported in this build and as small as possible (for test speed).
630
       *
631
       * If @p preferred_groups is non-empty, a group from that list is chosen
632
       *
633
       * @returns the name of a supported EC group, or std::nullopt if no
634
       *          supported EC group could be found for this build
635
       */
636
      static std::optional<std::string> supported_ec_group_name(std::vector<std::string> preferred_groups = {});
637

638
      const std::optional<CodeLocation>& registration_location() const { return m_registration_location; }
50,692✔
639

640
      /// @p smoke_test are run first in an unfiltered test run
641
      static void register_test(const std::string& category,
642
                                const std::string& name,
643
                                bool smoke_test,
644
                                bool needs_serialization,
645
                                std::function<std::unique_ptr<Test>()> maker_fn);
646

647
      static std::vector<std::string> registered_tests();
648
      static std::vector<std::string> registered_test_categories();
649

650
      static std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
651
                                                              const std::vector<std::string>& to_be_skipped);
652

653
      static std::unique_ptr<Test> get_test(const std::string& test_name);
654
      static bool test_needs_serialization(const std::string& test_name);
655

656
      static std::string data_dir(const std::string& subdir);
657
      static std::vector<std::string> files_in_data_dir(const std::string& subdir);
658
      static std::string data_file(const std::string& file);
659
      static std::string data_file_as_temporary_copy(const std::string& what);
660

661
      static std::string format_time(uint64_t nanoseconds);
662

663
      static std::vector<uint8_t> mutate_vec(const std::vector<uint8_t>& v,
664
                                             Botan::RandomNumberGenerator& rng,
665
                                             bool maybe_resize = false,
666
                                             size_t min_offset = 0);
667

668
      static void set_test_options(const Test_Options& opts);
669

670
      static void set_test_rng_seed(std::span<const uint8_t> seed, size_t epoch = 0);
671

672
      static const Test_Options& options() { return m_opts; }
673

674
      static bool run_long_tests() { return options().run_long_tests(); }
2,871✔
675

676
      static bool run_memory_intensive_tests() { return options().run_memory_intensive_tests(); }
1✔
677

678
      static const std::string& pkcs11_lib() { return options().pkcs11_lib(); }
50✔
679

680
      static std::string temp_file_name(const std::string& basename);
681
      static bool copy_file(const std::string& from, const std::string& to);
682

683
      static std::vector<std::string> provider_filter(const std::vector<std::string>& providers);
684

685
      static std::string read_data_file(const std::string& path);
686
      static std::vector<uint8_t> read_binary_data_file(const std::string& path);
687

688
      static std::unique_ptr<Botan::RandomNumberGenerator> new_rng(std::string_view test_name);
689
      static std::shared_ptr<Botan::RandomNumberGenerator> new_shared_rng(std::string_view test_name);
690

691
      static std::string random_password(Botan::RandomNumberGenerator& rng);
692
      static size_t random_index(Botan::RandomNumberGenerator& rng, size_t max);
693
      static uint64_t timestamp();  // nanoseconds arbitrary epoch
694

695
      static std::vector<Test::Result> flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists);
696

697
   private:
698
      static Test_Options m_opts;
699
      static std::string m_test_rng_seed;
700

701
      /// The string ID that was used to register this test
702
      std::string m_test_name;
703
      /// The source file location where the test was registered
704
      std::optional<CodeLocation> m_registration_location;
705
      /// The test-specific RNG state
706
      mutable std::unique_ptr<Botan::RandomNumberGenerator> m_test_rng;
707
};
708

709
/*
710
* Register the test with the runner
711
*/
712
template <typename Test_Class>
713
class TestClassRegistration {
714
   public:
715
      TestClassRegistration(const std::string& category,
385✔
716
                            const std::string& name,
717
                            bool smoke_test,
718
                            bool needs_serialization,
719
                            const CodeLocation& registration_location) {
720
         Test::register_test(category, name, smoke_test, needs_serialization, [=] {
1,878✔
721
            auto test = std::make_unique<Test_Class>();
385✔
722
            test->initialize(name, registration_location);
770✔
723
            return test;
385✔
724
         });
×
725
      }
385✔
726
};
727

728
// NOLINTBEGIN(*-macro-usage)
729

730
#define BOTAN_REGISTER_TEST(category, name, Test_Class) \
731
   /* NOLINTNEXTLINE(cert-err58-cpp) */                 \
732
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, false, {__FILE__, __LINE__})
733
#define BOTAN_REGISTER_SERIALIZED_TEST(category, name, Test_Class) \
734
   /* NOLINTNEXTLINE(cert-err58-cpp) */                            \
735
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, true, {__FILE__, __LINE__})
736
#define BOTAN_REGISTER_SMOKE_TEST(category, name, Test_Class) \
737
   /* NOLINTNEXTLINE(cert-err58-cpp) */                       \
738
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, false, {__FILE__, __LINE__})
739
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST(category, name, Test_Class) \
740
   /* NOLINTNEXTLINE(cert-err58-cpp) */                                  \
741
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, true, {__FILE__, __LINE__})
742

743
// NOLINTEND(*-macro-usage)
744

745
typedef Test::Result (*test_fn)();
746
typedef std::vector<Test::Result> (*test_fn_vec)();
747

748
class FnTest : public Test {
749
   private:
750
      using TestFnVariant = std::variant<test_fn, test_fn_vec>;
751

752
      template <typename TestFn>
753
      std::vector<TestFnVariant> make_variant_vector(TestFn fn) {
34✔
754
         using T = std::decay_t<decltype(fn)>;
755
         static_assert(std::is_same_v<T, test_fn> || std::is_same_v<T, test_fn_vec>,
756
                       "functions passed to BOTAN_REGISTER_TEST_FN must either return a "
757
                       "single Test::Result or a std::vector of Test::Result");
758
         return {fn};
34✔
759
      }
760

761
      template <typename TestFn, typename... TestFns>
762
      std::vector<TestFnVariant> make_variant_vector(const TestFn& fn, const TestFns&... fns) {
31✔
763
         auto functions = make_variant_vector(fns...);
31✔
764
         functions.emplace_back(fn);
31✔
765
         return functions;
31✔
766
      }
×
767

768
   public:
769
      template <typename... TestFns>
770
      explicit FnTest(TestFns... fns) : m_fns(make_variant_vector(fns...)) {}
34✔
771

772
      std::vector<Test::Result> run() override {
34✔
773
         std::vector<Test::Result> result;
34✔
774

775
         // TODO(Botan4) use std::ranges::reverse_view here once available (need newer Clang)
776
         // NOLINTNEXTLINE(modernize-loop-convert)
777
         for(auto fn_variant = m_fns.crbegin(); fn_variant != m_fns.crend(); ++fn_variant) {
99✔
778
            std::visit(
65✔
779
               [&](auto&& fn) {
130✔
780
                  using T = std::decay_t<decltype(fn)>;
781
                  if constexpr(std::is_same_v<T, test_fn>) {
782
                     result.emplace_back(fn());
7✔
783
                  } else {
784
                     const auto results = fn();
58✔
785
                     result.insert(result.end(), results.begin(), results.end());
58✔
786
                  }
58✔
787
               },
65✔
788
               *fn_variant);
65✔
789
         }
790

791
         return result;
34✔
792
      }
×
793

794
   private:
795
      std::vector<TestFnVariant> m_fns;
796
};
797

798
class TestFnRegistration {
799
   public:
800
      template <typename... TestFns>
801
      TestFnRegistration(const std::string& category,
34✔
802
                         const std::string& name,
803
                         bool smoke_test,
804
                         bool needs_serialization,
805
                         const CodeLocation& registration_location,
806
                         TestFns... fn) {
807
         Test::register_test(category, name, smoke_test, needs_serialization, [=] {
125✔
808
            auto test = std::make_unique<FnTest>(fn...);
34✔
809
            test->initialize(name, registration_location);
68✔
810
            return test;
34✔
811
         });
×
812
      }
34✔
813
};
814

815
// NOLINTBEGIN(*-macro-usage)
816

817
#define BOTAN_REGISTER_TEST_FN_IMPL(category, name, smoke_test, needs_serialization, fn0, ...) \
818
   /* NOLINTNEXTLINE(cert-err58-cpp) */                                                        \
819
   static const TestFnRegistration register_##fn0(                                             \
820
      category, name, smoke_test, needs_serialization, {__FILE__, __LINE__}, fn0 __VA_OPT__(, ) __VA_ARGS__)
821

822
#define BOTAN_REGISTER_TEST_FN(category, name, ...) \
823
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, false, false, __VA_ARGS__)
824
#define BOTAN_REGISTER_SMOKE_TEST_FN(category, name, ...) \
825
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, true, false, __VA_ARGS__)
826
#define BOTAN_REGISTER_SERIALIZED_TEST_FN(category, name, ...) \
827
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, false, true, __VA_ARGS__)
828
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST_FN(category, name, ...) \
829
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, true, true, __VA_ARGS__)
830

831
// NOLINTEND(*-macro-usage)
832

833
class VarMap {
181✔
834
   public:
835
      bool has_key(const std::string& key) const;
836

837
      bool get_req_bool(const std::string& key) const;
838

839
      std::vector<uint8_t> get_req_bin(const std::string& key) const;
840
      std::vector<uint8_t> get_opt_bin(const std::string& key) const;
841

842
      std::vector<std::vector<uint8_t>> get_req_bin_list(const std::string& key) const;
843

844
#if defined(BOTAN_HAS_BIGINT)
845
      Botan::BigInt get_req_bn(const std::string& key) const;
846
      Botan::BigInt get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const;
847
#endif
848

849
      std::string get_req_str(const std::string& key) const;
850
      std::string get_opt_str(const std::string& key, const std::string& def_value) const;
851

852
      size_t get_req_sz(const std::string& key) const;
853

854
      uint8_t get_req_u8(const std::string& key) const;
855
      uint32_t get_req_u32(const std::string& key) const;
856
      uint64_t get_req_u64(const std::string& key) const;
857

858
      size_t get_opt_sz(const std::string& key, size_t def_value) const;
859

860
      uint64_t get_opt_u64(const std::string& key, uint64_t def_value) const;
861

862
      void clear();
863

864
      void add(const std::string& key, const std::string& value);
865

866
   private:
867
      std::optional<std::string> get_var(const std::string& key) const;
868

869
      std::vector<std::pair<std::string, std::string>> m_vars;
870
};
871

872
/*
873
* A test based on reading an input file which contains key/value pairs
874
* Special note: the last value in required_key (there must be at least
875
* one), is the output key. This triggers the callback.
876
*
877
* Calls run_one_test with the variables set. If an ini-style [header]
878
* is used in the file, then header will be set to that value. This allows
879
* splitting up tests between [valid] and [invalid] tests, or different
880
* related algorithms tested in the same file. Use the get_XXX functions
881
* on VarMap to retrieve formatted values.
882
*
883
* If most of your tests are text-based but you find yourself with a few
884
* odds-and-ends tests that you want to do, override run_final_tests which
885
* can test whatever it likes and returns a vector of Results.
886
*/
887
class Text_Based_Test : public Test {
888
   public:
889
      Text_Based_Test(const std::string& data_src,
890
                      const std::string& required_keys_str,
891
                      const std::string& optional_keys_str = "");
892

893
      Text_Based_Test(const Text_Based_Test& other) = delete;
894
      Text_Based_Test(Text_Based_Test&& other) = default;
895
      Text_Based_Test& operator=(const Text_Based_Test& other) = delete;
896
      Text_Based_Test& operator=(Text_Based_Test&& other) = delete;
897

898
      ~Text_Based_Test() override;
899

900
      virtual bool clear_between_callbacks() const { return true; }
33,476✔
901

902
      std::vector<Test::Result> run() override;
903

904
   private:
905
      virtual Test::Result run_one_test(const std::string& header, const VarMap& vars) = 0;
906
      // Called before run_one_test
907
      virtual bool skip_this_test(const std::string& header, const VarMap& vars);
908

909
      virtual std::vector<Test::Result> run_final_tests() { return std::vector<Test::Result>(); }
172✔
910

911
   private:
912
      class Text_Based_Test_Data;
913
      std::unique_ptr<Text_Based_Test_Data> m_data;
914
};
915

916
/**
917
 * This is a convenience wrapper to write small self-contained and in particular
918
 * exception-safe unit tests. If some (unexpected) exception is thrown in one of
919
 * the CHECK-scopes, it will fail the particular test gracefully with a human-
920
 * understandable failure output.
921
 *
922
 * Example Usage:
923
 *
924
 * ```
925
 * std::vector<Test::Result> test_something()
926
 *    {
927
 *    return
928
 *       {
929
 *       CHECK("some unit test name", [](Test::Result& r)
930
 *          {
931
 *          r.confirm("some observation", 1+1 == 2);
932
 *          }),
933
 *       CHECK("some other unit test name", [](Test::Result& r)
934
 *          {
935
 *          // ...
936
 *          })
937
 *       };
938
 *    }
939
 *
940
 * BOTAN_REGISTER_TEST_FN("some_category", "some_test_name", test_something);
941
 * ```
942
 */
943
template <typename FunT>
944
Test::Result CHECK(const char* name, FunT check_fun) {
508✔
945
   Botan_Tests::Test::Result r(name);
585✔
946

947
   try {
948
      check_fun(r);
508✔
949
   } catch(const Botan_Tests::Test_Aborted&) {
×
950
      // pass, failure was already noted in the responsible `require`
951
   } catch(const std::exception& ex) {
×
952
      r.test_failure("failed unexpectedly", ex.what());
×
953
   } catch(...) {
×
954
      r.test_failure("failed with unknown exception");
×
955
   }
956

957
   return r;
508✔
958
}
×
959

960
}  // namespace Botan_Tests
961

962
#endif
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