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

randombit / botan / 22034777194

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

Pull #5338

github

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

102267 of 113631 relevant lines covered (90.0%)

11490211.35 hits per line

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

86.9
/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/types.h>
18
#include <functional>
19
#include <iosfwd>
20
#include <memory>
21
#include <optional>
22
#include <span>
23
#include <sstream>
24
#include <stdexcept>
25
#include <string>
26
#include <variant>
27
#include <vector>
28

29
namespace Botan {
30

31
class RandomNumberGenerator;
32

33
#if defined(BOTAN_HAS_BIGINT)
34
class BigInt;
35
#endif
36

37
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
38
class EC_Point;
39
#endif
40

41
}  // namespace Botan
42

43
namespace Botan_Tests {
44

45
#if defined(BOTAN_HAS_BIGINT)
46
using Botan::BigInt;
47
#endif
48

49
class Test_Error : public std::runtime_error {
50
   public:
51
      explicit Test_Error(std::string_view what);
52
};
53

54
class Test_Aborted final : public Test_Error {
55
   public:
56
      explicit Test_Aborted(std::string_view what) : Test_Error(what) {}
×
57
};
58

59
class Test_Options {
60
   public:
61
      Test_Options() = default;
62

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

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

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

112
      const std::string& data_dir() const { return m_data_dir; }
113

114
      const std::string& pkcs11_lib() const { return m_pkcs11_lib; }
3✔
115

116
      const std::string& provider() const { return m_provider; }
2✔
117

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

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

122
      uint32_t tpm2_persistent_rsa_handle() const { return static_cast<uint32_t>(m_tpm2_persistent_rsa_handle); }
2✔
123

124
      uint32_t tpm2_persistent_ecc_handle() const { return static_cast<uint32_t>(m_tpm2_persistent_ecc_handle); }
2✔
125

126
      const std::string& tpm2_persistent_auth_value() const { return m_tpm2_persistent_auth_value; }
127

128
      const std::string& drbg_seed() const { return m_drbg_seed; }
1✔
129

130
      const std::string& xml_results_dir() const { return m_xml_results_dir; }
1✔
131

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

134
      size_t test_runs() const { return m_test_runs; }
4✔
135

136
      size_t test_threads() const { return m_test_threads; }
3✔
137

138
      bool log_success() const { return m_log_success; }
3,620,290✔
139

140
      bool run_online_tests() const { return m_run_online_tests; }
2✔
141

142
      bool run_long_tests() const { return m_run_long_tests; }
2,871✔
143

144
      bool run_memory_intensive_tests() const { return m_run_memory_intensive_tests; }
1✔
145

146
      bool abort_on_first_fail() const { return m_abort_on_first_fail; }
25✔
147

148
      bool no_stdout() const { return m_no_stdout; }
1✔
149

150
      bool verbose() const { return m_verbose; }
2,542✔
151

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

177
namespace detail {
178

179
template <typename, typename = void>
180
constexpr bool has_std_to_string = false;
181
template <typename T>
182
constexpr bool has_std_to_string<T, std::void_t<decltype(std::to_string(std::declval<T>()))>> = true;
183

184
template <typename, typename = void>
185
constexpr bool has_ostream_operator = false;
186
template <typename T>
187
constexpr bool
188
   has_ostream_operator<T, std::void_t<decltype(operator<<(std::declval<std::ostringstream&>(), std::declval<T>()))>> =
189
      true;
190

191
template <typename T>
192
struct is_optional : std::false_type {};
193

194
template <typename T>
195
struct is_optional<std::optional<T>> : std::true_type {};
196

197
template <typename T>
198
constexpr bool is_optional_v = is_optional<T>::value;
199

200
}  // namespace detail
201

202
/**
203
 * A code location consisting of the source file path and a line
204
 */
205
struct CodeLocation {
206
      const char* path;
207
      unsigned int line;
208
};
209

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

226
            /**
227
             * This 'consolidation constructor' creates a single test result from
228
             * a vector of downstream test result objects.
229
             */
230
            Result(std::string_view who, const std::vector<Result>& downstream_results);
231

232
            size_t tests_passed() const { return m_tests_passed; }
12,590✔
233

234
            size_t tests_failed() const { return m_fail_log.size(); }
68,938✔
235

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

238
            bool any_results() const { return tests_run() > 0; }
239

240
            const std::string& who() const { return m_who; }
235,974✔
241

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

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

246
            std::optional<uint64_t> elapsed_time() const {
2,516✔
247
               if(m_ns_taken == 0) {
2,516✔
248
                  return std::nullopt;
249
               } else {
250
                  return m_ns_taken;
1,473✔
251
               }
252
            }
253

254
            // Nanoseconds since epoch
255
            uint64_t timestamp() const { return m_timestamp; }
2,516✔
256

257
            std::string result_string() const;
258

259
            static Result Failure(std::string_view who, std::string_view what) {
1✔
260
               Result r(who);
1✔
261
               r.test_failure(what);
1✔
262
               return r;
1✔
263
            }
×
264

265
            static Result Note(std::string_view who, std::string_view what) {
×
266
               Result r(who);
×
267
               r.test_note(what);
×
268
               return r;
×
269
            }
×
270

271
            void merge(const Result& other, bool ignore_test_name = false);
272

273
            /* Test reporting functions */
274

275
            void test_note(std::string_view note, const char* extra = nullptr);
276

277
            void test_note(std::string_view note, std::span<const uint8_t> context);
278

279
            void note_missing(std::string_view whatever);
280

281
            bool test_success(std::string_view note = "");
282

283
            bool test_failure(std::string err);
284

285
            bool test_failure(std::string_view err);
286

287
            bool test_failure(const char* err);
288

289
            bool test_failure(std::string_view what, std::string_view error);
290

291
            void test_failure(std::string_view what, const uint8_t buf[], size_t buf_len);
292

293
            void test_failure(std::string_view what, std::span<const uint8_t> context);
294

295
            /**
296
             * Require a condition, throw Test_Aborted otherwise
297
             * Note: works best when combined with CHECK scopes!
298
             */
299
            void require(std::string_view what, bool expr, bool expected = true);
300

301
            /* Generic arbitrary equality check */
302

303
            template <typename T>
304
            bool test_is_eq(const T& produced, const T& expected) {
42✔
305
               return test_is_eq("comparison", produced, expected);
39✔
306
            }
307

308
            template <typename T>
309
            bool test_is_eq(std::string_view what, const T& produced, const T& expected) {
334,174✔
310
               std::ostringstream out;
334,174✔
311
               out << m_who << " " << what;
334,174✔
312

313
               if(produced == expected) {
257,346✔
314
                  out << " produced expected result";
334,173✔
315
                  return test_success(out.str());
334,173✔
316
               } else {
317
                  out << " produced unexpected result '" << to_string(produced) << "' expected '" << to_string(expected)
318
                      << "'";
4✔
319
                  return test_failure(out.str());
1✔
320
               }
321
            }
334,174✔
322

323
            template <typename T>
324
            bool test_not_null(std::string_view what, const T& ptr) {
1,736✔
325
               if(ptr == nullptr) {
1,736✔
326
                  return test_failure(what, "was null");
×
327
               } else {
328
                  return test_success("not null");
1,736✔
329
               }
330
            }
331

332
            /* String comparison predicates */
333
            bool test_str_not_empty(std::string_view what, std::string_view produced);
334

335
            bool test_str_eq(std::string_view what, std::string_view produced, std::string_view expected);
336

337
            bool test_str_ne(std::string_view what, std::string_view produced, std::string_view expected);
338

339
            /* Test predicates on bool */
340
            bool test_bool_eq(std::string_view what, bool produced, bool expected);
341

342
            bool test_is_false(std::string_view what, bool produced);
343

344
            bool test_is_true(std::string_view what, bool produced);
345

346
            /* Test predicates on size_t */
347
            bool test_sz_eq(std::string_view what, size_t produced, size_t expected);
348
            bool test_sz_ne(std::string_view what, size_t produced, size_t expected);
349
            bool test_sz_lt(std::string_view what, size_t produced, size_t expected);
350
            bool test_sz_lte(std::string_view what, size_t produced, size_t expected);
351
            bool test_sz_gt(std::string_view what, size_t produced, size_t expected);
352
            bool test_sz_gte(std::string_view what, size_t produced, size_t expected);
353

354
            /* Type-hinted unsigned integer equality predicates */
355
            bool test_u8_eq(uint8_t produced, uint8_t expected);
356
            bool test_u8_eq(std::string_view what, uint8_t produced, uint8_t expected);
357

358
            bool test_u16_eq(uint16_t produced, uint16_t expected);
359
            bool test_u16_eq(std::string_view what, uint16_t produced, uint16_t expected);
360

361
            bool test_u32_eq(uint32_t produced, uint32_t expected);
362
            bool test_u32_eq(std::string_view what, uint32_t produced, uint32_t expected);
363

364
            bool test_u64_eq(uint64_t produced, uint64_t expected);
365
            bool test_u64_eq(std::string_view what, uint64_t produced, uint64_t expected);
366

367
            /* Test predicates on integer return codes */
368
            bool test_rc_ok(std::string_view func, int rc);
369
            bool test_rc_fail(std::string_view func, std::string_view why, int rc);
370
            bool test_rc(std::string_view func, int expected, int rc);
371
            bool test_rc_init(std::string_view func, int rc);
372

373
            /* Test predicates on optional values */
374

375
            template <typename T>
376
            bool test_opt_not_null(std::string_view what, const std::optional<T>& val) {
10✔
377
               if(val == std::nullopt) {
10✔
378
                  return test_failure(what, "was nullopt");
×
379
               } else {
380
                  return test_success("not nullopt");
10✔
381
               }
382
            }
383

384
            bool test_opt_u8_eq(std::string_view what, std::optional<uint8_t> a, std::optional<uint8_t> b);
385

386
#if defined(BOTAN_HAS_BIGINT)
387
            bool test_eq(std::string_view what, const BigInt& produced, const BigInt& expected);
388
            bool test_ne(std::string_view what, const BigInt& produced, const BigInt& expected);
389
#endif
390

391
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
392
            bool test_eq(std::string_view what, const Botan::EC_Point& a, const Botan::EC_Point& b);
393
#endif
394

395
            bool test_eq(const char* producer,
396
                         std::string_view what,
397
                         const uint8_t produced[],
398
                         size_t produced_size,
399
                         const uint8_t expected[],
400
                         size_t expected_size);
401

402
            bool test_ne(std::string_view what,
403
                         const uint8_t produced[],
404
                         size_t produced_len,
405
                         const uint8_t expected[],
406
                         size_t expected_len);
407

408
            bool test_eq(std::string_view what, std::span<const uint8_t> produced, std::span<const uint8_t> expected) {
131,395✔
409
               return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
131,264✔
410
            }
411

412
            bool test_eq(std::string_view producer,
115,198✔
413
                         std::string_view what,
414
                         std::span<const uint8_t> produced,
415
                         std::span<const uint8_t> expected) {
416
               return test_eq(std::string(producer).c_str(),
115,198✔
417
                              what,
418
                              produced.data(),
419
                              produced.size(),
420
                              expected.data(),
421
                              expected.size());
115,198✔
422
            }
230,396✔
423

424
            bool test_eq(std::string_view what, std::span<const uint8_t> produced, const char* expected_hex);
425

426
            template <std::size_t N>
427
            bool test_eq(std::string_view what,
2,440✔
428
                         const std::array<uint8_t, N>& produced,
429
                         const std::array<uint8_t, N>& expected) {
430
               return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
1,163✔
431
            }
432

433
            bool test_ne(std::string_view what, std::span<const uint8_t> produced, std::span<const uint8_t> expected) {
3,409✔
434
               return test_ne(what, produced.data(), produced.size(), expected.data(), expected.size());
3,409✔
435
            }
436

437
         private:
438
            class ThrowExpectations {
439
               public:
440
                  explicit ThrowExpectations(std::function<void()> fn) : m_fn(std::move(fn)) {}
73,518✔
441

442
                  ThrowExpectations(const ThrowExpectations&) = delete;
443
                  ThrowExpectations& operator=(const ThrowExpectations&) = delete;
444
                  ThrowExpectations(ThrowExpectations&&) = default;
445
                  ThrowExpectations& operator=(ThrowExpectations&&) = default;
446

447
                  ~ThrowExpectations();
448

449
                  ThrowExpectations& expect_success();
450

451
                  ThrowExpectations& expect_message(std::string_view message);
452

453
                  template <typename ExT>
454
                  ThrowExpectations& expect_exception_type() {
62,048✔
455
                     assert_that_success_is_not_expected();
62,048✔
456

457
                     m_expected_exception_check_fn = [](const std::exception_ptr& e) {
124,096✔
458
                        try {
459
                           if(e) {
62,048✔
460
                              std::rethrow_exception(e);
124,096✔
461
                           }
462
                        } catch(const ExT&) {
62,048✔
463
                           return true;
464
                        } catch(...) {
2✔
465
                           return false;
466
                        }
467
                        return false;
468
                     };
469
                     return *this;
470
                  }
471

472
                  bool check(std::string_view test_name, Test::Result& result);
473

474
               private:
475
                  void assert_that_success_is_not_expected() const;
476

477
                  std::function<void()> m_fn;
478
                  std::optional<std::string> m_expected_message;
479
                  std::function<bool(std::exception_ptr)> m_expected_exception_check_fn;
480
                  bool m_expect_success = false;
481
                  bool m_consumed = false;
482
            };
483

484
         public:
485
            bool test_throws(std::string_view what, std::function<void()> fn);
486

487
            bool test_throws(std::string_view what, std::string_view expected, std::function<void()> fn);
488

489
            bool test_no_throw(std::string_view what, std::function<void()> fn);
490

491
            template <typename ExceptionT>
492
            bool test_throws(std::string_view what, std::function<void()> fn) {
62,033✔
493
               return ThrowExpectations(std::move(fn)).expect_exception_type<ExceptionT>().check(what, *this);
186,099✔
494
            }
495

496
            template <typename ExceptionT>
497
            bool test_throws(std::string_view what, std::string_view expected, std::function<void()> fn) {
15✔
498
               // clang-format off
499
               return ThrowExpectations(std::move(fn)).expect_exception_type<ExceptionT>().expect_message(expected).check(what, *this);
45✔
500
               // clang-format on
501
            }
502

503
            void set_ns_consumed(uint64_t ns) { m_ns_taken = ns; }
48,254✔
504

505
            void start_timer();
506
            void end_timer();
507

508
            void set_code_location(CodeLocation where) { m_where = where; }
50,695✔
509

510
            const std::optional<CodeLocation>& code_location() const { return m_where; }
53,211✔
511

512
         private:
513
            template <typename T>
514
            std::string to_string(const T& v) {
2✔
515
               if constexpr(detail::is_optional_v<T>) {
516
                  return (v.has_value()) ? to_string(v.value()) : std::string("std::nullopt");
×
517
               } else if constexpr(detail::has_ostream_operator<T>) {
518
                  std::ostringstream oss;
2✔
519
                  oss << v;
2✔
520
                  return oss.str();
2✔
521
               } else if constexpr(detail::has_std_to_string<T>) {
2✔
522
                  //static_assert(false, "no std::to_string for you");
523
                  return std::to_string(v);
×
524
               } else {
525
                  //static_assert(false, "unknown type");
526
                  return "<?>";
×
527
               }
528
            }
529

530
         private:
531
            std::string m_who;
532
            std::optional<CodeLocation> m_where;
533
            uint64_t m_timestamp;
534
            uint64_t m_started = 0;
535
            uint64_t m_ns_taken = 0;
536
            size_t m_tests_passed = 0;
537
            std::vector<std::string> m_fail_log;
538
            std::vector<std::string> m_log;
539
      };
540

541
      virtual ~Test();
542

543
      Test();
544
      Test(const Test& other) = delete;
545
      Test(Test&& other) = default;
546
      Test& operator=(const Test& other) = delete;
547
      Test& operator=(Test&& other) = delete;
548

549
      virtual std::vector<Test::Result> run() = 0;
550

551
      virtual std::vector<std::string> possible_providers(const std::string& alg);
552

553
      void initialize(std::string test_name, CodeLocation location);
554

555
      const std::string& test_name() const { return m_test_name; }
23✔
556

557
      Botan::RandomNumberGenerator& rng() const;
558

559
      /**
560
       * Use this if a test needs some supported EC group but it is not relevant
561
       * which one exactly. This tries to find a commonly used group that is
562
       * both supported in this build and as small as possible (for test speed).
563
       *
564
       * If @p preferred_groups is non-empty, a group from that list is chosen
565
       *
566
       * @returns the name of a supported EC group, or std::nullopt if no
567
       *          supported EC group could be found for this build
568
       */
569
      static std::optional<std::string> supported_ec_group_name(std::vector<std::string> preferred_groups = {});
570

571
      const std::optional<CodeLocation>& registration_location() const { return m_registration_location; }
50,695✔
572

573
      /// @p smoke_test are run first in an unfiltered test run
574
      static void register_test(const std::string& category,
575
                                const std::string& name,
576
                                bool smoke_test,
577
                                bool needs_serialization,
578
                                std::function<std::unique_ptr<Test>()> maker_fn);
579

580
      static std::vector<std::string> registered_tests();
581
      static std::vector<std::string> registered_test_categories();
582

583
      static std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
584
                                                              const std::vector<std::string>& to_be_skipped);
585

586
      static std::unique_ptr<Test> get_test(const std::string& test_name);
587
      static bool test_needs_serialization(const std::string& test_name);
588

589
      static std::string data_dir(const std::string& subdir);
590
      static std::vector<std::string> files_in_data_dir(const std::string& subdir);
591
      static std::string data_file(const std::string& file);
592
      static std::string data_file_as_temporary_copy(const std::string& what);
593

594
      static std::string format_time(uint64_t nanoseconds);
595

596
      static std::vector<uint8_t> mutate_vec(const std::vector<uint8_t>& v,
597
                                             Botan::RandomNumberGenerator& rng,
598
                                             bool maybe_resize = false,
599
                                             size_t min_offset = 0);
600

601
      static void set_test_options(const Test_Options& opts);
602

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

605
      static const Test_Options& options() { return m_opts; }
606

607
      static bool run_long_tests() { return options().run_long_tests(); }
2,871✔
608

609
      static bool run_memory_intensive_tests() { return options().run_memory_intensive_tests(); }
1✔
610

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

613
      static std::string temp_file_name(const std::string& basename);
614
      static bool copy_file(const std::string& from, const std::string& to);
615

616
      static std::vector<std::string> provider_filter(const std::vector<std::string>& providers);
617

618
      static std::string read_data_file(const std::string& path);
619
      static std::vector<uint8_t> read_binary_data_file(const std::string& path);
620

621
      static std::unique_ptr<Botan::RandomNumberGenerator> new_rng(std::string_view test_name);
622
      static std::shared_ptr<Botan::RandomNumberGenerator> new_shared_rng(std::string_view test_name);
623

624
      static std::string random_password(Botan::RandomNumberGenerator& rng);
625
      static size_t random_index(Botan::RandomNumberGenerator& rng, size_t max);
626
      static uint64_t timestamp();  // nanoseconds arbitrary epoch
627

628
      static std::vector<Test::Result> flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists);
629

630
   private:
631
      static Test_Options m_opts;
632
      static std::string m_test_rng_seed;
633

634
      /// The string ID that was used to register this test
635
      std::string m_test_name;
636
      /// The source file location where the test was registered
637
      std::optional<CodeLocation> m_registration_location;
638
      /// The test-specific RNG state
639
      mutable std::unique_ptr<Botan::RandomNumberGenerator> m_test_rng;
640
};
641

642
/*
643
* Register the test with the runner
644
*/
645
template <typename Test_Class>
646
class TestClassRegistration {
647
   public:
648
      TestClassRegistration(const std::string& category,
385✔
649
                            const std::string& name,
650
                            bool smoke_test,
651
                            bool needs_serialization,
652
                            const CodeLocation& registration_location) {
653
         Test::register_test(category, name, smoke_test, needs_serialization, [=] {
1,878✔
654
            auto test = std::make_unique<Test_Class>();
385✔
655
            test->initialize(name, registration_location);
770✔
656
            return test;
385✔
657
         });
×
658
      }
385✔
659
};
660

661
// NOLINTBEGIN(*-macro-usage)
662

663
#define BOTAN_REGISTER_TEST(category, name, Test_Class) \
664
   /* NOLINTNEXTLINE(cert-err58-cpp) */                 \
665
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, false, {__FILE__, __LINE__})
666
#define BOTAN_REGISTER_SERIALIZED_TEST(category, name, Test_Class) \
667
   /* NOLINTNEXTLINE(cert-err58-cpp) */                            \
668
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, true, {__FILE__, __LINE__})
669
#define BOTAN_REGISTER_SMOKE_TEST(category, name, Test_Class) \
670
   /* NOLINTNEXTLINE(cert-err58-cpp) */                       \
671
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, false, {__FILE__, __LINE__})
672
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST(category, name, Test_Class) \
673
   /* NOLINTNEXTLINE(cert-err58-cpp) */                                  \
674
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, true, {__FILE__, __LINE__})
675

676
// NOLINTEND(*-macro-usage)
677

678
typedef Test::Result (*test_fn)();
679
typedef std::vector<Test::Result> (*test_fn_vec)();
680

681
class FnTest : public Test {
682
   private:
683
      using TestFnVariant = std::variant<test_fn, test_fn_vec>;
684

685
      template <typename TestFn>
686
      std::vector<TestFnVariant> make_variant_vector(TestFn fn) {
34✔
687
         using T = std::decay_t<decltype(fn)>;
688
         static_assert(std::is_same_v<T, test_fn> || std::is_same_v<T, test_fn_vec>,
689
                       "functions passed to BOTAN_REGISTER_TEST_FN must either return a "
690
                       "single Test::Result or a std::vector of Test::Result");
691
         return {fn};
34✔
692
      }
693

694
      template <typename TestFn, typename... TestFns>
695
      std::vector<TestFnVariant> make_variant_vector(const TestFn& fn, const TestFns&... fns) {
31✔
696
         auto functions = make_variant_vector(fns...);
31✔
697
         functions.emplace_back(fn);
31✔
698
         return functions;
31✔
699
      }
×
700

701
   public:
702
      template <typename... TestFns>
703
      explicit FnTest(TestFns... fns) : m_fns(make_variant_vector(fns...)) {}
34✔
704

705
      std::vector<Test::Result> run() override {
34✔
706
         std::vector<Test::Result> result;
34✔
707

708
         // TODO(Botan4) use std::ranges::reverse_view here once available (need newer Clang)
709
         // NOLINTNEXTLINE(modernize-loop-convert)
710
         for(auto fn_variant = m_fns.crbegin(); fn_variant != m_fns.crend(); ++fn_variant) {
99✔
711
            std::visit(
65✔
712
               [&](auto&& fn) {
130✔
713
                  using T = std::decay_t<decltype(fn)>;
714
                  if constexpr(std::is_same_v<T, test_fn>) {
715
                     result.emplace_back(fn());
7✔
716
                  } else {
717
                     const auto results = fn();
58✔
718
                     result.insert(result.end(), results.begin(), results.end());
58✔
719
                  }
58✔
720
               },
65✔
721
               *fn_variant);
65✔
722
         }
723

724
         return result;
34✔
725
      }
×
726

727
   private:
728
      std::vector<TestFnVariant> m_fns;
729
};
730

731
class TestFnRegistration {
732
   public:
733
      template <typename... TestFns>
734
      TestFnRegistration(const std::string& category,
34✔
735
                         const std::string& name,
736
                         bool smoke_test,
737
                         bool needs_serialization,
738
                         const CodeLocation& registration_location,
739
                         TestFns... fn) {
740
         Test::register_test(category, name, smoke_test, needs_serialization, [=] {
125✔
741
            auto test = std::make_unique<FnTest>(fn...);
34✔
742
            test->initialize(name, registration_location);
68✔
743
            return test;
34✔
744
         });
×
745
      }
34✔
746
};
747

748
// NOLINTBEGIN(*-macro-usage)
749

750
#define BOTAN_REGISTER_TEST_FN_IMPL(category, name, smoke_test, needs_serialization, fn0, ...) \
751
   /* NOLINTNEXTLINE(cert-err58-cpp) */                                                        \
752
   static const TestFnRegistration register_##fn0(                                             \
753
      category, name, smoke_test, needs_serialization, {__FILE__, __LINE__}, fn0 __VA_OPT__(, ) __VA_ARGS__)
754

755
#define BOTAN_REGISTER_TEST_FN(category, name, ...) \
756
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, false, false, __VA_ARGS__)
757
#define BOTAN_REGISTER_SMOKE_TEST_FN(category, name, ...) \
758
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, true, false, __VA_ARGS__)
759
#define BOTAN_REGISTER_SERIALIZED_TEST_FN(category, name, ...) \
760
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, false, true, __VA_ARGS__)
761
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST_FN(category, name, ...) \
762
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, true, true, __VA_ARGS__)
763

764
// NOLINTEND(*-macro-usage)
765

766
class VarMap {
181✔
767
   public:
768
      bool has_key(const std::string& key) const;
769

770
      bool get_req_bool(const std::string& key) const;
771

772
      std::vector<uint8_t> get_req_bin(const std::string& key) const;
773
      std::vector<uint8_t> get_opt_bin(const std::string& key) const;
774

775
      std::vector<std::vector<uint8_t>> get_req_bin_list(const std::string& key) const;
776

777
#if defined(BOTAN_HAS_BIGINT)
778
      Botan::BigInt get_req_bn(const std::string& key) const;
779
      Botan::BigInt get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const;
780
#endif
781

782
      std::string get_req_str(const std::string& key) const;
783
      std::string get_opt_str(const std::string& key, const std::string& def_value) const;
784

785
      size_t get_req_sz(const std::string& key) const;
786

787
      uint8_t get_req_u8(const std::string& key) const;
788
      uint32_t get_req_u32(const std::string& key) const;
789
      uint64_t get_req_u64(const std::string& key) const;
790

791
      size_t get_opt_sz(const std::string& key, size_t def_value) const;
792

793
      uint64_t get_opt_u64(const std::string& key, uint64_t def_value) const;
794

795
      void clear();
796

797
      void add(const std::string& key, const std::string& value);
798

799
   private:
800
      std::optional<std::string> get_var(const std::string& key) const;
801

802
      std::vector<std::pair<std::string, std::string>> m_vars;
803
};
804

805
/*
806
* A test based on reading an input file which contains key/value pairs
807
* Special note: the last value in required_key (there must be at least
808
* one), is the output key. This triggers the callback.
809
*
810
* Calls run_one_test with the variables set. If an ini-style [header]
811
* is used in the file, then header will be set to that value. This allows
812
* splitting up tests between [valid] and [invalid] tests, or different
813
* related algorithms tested in the same file. Use the get_XXX functions
814
* on VarMap to retrieve formatted values.
815
*
816
* If most of your tests are text-based but you find yourself with a few
817
* odds-and-ends tests that you want to do, override run_final_tests which
818
* can test whatever it likes and returns a vector of Results.
819
*/
820
class Text_Based_Test : public Test {
821
   public:
822
      Text_Based_Test(const std::string& data_src,
823
                      const std::string& required_keys_str,
824
                      const std::string& optional_keys_str = "");
825

826
      Text_Based_Test(const Text_Based_Test& other) = delete;
827
      Text_Based_Test(Text_Based_Test&& other) = default;
828
      Text_Based_Test& operator=(const Text_Based_Test& other) = delete;
829
      Text_Based_Test& operator=(Text_Based_Test&& other) = delete;
830

831
      ~Text_Based_Test() override;
832

833
      virtual bool clear_between_callbacks() const { return true; }
33,479✔
834

835
      std::vector<Test::Result> run() override;
836

837
   private:
838
      virtual Test::Result run_one_test(const std::string& header, const VarMap& vars) = 0;
839
      // Called before run_one_test
840
      virtual bool skip_this_test(const std::string& header, const VarMap& vars);
841

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

844
   private:
845
      class Text_Based_Test_Data;
846
      std::unique_ptr<Text_Based_Test_Data> m_data;
847
};
848

849
/**
850
 * This is a convenience wrapper to write small self-contained and in particular
851
 * exception-safe unit tests. If some (unexpected) exception is thrown in one of
852
 * the CHECK-scopes, it will fail the particular test gracefully with a human-
853
 * understandable failure output.
854
 *
855
 * Example Usage:
856
 *
857
 * ```
858
 * std::vector<Test::Result> test_something()
859
 *    {
860
 *    return
861
 *       {
862
 *       CHECK("some unit test name", [](Test::Result& r)
863
 *          {
864
 *          r.test_is_true("some observation", 1+1 == 2);
865
 *          }),
866
 *       CHECK("some other unit test name", [](Test::Result& r)
867
 *          {
868
 *          // ...
869
 *          })
870
 *       };
871
 *    }
872
 *
873
 * BOTAN_REGISTER_TEST_FN("some_category", "some_test_name", test_something);
874
 * ```
875
 */
876
template <typename FunT>
877
Test::Result CHECK(const char* name, FunT check_fun) {
508✔
878
   Botan_Tests::Test::Result r(name);
508✔
879

880
   try {
881
      check_fun(r);
508✔
882
   } catch(const Botan_Tests::Test_Aborted&) {
×
883
      // pass, failure was already noted in the responsible `require`
884
   } catch(const std::exception& ex) {
×
885
      r.test_failure("failed unexpectedly", ex.what());
×
886
   } catch(...) {
×
887
      r.test_failure("failed with unknown exception");
×
888
   }
889

890
   return r;
507✔
891
}
×
892

893
}  // namespace Botan_Tests
894

895
#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