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

randombit / botan / 22038388571

15 Feb 2026 03:39PM UTC coverage: 90.056% (-0.003%) from 90.059%
22038388571

Pull #5341

github

web-flow
Merge e5a537aa4 into 76dfe61e9
Pull Request #5341: Cleanup test predicates on binary strings

102343 of 113644 relevant lines covered (90.06%)

11670901.95 hits per line

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

82.82
/src/tests/tests.h
1
/*
2
* (C) 2014,2015,2026 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
}  // namespace Botan
38

39
namespace Botan_Tests {
40

41
#if defined(BOTAN_HAS_BIGINT)
42
using Botan::BigInt;
43
#endif
44

45
class Test_Error : public std::runtime_error {
46
   public:
47
      explicit Test_Error(std::string_view what);
48
};
49

50
class Test_Aborted final : public Test_Error {
51
   public:
52
      explicit Test_Aborted(std::string_view what) : Test_Error(what) {}
×
53
};
54

55
class Test_Options {
56
   public:
57
      Test_Options() = default;
58

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

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

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

108
      const std::string& data_dir() const { return m_data_dir; }
109

110
      const std::string& pkcs11_lib() const { return m_pkcs11_lib; }
3✔
111

112
      const std::string& provider() const { return m_provider; }
2✔
113

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

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

118
      uint32_t tpm2_persistent_rsa_handle() const { return static_cast<uint32_t>(m_tpm2_persistent_rsa_handle); }
2✔
119

120
      uint32_t tpm2_persistent_ecc_handle() const { return static_cast<uint32_t>(m_tpm2_persistent_ecc_handle); }
2✔
121

122
      const std::string& tpm2_persistent_auth_value() const { return m_tpm2_persistent_auth_value; }
123

124
      const std::string& drbg_seed() const { return m_drbg_seed; }
1✔
125

126
      const std::string& xml_results_dir() const { return m_xml_results_dir; }
1✔
127

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

130
      size_t test_runs() const { return m_test_runs; }
4✔
131

132
      size_t test_threads() const { return m_test_threads; }
3✔
133

134
      bool log_success() const { return m_log_success; }
3,620,764✔
135

136
      bool run_online_tests() const { return m_run_online_tests; }
2✔
137

138
      bool run_long_tests() const { return m_run_long_tests; }
2,871✔
139

140
      bool run_memory_intensive_tests() const { return m_run_memory_intensive_tests; }
1✔
141

142
      bool abort_on_first_fail() const { return m_abort_on_first_fail; }
24✔
143

144
      bool no_stdout() const { return m_no_stdout; }
1✔
145

146
      bool verbose() const { return m_verbose; }
2,557✔
147

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

173
namespace detail {
174

175
template <typename, typename = void>
176
constexpr bool has_std_to_string = false;
177
template <typename T>
178
constexpr bool has_std_to_string<T, std::void_t<decltype(std::to_string(std::declval<T>()))>> = true;
179

180
template <typename, typename = void>
181
constexpr bool has_ostream_operator = false;
182
template <typename T>
183
constexpr bool
184
   has_ostream_operator<T, std::void_t<decltype(operator<<(std::declval<std::ostringstream&>(), std::declval<T>()))>> =
185
      true;
186

187
template <typename T>
188
struct is_optional : std::false_type {};
189

190
template <typename T>
191
struct is_optional<std::optional<T>> : std::true_type {};
192

193
template <typename T>
194
constexpr bool is_optional_v = is_optional<T>::value;
195

196
}  // namespace detail
197

198
/**
199
 * A code location consisting of the source file path and a line
200
 */
201
struct CodeLocation {
202
      const char* path;
203
      unsigned int line;
204
};
205

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

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

228
            size_t tests_passed() const { return m_tests_passed; }
12,668✔
229

230
            size_t tests_failed() const { return m_fail_log.size(); }
69,004✔
231

232
            size_t tests_run() const { return tests_passed() + tests_failed(); }
12,668✔
233

234
            bool any_results() const { return tests_run() > 0; }
235

236
            const std::string& who() const { return m_who; }
236,130✔
237

238
            const std::vector<std::string>& failures() const { return m_fail_log; }
2,532✔
239

240
            const std::vector<std::string>& notes() const { return m_log; }
2,532✔
241

242
            std::optional<uint64_t> elapsed_time() const {
2,532✔
243
               if(m_ns_taken == 0) {
2,532✔
244
                  return std::nullopt;
245
               } else {
246
                  return m_ns_taken;
1,473✔
247
               }
248
            }
249

250
            // Nanoseconds since epoch
251
            uint64_t timestamp() const { return m_timestamp; }
2,532✔
252

253
            std::string result_string() const;
254

255
            static Result Failure(std::string_view who, std::string_view what) {
1✔
256
               Result r(who);
1✔
257
               r.test_failure(what);
1✔
258
               return r;
1✔
259
            }
×
260

261
            static Result Note(std::string_view who, std::string_view what) {
×
262
               Result r(who);
×
263
               r.test_note(what);
×
264
               return r;
×
265
            }
×
266

267
            void merge(const Result& other, bool ignore_test_name = false);
268

269
            /* Test reporting functions */
270

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

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

275
            void note_missing(std::string_view whatever);
276

277
            bool test_success(std::string_view note = "");
278

279
            bool test_failure(std::string err);
280

281
            bool test_failure(std::string_view err);
282

283
            bool test_failure(const char* err);
284

285
            bool test_failure(std::string_view what, std::string_view error);
286

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

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

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

297
            /* Generic arbitrary equality check */
298

299
            template <typename T>
300
            bool test_is_eq(const T& produced, const T& expected) {
8✔
301
               return test_is_eq("comparison", produced, expected);
8✔
302
            }
303

304
            template <typename T>
305
            bool test_is_eq(std::string_view what, const T& produced, const T& expected) {
46✔
306
               static_assert(!std::convertible_to<T, std::span<const uint8_t>>, "Use test_bin_eq");
307
               static_assert(!std::convertible_to<T, std::string_view>, "Use test_str_eq");
308
               static_assert(!std::is_integral_v<T>, "Use test_{sz,u8,u16,u32,u64}_eq");
309
               static_assert(!std::is_enum_v<T>, "Use test_enum_eq");
310

311
               std::ostringstream out;
46✔
312
               out << m_who << " " << what;
46✔
313

314
               if(produced == expected) {
37✔
315
                  out << " produced expected result";
46✔
316
                  return test_success(out.str());
46✔
317
               } else {
318
                  out << " produced unexpected result '" << to_string(produced) << "' expected '" << to_string(expected)
319
                      << "'";
×
320
                  return test_failure(out.str());
×
321
               }
322
            }
46✔
323

324
            template <typename E>
325
               requires std::is_enum_v<E>
326
            bool test_enum_eq(std::string_view what, const E& produced, const E& expected) {
31✔
327
               auto produced_v = static_cast<std::underlying_type_t<E>>(produced);
31✔
328
               auto expected_v = static_cast<std::underlying_type_t<E>>(expected);
31✔
329
               return test_u64_eq(what, produced_v, expected_v);
29✔
330
            }
331

332
            template <typename T>
333
            bool test_not_null(std::string_view what, const T& ptr) {
1,736✔
334
               if(ptr == nullptr) {
1,736✔
335
                  return test_failure(what, "was null");
×
336
               } else {
337
                  return test_success("not null");
1,736✔
338
               }
339
            }
340

341
            /* String comparison predicates */
342
            bool test_str_not_empty(std::string_view what, std::string_view produced);
343

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

346
            bool test_str_ne(std::string_view what, std::string_view produced, std::string_view expected);
347

348
            /* Test predicates on bool */
349
            bool test_bool_eq(std::string_view what, bool produced, bool expected);
350

351
            bool test_is_false(std::string_view what, bool produced);
352

353
            bool test_is_true(std::string_view what, bool produced);
354

355
            /* Test predicates on size_t */
356
            bool test_sz_eq(std::string_view what, size_t produced, size_t expected);
357
            bool test_sz_ne(std::string_view what, size_t produced, size_t expected);
358
            bool test_sz_lt(std::string_view what, size_t produced, size_t expected);
359
            bool test_sz_lte(std::string_view what, size_t produced, size_t expected);
360
            bool test_sz_gt(std::string_view what, size_t produced, size_t expected);
361
            bool test_sz_gte(std::string_view what, size_t produced, size_t expected);
362

363
            /* Type-hinted unsigned integer equality predicates */
364
            bool test_u8_eq(std::string_view what, uint8_t produced, uint8_t expected);
365
            bool test_u16_eq(std::string_view what, uint16_t produced, uint16_t expected);
366
            bool test_u32_eq(std::string_view what, uint32_t produced, uint32_t expected);
367
            bool test_u64_eq(std::string_view what, uint64_t produced, uint64_t expected);
368
            bool test_i16_eq(std::string_view what, int16_t produced, int16_t expected);
369
            bool test_i32_eq(std::string_view what, int32_t produced, int32_t expected);
370

371
            /* Prefer the versions that take a descriptor string above */
372
            bool test_u8_eq(uint8_t produced, uint8_t expected);
373
            bool test_u16_eq(uint16_t produced, uint16_t expected);
374
            bool test_u32_eq(uint32_t produced, uint32_t expected);
375
            bool test_u64_eq(uint64_t produced, uint64_t expected);
376

377
            /* Test predicates on integer return codes */
378
            bool test_rc_ok(std::string_view func, int rc);
379
            bool test_rc_fail(std::string_view func, std::string_view why, int rc);
380
            bool test_rc(std::string_view func, int rc, int expected);
381
            bool test_rc_init(std::string_view func, int rc);
382

383
            /* Test predicates on optional values */
384

385
            template <typename T>
386
            bool test_opt_not_null(std::string_view what, const std::optional<T>& val) {
10✔
387
               if(val == std::nullopt) {
10✔
388
                  return test_failure(what, "was nullopt");
×
389
               } else {
390
                  return test_success("not nullopt");
10✔
391
               }
392
            }
393

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

396
#if defined(BOTAN_HAS_BIGINT)
397
            /* Test predicates for BigInt */
398
            bool test_bn_eq(std::string_view what, const BigInt& produced, const BigInt& expected);
399
            bool test_bn_ne(std::string_view what, const BigInt& produced, const BigInt& expected);
400
#endif
401

402
            /* Test predicates for binary strings */
403
            bool test_bin_ne(std::string_view what,
404
                             std::span<const uint8_t> produced,
405
                             std::span<const uint8_t> expected);
406

407
            bool test_bin_eq(std::string_view what,
408
                             std::span<const uint8_t> produced,
409
                             std::span<const uint8_t> expected);
410

411
            bool test_bin_eq(std::string_view what, std::span<const uint8_t> produced, std::string_view expected_hex);
412

413
            template <std::size_t N>
414
            bool test_bin_eq(std::string_view what,
1,212✔
415
                             const std::array<uint8_t, N>& produced,
416
                             const std::array<uint8_t, N>& expected) {
417
               return test_bin_eq(what, std::span{produced}, std::span{expected});
1,186✔
418
            }
419

420
         private:
421
            class ThrowExpectations {
422
               public:
423
                  explicit ThrowExpectations(std::function<void()> fn) : m_fn(std::move(fn)) {}
73,518✔
424

425
                  ThrowExpectations(const ThrowExpectations&) = delete;
426
                  ThrowExpectations& operator=(const ThrowExpectations&) = delete;
427
                  ThrowExpectations(ThrowExpectations&&) = default;
428
                  ThrowExpectations& operator=(ThrowExpectations&&) = default;
429

430
                  ~ThrowExpectations();
431

432
                  ThrowExpectations& expect_success();
433

434
                  ThrowExpectations& expect_message(std::string_view message);
435

436
                  template <typename ExT>
437
                  ThrowExpectations& expect_exception_type() {
62,048✔
438
                     assert_that_success_is_not_expected();
62,048✔
439

440
                     m_expected_exception_check_fn = [](const std::exception_ptr& e) {
124,096✔
441
                        try {
442
                           if(e) {
62,048✔
443
                              std::rethrow_exception(e);
124,096✔
444
                           }
445
                        } catch(const ExT&) {
62,048✔
446
                           return true;
447
                        } catch(...) {
2✔
448
                           return false;
449
                        }
450
                        return false;
451
                     };
452
                     return *this;
453
                  }
454

455
                  bool check(std::string_view test_name, Test::Result& result);
456

457
               private:
458
                  void assert_that_success_is_not_expected() const;
459

460
                  std::function<void()> m_fn;
461
                  std::optional<std::string> m_expected_message;
462
                  std::function<bool(std::exception_ptr)> m_expected_exception_check_fn;
463
                  bool m_expect_success = false;
464
                  bool m_consumed = false;
465
            };
466

467
         public:
468
            bool test_throws(std::string_view what, std::function<void()> fn);
469

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

472
            bool test_no_throw(std::string_view what, std::function<void()> fn);
473

474
            template <typename ExceptionT>
475
            bool test_throws(std::string_view what, std::function<void()> fn) {
62,033✔
476
               return ThrowExpectations(std::move(fn)).expect_exception_type<ExceptionT>().check(what, *this);
186,099✔
477
            }
478

479
            template <typename ExceptionT>
480
            bool test_throws(std::string_view what, std::string_view expected, std::function<void()> fn) {
15✔
481
               // clang-format off
482
               return ThrowExpectations(std::move(fn)).expect_exception_type<ExceptionT>().expect_message(expected).check(what, *this);
45✔
483
               // clang-format on
484
            }
485

486
            void set_ns_consumed(uint64_t ns) { m_ns_taken = ns; }
48,267✔
487

488
            void start_timer();
489
            void end_timer();
490

491
            void set_code_location(CodeLocation where) { m_where = where; }
50,724✔
492

493
            const std::optional<CodeLocation>& code_location() const { return m_where; }
53,256✔
494

495
         private:
496
            template <typename T>
497
            std::string to_string(const T& v) {
×
498
               if constexpr(detail::is_optional_v<T>) {
499
                  return (v.has_value()) ? to_string(v.value()) : std::string("std::nullopt");
×
500
               } else if constexpr(detail::has_ostream_operator<T>) {
501
                  std::ostringstream oss;
×
502
                  oss << v;
×
503
                  return oss.str();
×
504
               } else if constexpr(detail::has_std_to_string<T>) {
×
505
                  //static_assert(false, "no std::to_string for you");
506
                  return std::to_string(v);
507
               } else {
508
                  //static_assert(false, "unknown type");
509
                  return "<?>";
×
510
               }
511
            }
512

513
         private:
514
            std::string m_who;
515
            std::optional<CodeLocation> m_where;
516
            uint64_t m_timestamp;
517
            uint64_t m_started = 0;
518
            uint64_t m_ns_taken = 0;
519
            size_t m_tests_passed = 0;
520
            std::vector<std::string> m_fail_log;
521
            std::vector<std::string> m_log;
522
      };
523

524
      virtual ~Test();
525

526
      Test();
527
      Test(const Test& other) = delete;
528
      Test(Test&& other) = default;
529
      Test& operator=(const Test& other) = delete;
530
      Test& operator=(Test&& other) = delete;
531

532
      virtual std::vector<Test::Result> run() = 0;
533

534
      virtual std::vector<std::string> possible_providers(const std::string& alg);
535

536
      void initialize(std::string test_name, CodeLocation location);
537

538
      const std::string& test_name() const { return m_test_name; }
23✔
539

540
      Botan::RandomNumberGenerator& rng() const;
541

542
      /**
543
       * Use this if a test needs some supported EC group but it is not relevant
544
       * which one exactly. This tries to find a commonly used group that is
545
       * both supported in this build and as small as possible (for test speed).
546
       *
547
       * If @p preferred_groups is non-empty, a group from that list is chosen
548
       *
549
       * @returns the name of a supported EC group, or std::nullopt if no
550
       *          supported EC group could be found for this build
551
       */
552
      static std::optional<std::string> supported_ec_group_name(std::vector<std::string> preferred_groups = {});
553

554
      const std::optional<CodeLocation>& registration_location() const { return m_registration_location; }
50,724✔
555

556
      /// @p smoke_test are run first in an unfiltered test run
557
      static void register_test(const std::string& category,
558
                                const std::string& name,
559
                                bool smoke_test,
560
                                bool needs_serialization,
561
                                std::function<std::unique_ptr<Test>()> maker_fn);
562

563
      static std::vector<std::string> registered_tests();
564
      static std::vector<std::string> registered_test_categories();
565

566
      static std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
567
                                                              const std::vector<std::string>& to_be_skipped);
568

569
      static std::unique_ptr<Test> get_test(const std::string& test_name);
570
      static bool test_needs_serialization(const std::string& test_name);
571

572
      static std::string data_dir(const std::string& subdir);
573
      static std::vector<std::string> files_in_data_dir(const std::string& subdir);
574
      static std::string data_file(const std::string& file);
575
      static std::string data_file_as_temporary_copy(const std::string& what);
576

577
      static std::string format_time(uint64_t nanoseconds);
578

579
      static std::vector<uint8_t> mutate_vec(const std::vector<uint8_t>& v,
580
                                             Botan::RandomNumberGenerator& rng,
581
                                             bool maybe_resize = false,
582
                                             size_t min_offset = 0);
583

584
      static void set_test_options(const Test_Options& opts);
585

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

588
      static const Test_Options& options() { return m_opts; }
589

590
      static bool run_long_tests() { return options().run_long_tests(); }
2,871✔
591

592
      static bool run_memory_intensive_tests() { return options().run_memory_intensive_tests(); }
1✔
593

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

596
      static std::string temp_file_name(const std::string& basename);
597
      static bool copy_file(const std::string& from, const std::string& to);
598

599
      static std::vector<std::string> provider_filter(const std::vector<std::string>& providers);
600

601
      static std::string read_data_file(const std::string& path);
602
      static std::vector<uint8_t> read_binary_data_file(const std::string& path);
603

604
      static std::unique_ptr<Botan::RandomNumberGenerator> new_rng(std::string_view test_name);
605
      static std::shared_ptr<Botan::RandomNumberGenerator> new_shared_rng(std::string_view test_name);
606

607
      static std::string random_password(Botan::RandomNumberGenerator& rng);
608
      static size_t random_index(Botan::RandomNumberGenerator& rng, size_t max);
609
      static uint64_t timestamp();  // nanoseconds arbitrary epoch
610

611
      static std::vector<Test::Result> flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists);
612

613
   private:
614
      static Test_Options m_opts;
615
      static std::string m_test_rng_seed;
616

617
      /// The string ID that was used to register this test
618
      std::string m_test_name;
619
      /// The source file location where the test was registered
620
      std::optional<CodeLocation> m_registration_location;
621
      /// The test-specific RNG state
622
      mutable std::unique_ptr<Botan::RandomNumberGenerator> m_test_rng;
623
};
624

625
/*
626
* Register the test with the runner
627
*/
628
template <typename Test_Class>
629
class TestClassRegistration {
630
   public:
631
      TestClassRegistration(const std::string& category,
386✔
632
                            const std::string& name,
633
                            bool smoke_test,
634
                            bool needs_serialization,
635
                            const CodeLocation& registration_location) {
636
         Test::register_test(category, name, smoke_test, needs_serialization, [=] {
1,884✔
637
            auto test = std::make_unique<Test_Class>();
386✔
638
            test->initialize(name, registration_location);
772✔
639
            return test;
386✔
640
         });
×
641
      }
386✔
642
};
643

644
// NOLINTBEGIN(*-macro-usage)
645

646
#define BOTAN_REGISTER_TEST(category, name, Test_Class) \
647
   /* NOLINTNEXTLINE(cert-err58-cpp) */                 \
648
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, false, {__FILE__, __LINE__})
649
#define BOTAN_REGISTER_SERIALIZED_TEST(category, name, Test_Class) \
650
   /* NOLINTNEXTLINE(cert-err58-cpp) */                            \
651
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, true, {__FILE__, __LINE__})
652
#define BOTAN_REGISTER_SMOKE_TEST(category, name, Test_Class) \
653
   /* NOLINTNEXTLINE(cert-err58-cpp) */                       \
654
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, false, {__FILE__, __LINE__})
655
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST(category, name, Test_Class) \
656
   /* NOLINTNEXTLINE(cert-err58-cpp) */                                  \
657
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, true, {__FILE__, __LINE__})
658

659
// NOLINTEND(*-macro-usage)
660

661
typedef Test::Result (*test_fn)();
662
typedef std::vector<Test::Result> (*test_fn_vec)();
663

664
class FnTest : public Test {
665
   private:
666
      using TestFnVariant = std::variant<test_fn, test_fn_vec>;
667

668
      template <typename TestFn>
669
      std::vector<TestFnVariant> make_variant_vector(TestFn fn) {
34✔
670
         using T = std::decay_t<decltype(fn)>;
671
         static_assert(std::is_same_v<T, test_fn> || std::is_same_v<T, test_fn_vec>,
672
                       "functions passed to BOTAN_REGISTER_TEST_FN must either return a "
673
                       "single Test::Result or a std::vector of Test::Result");
674
         return {fn};
34✔
675
      }
676

677
      template <typename TestFn, typename... TestFns>
678
      std::vector<TestFnVariant> make_variant_vector(const TestFn& fn, const TestFns&... fns) {
31✔
679
         auto functions = make_variant_vector(fns...);
31✔
680
         functions.emplace_back(fn);
31✔
681
         return functions;
31✔
682
      }
×
683

684
   public:
685
      template <typename... TestFns>
686
      explicit FnTest(TestFns... fns) : m_fns(make_variant_vector(fns...)) {}
34✔
687

688
      std::vector<Test::Result> run() override {
34✔
689
         std::vector<Test::Result> result;
34✔
690

691
         // TODO(Botan4) use std::ranges::reverse_view here once available (need newer Clang)
692
         // NOLINTNEXTLINE(modernize-loop-convert)
693
         for(auto fn_variant = m_fns.crbegin(); fn_variant != m_fns.crend(); ++fn_variant) {
99✔
694
            std::visit(
65✔
695
               [&](auto&& fn) {
130✔
696
                  using T = std::decay_t<decltype(fn)>;
697
                  if constexpr(std::is_same_v<T, test_fn>) {
698
                     result.emplace_back(fn());
7✔
699
                  } else {
700
                     const auto results = fn();
58✔
701
                     result.insert(result.end(), results.begin(), results.end());
58✔
702
                  }
58✔
703
               },
65✔
704
               *fn_variant);
65✔
705
         }
706

707
         return result;
34✔
708
      }
×
709

710
   private:
711
      std::vector<TestFnVariant> m_fns;
712
};
713

714
class TestFnRegistration {
715
   public:
716
      template <typename... TestFns>
717
      TestFnRegistration(const std::string& category,
34✔
718
                         const std::string& name,
719
                         bool smoke_test,
720
                         bool needs_serialization,
721
                         const CodeLocation& registration_location,
722
                         TestFns... fn) {
723
         Test::register_test(category, name, smoke_test, needs_serialization, [=] {
125✔
724
            auto test = std::make_unique<FnTest>(fn...);
34✔
725
            test->initialize(name, registration_location);
68✔
726
            return test;
34✔
727
         });
×
728
      }
34✔
729
};
730

731
// NOLINTBEGIN(*-macro-usage)
732

733
#define BOTAN_REGISTER_TEST_FN_IMPL(category, name, smoke_test, needs_serialization, fn0, ...) \
734
   /* NOLINTNEXTLINE(cert-err58-cpp) */                                                        \
735
   static const TestFnRegistration register_##fn0(                                             \
736
      category, name, smoke_test, needs_serialization, {__FILE__, __LINE__}, fn0 __VA_OPT__(, ) __VA_ARGS__)
737

738
#define BOTAN_REGISTER_TEST_FN(category, name, ...) \
739
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, false, false, __VA_ARGS__)
740
#define BOTAN_REGISTER_SMOKE_TEST_FN(category, name, ...) \
741
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, true, false, __VA_ARGS__)
742
#define BOTAN_REGISTER_SERIALIZED_TEST_FN(category, name, ...) \
743
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, false, true, __VA_ARGS__)
744
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST_FN(category, name, ...) \
745
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, true, true, __VA_ARGS__)
746

747
// NOLINTEND(*-macro-usage)
748

749
class VarMap {
181✔
750
   public:
751
      bool has_key(const std::string& key) const;
752

753
      bool get_req_bool(const std::string& key) const;
754

755
      std::vector<uint8_t> get_req_bin(const std::string& key) const;
756
      std::vector<uint8_t> get_opt_bin(const std::string& key) const;
757

758
      std::vector<std::vector<uint8_t>> get_req_bin_list(const std::string& key) const;
759

760
#if defined(BOTAN_HAS_BIGINT)
761
      Botan::BigInt get_req_bn(const std::string& key) const;
762
      Botan::BigInt get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const;
763
#endif
764

765
      std::string get_req_str(const std::string& key) const;
766
      std::string get_opt_str(const std::string& key, const std::string& def_value) const;
767

768
      size_t get_req_sz(const std::string& key) const;
769

770
      uint8_t get_req_u8(const std::string& key) const;
771
      uint32_t get_req_u32(const std::string& key) const;
772
      uint64_t get_req_u64(const std::string& key) const;
773

774
      size_t get_opt_sz(const std::string& key, size_t def_value) const;
775

776
      uint64_t get_opt_u64(const std::string& key, uint64_t def_value) const;
777

778
      void clear();
779

780
      void add(const std::string& key, const std::string& value);
781

782
   private:
783
      std::optional<std::string> get_var(const std::string& key) const;
784

785
      std::vector<std::pair<std::string, std::string>> m_vars;
786
};
787

788
/*
789
* A test based on reading an input file which contains key/value pairs
790
* Special note: the last value in required_key (there must be at least
791
* one), is the output key. This triggers the callback.
792
*
793
* Calls run_one_test with the variables set. If an ini-style [header]
794
* is used in the file, then header will be set to that value. This allows
795
* splitting up tests between [valid] and [invalid] tests, or different
796
* related algorithms tested in the same file. Use the get_XXX functions
797
* on VarMap to retrieve formatted values.
798
*
799
* If most of your tests are text-based but you find yourself with a few
800
* odds-and-ends tests that you want to do, override run_final_tests which
801
* can test whatever it likes and returns a vector of Results.
802
*/
803
class Text_Based_Test : public Test {
804
   public:
805
      Text_Based_Test(const std::string& data_src,
806
                      const std::string& required_keys_str,
807
                      const std::string& optional_keys_str = "");
808

809
      Text_Based_Test(const Text_Based_Test& other) = delete;
810
      Text_Based_Test(Text_Based_Test&& other) = default;
811
      Text_Based_Test& operator=(const Text_Based_Test& other) = delete;
812
      Text_Based_Test& operator=(Text_Based_Test&& other) = delete;
813

814
      ~Text_Based_Test() override;
815

816
      virtual bool clear_between_callbacks() const { return true; }
33,492✔
817

818
      std::vector<Test::Result> run() override;
819

820
   private:
821
      virtual Test::Result run_one_test(const std::string& header, const VarMap& vars) = 0;
822
      // Called before run_one_test
823
      virtual bool skip_this_test(const std::string& header, const VarMap& vars);
824

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

827
   private:
828
      class Text_Based_Test_Data;
829
      std::unique_ptr<Text_Based_Test_Data> m_data;
830
};
831

832
/**
833
 * This is a convenience wrapper to write small self-contained and in particular
834
 * exception-safe unit tests. If some (unexpected) exception is thrown in one of
835
 * the CHECK-scopes, it will fail the particular test gracefully with a human-
836
 * understandable failure output.
837
 *
838
 * Example Usage:
839
 *
840
 * ```
841
 * std::vector<Test::Result> test_something()
842
 *    {
843
 *    return
844
 *       {
845
 *       CHECK("some unit test name", [](Test::Result& r)
846
 *          {
847
 *          r.test_is_true("some observation", 1+1 == 2);
848
 *          }),
849
 *       CHECK("some other unit test name", [](Test::Result& r)
850
 *          {
851
 *          // ...
852
 *          })
853
 *       };
854
 *    }
855
 *
856
 * BOTAN_REGISTER_TEST_FN("some_category", "some_test_name", test_something);
857
 * ```
858
 */
859
template <typename FunT>
860
Test::Result CHECK(const char* name, FunT check_fun) {
508✔
861
   Botan_Tests::Test::Result r(name);
508✔
862

863
   try {
864
      check_fun(r);
508✔
865
   } catch(const Botan_Tests::Test_Aborted&) {
×
866
      // pass, failure was already noted in the responsible `require`
867
   } catch(const std::exception& ex) {
×
868
      r.test_failure("failed unexpectedly", ex.what());
×
869
   } catch(...) {
×
870
      r.test_failure("failed with unknown exception");
×
871
   }
872

873
   return r;
507✔
874
}
×
875

876
}  // namespace Botan_Tests
877

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