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

randombit / botan / 21794448852

08 Feb 2026 12:09AM UTC coverage: 90.065% (-0.008%) from 90.073%
21794448852

push

github

web-flow
Merge pull request #5295 from randombit/jack/header-patrol-3

Reduce header dependencies in tests and cli

102230 of 113507 relevant lines covered (90.06%)

11492365.41 hits per line

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

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

30
namespace Botan {
31

32
class RandomNumberGenerator;
33
class OctetString;
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,246✔
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_std_to_string = false;
183
template <typename T>
184
constexpr bool has_std_to_string<T, std::void_t<decltype(std::to_string(std::declval<T>()))>> = true;
185

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

193
template <typename T>
194
struct is_optional : std::false_type {};
195

196
template <typename T>
197
struct is_optional<std::optional<T>> : std::true_type {};
198

199
template <typename T>
200
constexpr bool is_optional_v = is_optional<T>::value;
201

202
}  // namespace detail
203

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

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

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

234
            size_t tests_passed() const { return m_tests_passed; }
12,590✔
235

236
            size_t tests_failed() const { return m_fail_log.size(); }
68,910✔
237

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

240
            bool any_results() const { return tests_run() > 0; }
241

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

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

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

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

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

259
            std::string result_string() const;
260

261
            static Result Failure(const std::string& who, const std::string& what) {
1✔
262
               Result r(who);
1✔
263
               r.test_failure(what);
1✔
264
               return r;
1✔
265
            }
×
266

267
            static Result Note(const std::string& who, const std::string& what) {
×
268
               Result r(who);
×
269
               r.test_note(what);
×
270
               return r;
×
271
            }
×
272

273
            void merge(const Result& other, bool ignore_test_name = false);
274

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

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

279
            void note_missing(const std::string& whatever);
280

281
            bool test_success(const std::string& note = "");
282

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

285
            bool test_failure(const std::string& what, const std::string& error);
286

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

289
            template <typename Alloc>
290
            void test_failure(const std::string& what, const std::vector<uint8_t, Alloc>& buf) {
1✔
291
               test_failure(what, buf.data(), buf.size());
1✔
292
            }
1✔
293

294
            bool confirm(const std::string& what, bool expr, bool expected = true) {
174,241✔
295
               return test_eq(what, expr, expected);
173,912✔
296
            }
297

298
            /**
299
             * Require a condition, throw Test_Aborted otherwise
300
             * Note: works best when combined with CHECK scopes!
301
             */
302
            void require(const std::string& what, bool expr, bool expected = true) {
329✔
303
               if(!confirm(what, expr, expected)) {
329✔
304
                  throw Test_Aborted("test aborted, because required condition was not met: " + what);
×
305
               }
306
            }
329✔
307

308
            template <typename T>
309
            bool test_is_eq(const T& produced, const T& expected) {
343✔
310
               return test_is_eq("comparison", produced, expected);
343✔
311
            }
312

313
            template <typename T>
314
            bool test_is_eq(const std::string& what, const T& produced, const T& expected) {
906,702✔
315
               std::ostringstream out;
906,702✔
316
               out << m_who << " " << what;
906,702✔
317

318
               if(produced == expected) {
906,693✔
319
                  out << " produced expected result";
906,700✔
320
                  return test_success(out.str());
906,700✔
321
               } else {
322
                  out << " produced unexpected result '" << to_string(produced) << "' expected '" << to_string(expected)
323
                      << "'";
7✔
324
                  return test_failure(out.str());
2✔
325
               }
326
            }
906,702✔
327

328
            template <typename T>
329
            bool test_not_null(const std::string& what, const T& ptr) {
1,735✔
330
               if(ptr == nullptr) {
1,735✔
331
                  return test_failure(what + " was null");
×
332
               } else {
333
                  return test_success(what + " was not null");
1,735✔
334
               }
335
            }
336

337
            template <typename T>
338
            bool test_not_nullopt(const std::string& what, const std::optional<T>& val) {
10✔
339
               if(val == std::nullopt) {
10✔
340
                  return test_failure(what + " was nullopt");
×
341
               } else {
342
                  return test_success(what + " was not nullopt");
10✔
343
               }
344
            }
345

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

348
            bool test_is_nonempty(const std::string& what_is_it, const std::string& to_examine);
349

350
            bool test_eq(const std::string& what, const std::string& produced, const std::string& expected);
351

352
            bool test_eq(const std::string& what, bool produced, bool expected);
353

354
            bool test_eq(const std::string& what, size_t produced, size_t expected);
355
            bool test_eq_sz(const std::string& what, size_t produced, size_t expected);
356

357
            bool test_eq(const std::string& what,
358
                         const Botan::OctetString& produced,
359
                         const Botan::OctetString& expected);
360

361
            template <typename I1, typename I2>
362
            bool test_int_eq(I1 x, I2 y, const char* what) {
59✔
363
               return test_eq(what, static_cast<size_t>(x), static_cast<size_t>(y));
59✔
364
            }
365

366
            template <typename I1, typename I2>
367
            bool test_int_eq(const std::string& what, I1 x, I2 y) {
5,179✔
368
               return test_eq(what, static_cast<size_t>(x), static_cast<size_t>(y));
5,179✔
369
            }
370

371
            template <typename T>
372
            bool test_eq(const std::string& what, const std::optional<T>& a, const std::optional<T>& b) {
1,215✔
373
               if(a.has_value() != b.has_value()) {
1,215✔
374
                  std::ostringstream err;
×
375
                  err << m_who << " " << what << " only one of a/b was nullopt";
×
376
                  return test_failure(err.str());
×
377
               } else if(a.has_value() && b.has_value()) {
1,215✔
378
                  return test_is_eq(what, a.value(), b.value());
10✔
379
               } else {
380
                  // both nullopt
381
                  return test_success();
1,205✔
382
               }
383
            }
384

385
            bool test_lt(const std::string& what, size_t produced, size_t expected);
386
            bool test_lte(const std::string& what, size_t produced, size_t expected);
387
            bool test_gt(const std::string& what, size_t produced, size_t expected);
388
            bool test_gte(const std::string& what, size_t produced, size_t expected);
389

390
            /* Test predicates on integer return codes */
391
            bool test_rc_ok(const std::string& func, int rc);
392
            bool test_rc_fail(const std::string& func, const std::string& why, int rc);
393
            bool test_rc(const std::string& func, int expected, int rc);
394
            bool test_rc_init(const std::string& func, int rc);
395

396
            bool test_ne(const std::string& what, size_t produced, size_t expected);
397

398
            bool test_ne(const std::string& what, const std::string& str1, const std::string& str2);
399

400
#if defined(BOTAN_HAS_BIGINT)
401
            bool test_eq(const std::string& what, const BigInt& produced, const BigInt& expected);
402
            bool test_ne(const std::string& what, const BigInt& produced, const BigInt& expected);
403
#endif
404

405
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
406
            bool test_eq(const std::string& what, const Botan::EC_Point& a, const Botan::EC_Point& b);
407
#endif
408

409
            bool test_eq(const char* producer,
410
                         const std::string& what,
411
                         const uint8_t produced[],
412
                         size_t produced_size,
413
                         const uint8_t expected[],
414
                         size_t expected_size);
415

416
            bool test_ne(const std::string& what,
417
                         const uint8_t produced[],
418
                         size_t produced_len,
419
                         const uint8_t expected[],
420
                         size_t expected_len);
421

422
            bool test_eq(const std::string& what,
131,306✔
423
                         std::span<const uint8_t> produced,
424
                         std::span<const uint8_t> expected) {
425
               return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
131,306✔
426
            }
427

428
            bool test_eq(const std::string& producer,
115,192✔
429
                         const std::string& what,
430
                         std::span<const uint8_t> produced,
431
                         std::span<const uint8_t> expected) {
432
               return test_eq(
115,192✔
433
                  producer.c_str(), what, produced.data(), produced.size(), expected.data(), expected.size());
115,192✔
434
            }
435

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

438
            template <std::size_t N>
439
            bool test_eq(const std::string& what,
2,440✔
440
                         const std::array<uint8_t, N>& produced,
441
                         const std::array<uint8_t, N>& expected) {
442
               return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
2,440✔
443
            }
444

445
            bool test_ne(const std::string& what,
3,408✔
446
                         std::span<const uint8_t> produced,
447
                         std::span<const uint8_t> expected) {
448
               return test_ne(what, produced.data(), produced.size(), expected.data(), expected.size());
3,408✔
449
            }
450

451
         private:
452
            class ThrowExpectations {
453
               public:
454
                  explicit ThrowExpectations(std::function<void()> fn) : m_fn(std::move(fn)) {}
135,572✔
455

456
                  ThrowExpectations(const ThrowExpectations&) = delete;
457
                  ThrowExpectations& operator=(const ThrowExpectations&) = delete;
458
                  ThrowExpectations(ThrowExpectations&&) = default;
459
                  ThrowExpectations& operator=(ThrowExpectations&&) = default;
460

461
                  ~ThrowExpectations() { BOTAN_ASSERT_NOMSG(m_consumed); }
130,023✔
462

463
                  ThrowExpectations& expect_success() {
1,645✔
464
                     BOTAN_ASSERT_NOMSG(!m_expected_message && !m_expected_exception_check_fn);
1,645✔
465
                     m_expect_success = true;
1,645✔
466
                     return *this;
1,645✔
467
                  }
468

469
                  ThrowExpectations& expect_message(const std::string& message) {
189✔
470
                     BOTAN_ASSERT_NOMSG(!m_expect_success);
189✔
471
                     m_expected_message = message;
189✔
472
                     return *this;
189✔
473
                  }
474

475
                  template <typename ExT>
476
                  ThrowExpectations& expect_exception_type() {
62,048✔
477
                     BOTAN_ASSERT_NOMSG(!m_expect_success);
62,048✔
478
                     m_expected_exception_check_fn = [](const std::exception_ptr& e) {
124,096✔
479
                        try {
480
                           if(e) {
62,048✔
481
                              std::rethrow_exception(e);
124,096✔
482
                           }
483
                        } catch(const ExT&) {
62,048✔
484
                           return true;
485
                        } catch(...) {
2✔
486
                           return false;
487
                        }
488
                        return false;
489
                     };
490
                     return *this;
62,048✔
491
                  }
492

493
                  bool check(const std::string& test_name, Test::Result& result);
494

495
               private:
496
                  std::function<void()> m_fn;
497
                  std::optional<std::string> m_expected_message;
498
                  std::function<bool(std::exception_ptr)> m_expected_exception_check_fn;
499
                  bool m_expect_success = false;
500
                  bool m_consumed = false;
501
            };
502

503
         public:
504
            bool test_throws(const std::string& what, const std::function<void()>& fn);
505

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

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

510
            template <typename ExceptionT>
511
            bool test_throws(const std::string& what, const std::function<void()>& fn) {
62,033✔
512
               return ThrowExpectations(fn).expect_exception_type<ExceptionT>().check(what, *this);
124,066✔
513
            }
514

515
            template <typename ExceptionT>
516
            bool test_throws(const std::string& what, const std::string& expected, const std::function<void()>& fn) {
15✔
517
               return ThrowExpectations(fn).expect_exception_type<ExceptionT>().expect_message(expected).check(what,
30✔
518
                                                                                                               *this);
15✔
519
            }
520

521
            void set_ns_consumed(uint64_t ns) { m_ns_taken = ns; }
48,251✔
522

523
            void start_timer();
524
            void end_timer();
525

526
            void set_code_location(CodeLocation where) { m_where = where; }
50,692✔
527

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

530
         private:
531
            template <typename T>
532
            std::string to_string(const T& v) {
2✔
533
               if constexpr(detail::is_optional_v<T>) {
534
                  return (v.has_value()) ? to_string(v.value()) : std::string("std::nullopt");
×
535
               } else if constexpr(detail::has_ostream_operator<T>) {
536
                  std::ostringstream oss;
2✔
537
                  oss << v;
2✔
538
                  return oss.str();
2✔
539
               } else if constexpr(detail::has_std_to_string<T>) {
2✔
540
                  //static_assert(false, "no std::to_string for you");
541
                  return std::to_string(v);
2✔
542
               } else {
543
                  //static_assert(false, "unknown type");
544
                  return "<?>";
×
545
               }
546
            }
547

548
         private:
549
            std::string m_who;
550
            std::optional<CodeLocation> m_where;
551
            uint64_t m_timestamp;
552
            uint64_t m_started = 0;
553
            uint64_t m_ns_taken = 0;
554
            size_t m_tests_passed = 0;
555
            std::vector<std::string> m_fail_log;
556
            std::vector<std::string> m_log;
557
      };
558

559
      virtual ~Test();
560

561
      Test();
562
      Test(const Test& other) = delete;
563
      Test(Test&& other) = default;
564
      Test& operator=(const Test& other) = delete;
565
      Test& operator=(Test&& other) = delete;
566

567
      virtual std::vector<Test::Result> run() = 0;
568

569
      virtual std::vector<std::string> possible_providers(const std::string& alg);
570

571
      void initialize(std::string test_name, CodeLocation location);
572

573
      const std::string& test_name() const { return m_test_name; }
23✔
574

575
      Botan::RandomNumberGenerator& rng() const;
576

577
      /**
578
       * Use this if a test needs some supported EC group but it is not relevant
579
       * which one exactly. This tries to find a commonly used group that is
580
       * both supported in this build and as small as possible (for test speed).
581
       *
582
       * If @p preferred_groups is non-empty, a group from that list is chosen
583
       *
584
       * @returns the name of a supported EC group, or std::nullopt if no
585
       *          supported EC group could be found for this build
586
       */
587
      static std::optional<std::string> supported_ec_group_name(std::vector<std::string> preferred_groups = {});
588

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

591
      /// @p smoke_test are run first in an unfiltered test run
592
      static void register_test(const std::string& category,
593
                                const std::string& name,
594
                                bool smoke_test,
595
                                bool needs_serialization,
596
                                std::function<std::unique_ptr<Test>()> maker_fn);
597

598
      static std::vector<std::string> registered_tests();
599
      static std::vector<std::string> registered_test_categories();
600

601
      static std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
602
                                                              const std::vector<std::string>& to_be_skipped);
603

604
      static std::unique_ptr<Test> get_test(const std::string& test_name);
605
      static bool test_needs_serialization(const std::string& test_name);
606

607
      static std::string data_dir(const std::string& subdir);
608
      static std::vector<std::string> files_in_data_dir(const std::string& subdir);
609
      static std::string data_file(const std::string& file);
610
      static std::string data_file_as_temporary_copy(const std::string& what);
611

612
      static std::string format_time(uint64_t nanoseconds);
613

614
      static std::vector<uint8_t> mutate_vec(const std::vector<uint8_t>& v,
615
                                             Botan::RandomNumberGenerator& rng,
616
                                             bool maybe_resize = false,
617
                                             size_t min_offset = 0);
618

619
      static void set_test_options(const Test_Options& opts);
620

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

623
      static const Test_Options& options() { return m_opts; }
624

625
      static bool run_long_tests() { return options().run_long_tests(); }
2,871✔
626

627
      static bool run_memory_intensive_tests() { return options().run_memory_intensive_tests(); }
1✔
628

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

631
      static std::string temp_file_name(const std::string& basename);
632
      static bool copy_file(const std::string& from, const std::string& to);
633

634
      static std::vector<std::string> provider_filter(const std::vector<std::string>& providers);
635

636
      static std::string read_data_file(const std::string& path);
637
      static std::vector<uint8_t> read_binary_data_file(const std::string& path);
638

639
      static std::unique_ptr<Botan::RandomNumberGenerator> new_rng(std::string_view test_name);
640
      static std::shared_ptr<Botan::RandomNumberGenerator> new_shared_rng(std::string_view test_name);
641

642
      static std::string random_password(Botan::RandomNumberGenerator& rng);
643
      static size_t random_index(Botan::RandomNumberGenerator& rng, size_t max);
644
      static uint64_t timestamp();  // nanoseconds arbitrary epoch
645

646
      static std::vector<Test::Result> flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists);
647

648
   private:
649
      static Test_Options m_opts;
650
      static std::string m_test_rng_seed;
651

652
      /// The string ID that was used to register this test
653
      std::string m_test_name;
654
      /// The source file location where the test was registered
655
      std::optional<CodeLocation> m_registration_location;
656
      /// The test-specific RNG state
657
      mutable std::unique_ptr<Botan::RandomNumberGenerator> m_test_rng;
658
};
659

660
/*
661
* Register the test with the runner
662
*/
663
template <typename Test_Class>
664
class TestClassRegistration {
665
   public:
666
      TestClassRegistration(const std::string& category,
385✔
667
                            const std::string& name,
668
                            bool smoke_test,
669
                            bool needs_serialization,
670
                            const CodeLocation& registration_location) {
671
         Test::register_test(category, name, smoke_test, needs_serialization, [=] {
1,878✔
672
            auto test = std::make_unique<Test_Class>();
385✔
673
            test->initialize(name, registration_location);
770✔
674
            return test;
385✔
675
         });
×
676
      }
385✔
677
};
678

679
// NOLINTBEGIN(*-macro-usage)
680

681
#define BOTAN_REGISTER_TEST(category, name, Test_Class) \
682
   /* NOLINTNEXTLINE(cert-err58-cpp) */                 \
683
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, false, {__FILE__, __LINE__})
684
#define BOTAN_REGISTER_SERIALIZED_TEST(category, name, Test_Class) \
685
   /* NOLINTNEXTLINE(cert-err58-cpp) */                            \
686
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, true, {__FILE__, __LINE__})
687
#define BOTAN_REGISTER_SMOKE_TEST(category, name, Test_Class) \
688
   /* NOLINTNEXTLINE(cert-err58-cpp) */                       \
689
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, false, {__FILE__, __LINE__})
690
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST(category, name, Test_Class) \
691
   /* NOLINTNEXTLINE(cert-err58-cpp) */                                  \
692
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, true, {__FILE__, __LINE__})
693

694
// NOLINTEND(*-macro-usage)
695

696
typedef Test::Result (*test_fn)();
697
typedef std::vector<Test::Result> (*test_fn_vec)();
698

699
class FnTest : public Test {
700
   private:
701
      using TestFnVariant = std::variant<test_fn, test_fn_vec>;
702

703
      template <typename TestFn>
704
      std::vector<TestFnVariant> make_variant_vector(TestFn fn) {
34✔
705
         using T = std::decay_t<decltype(fn)>;
706
         static_assert(std::is_same_v<T, test_fn> || std::is_same_v<T, test_fn_vec>,
707
                       "functions passed to BOTAN_REGISTER_TEST_FN must either return a "
708
                       "single Test::Result or a std::vector of Test::Result");
709
         return {fn};
34✔
710
      }
711

712
      template <typename TestFn, typename... TestFns>
713
      std::vector<TestFnVariant> make_variant_vector(const TestFn& fn, const TestFns&... fns) {
31✔
714
         auto functions = make_variant_vector(fns...);
31✔
715
         functions.emplace_back(fn);
31✔
716
         return functions;
31✔
717
      }
×
718

719
   public:
720
      template <typename... TestFns>
721
      explicit FnTest(TestFns... fns) : m_fns(make_variant_vector(fns...)) {}
34✔
722

723
      std::vector<Test::Result> run() override {
34✔
724
         std::vector<Test::Result> result;
34✔
725

726
         // TODO(Botan4) use std::ranges::reverse_view here once available (need newer Clang)
727
         // NOLINTNEXTLINE(modernize-loop-convert)
728
         for(auto fn_variant = m_fns.crbegin(); fn_variant != m_fns.crend(); ++fn_variant) {
99✔
729
            std::visit(
65✔
730
               [&](auto&& fn) {
130✔
731
                  using T = std::decay_t<decltype(fn)>;
732
                  if constexpr(std::is_same_v<T, test_fn>) {
733
                     result.emplace_back(fn());
7✔
734
                  } else {
735
                     const auto results = fn();
58✔
736
                     result.insert(result.end(), results.begin(), results.end());
58✔
737
                  }
58✔
738
               },
65✔
739
               *fn_variant);
65✔
740
         }
741

742
         return result;
34✔
743
      }
×
744

745
   private:
746
      std::vector<TestFnVariant> m_fns;
747
};
748

749
class TestFnRegistration {
750
   public:
751
      template <typename... TestFns>
752
      TestFnRegistration(const std::string& category,
34✔
753
                         const std::string& name,
754
                         bool smoke_test,
755
                         bool needs_serialization,
756
                         const CodeLocation& registration_location,
757
                         TestFns... fn) {
758
         Test::register_test(category, name, smoke_test, needs_serialization, [=] {
125✔
759
            auto test = std::make_unique<FnTest>(fn...);
34✔
760
            test->initialize(name, registration_location);
68✔
761
            return test;
34✔
762
         });
×
763
      }
34✔
764
};
765

766
// NOLINTBEGIN(*-macro-usage)
767

768
#define BOTAN_REGISTER_TEST_FN_IMPL(category, name, smoke_test, needs_serialization, fn0, ...) \
769
   /* NOLINTNEXTLINE(cert-err58-cpp) */                                                        \
770
   static const TestFnRegistration register_##fn0(                                             \
771
      category, name, smoke_test, needs_serialization, {__FILE__, __LINE__}, fn0 __VA_OPT__(, ) __VA_ARGS__)
772

773
#define BOTAN_REGISTER_TEST_FN(category, name, ...) \
774
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, false, false, __VA_ARGS__)
775
#define BOTAN_REGISTER_SMOKE_TEST_FN(category, name, ...) \
776
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, true, false, __VA_ARGS__)
777
#define BOTAN_REGISTER_SERIALIZED_TEST_FN(category, name, ...) \
778
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, false, true, __VA_ARGS__)
779
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST_FN(category, name, ...) \
780
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, true, true, __VA_ARGS__)
781

782
// NOLINTEND(*-macro-usage)
783

784
class VarMap {
181✔
785
   public:
786
      bool has_key(const std::string& key) const;
787

788
      bool get_req_bool(const std::string& key) const;
789

790
      std::vector<uint8_t> get_req_bin(const std::string& key) const;
791
      std::vector<uint8_t> get_opt_bin(const std::string& key) const;
792

793
      std::vector<std::vector<uint8_t>> get_req_bin_list(const std::string& key) const;
794

795
#if defined(BOTAN_HAS_BIGINT)
796
      Botan::BigInt get_req_bn(const std::string& key) const;
797
      Botan::BigInt get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const;
798
#endif
799

800
      std::string get_req_str(const std::string& key) const;
801
      std::string get_opt_str(const std::string& key, const std::string& def_value) const;
802

803
      size_t get_req_sz(const std::string& key) const;
804

805
      uint8_t get_req_u8(const std::string& key) const;
806
      uint32_t get_req_u32(const std::string& key) const;
807
      uint64_t get_req_u64(const std::string& key) const;
808

809
      size_t get_opt_sz(const std::string& key, size_t def_value) const;
810

811
      uint64_t get_opt_u64(const std::string& key, uint64_t def_value) const;
812

813
      void clear();
814

815
      void add(const std::string& key, const std::string& value);
816

817
   private:
818
      std::optional<std::string> get_var(const std::string& key) const;
819

820
      std::vector<std::pair<std::string, std::string>> m_vars;
821
};
822

823
/*
824
* A test based on reading an input file which contains key/value pairs
825
* Special note: the last value in required_key (there must be at least
826
* one), is the output key. This triggers the callback.
827
*
828
* Calls run_one_test with the variables set. If an ini-style [header]
829
* is used in the file, then header will be set to that value. This allows
830
* splitting up tests between [valid] and [invalid] tests, or different
831
* related algorithms tested in the same file. Use the get_XXX functions
832
* on VarMap to retrieve formatted values.
833
*
834
* If most of your tests are text-based but you find yourself with a few
835
* odds-and-ends tests that you want to do, override run_final_tests which
836
* can test whatever it likes and returns a vector of Results.
837
*/
838
class Text_Based_Test : public Test {
839
   public:
840
      Text_Based_Test(const std::string& data_src,
841
                      const std::string& required_keys_str,
842
                      const std::string& optional_keys_str = "");
843

844
      Text_Based_Test(const Text_Based_Test& other) = delete;
845
      Text_Based_Test(Text_Based_Test&& other) = default;
846
      Text_Based_Test& operator=(const Text_Based_Test& other) = delete;
847
      Text_Based_Test& operator=(Text_Based_Test&& other) = delete;
848

849
      ~Text_Based_Test() override;
850

851
      virtual bool clear_between_callbacks() const { return true; }
33,476✔
852

853
      std::vector<Test::Result> run() override;
854

855
   private:
856
      virtual Test::Result run_one_test(const std::string& header, const VarMap& vars) = 0;
857
      // Called before run_one_test
858
      virtual bool skip_this_test(const std::string& header, const VarMap& vars);
859

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

862
   private:
863
      class Text_Based_Test_Data;
864
      std::unique_ptr<Text_Based_Test_Data> m_data;
865
};
866

867
/**
868
 * This is a convenience wrapper to write small self-contained and in particular
869
 * exception-safe unit tests. If some (unexpected) exception is thrown in one of
870
 * the CHECK-scopes, it will fail the particular test gracefully with a human-
871
 * understandable failure output.
872
 *
873
 * Example Usage:
874
 *
875
 * ```
876
 * std::vector<Test::Result> test_something()
877
 *    {
878
 *    return
879
 *       {
880
 *       CHECK("some unit test name", [](Test::Result& r)
881
 *          {
882
 *          r.confirm("some observation", 1+1 == 2);
883
 *          }),
884
 *       CHECK("some other unit test name", [](Test::Result& r)
885
 *          {
886
 *          // ...
887
 *          })
888
 *       };
889
 *    }
890
 *
891
 * BOTAN_REGISTER_TEST_FN("some_category", "some_test_name", test_something);
892
 * ```
893
 */
894
template <typename FunT>
895
Test::Result CHECK(const char* name, FunT check_fun) {
508✔
896
   Botan_Tests::Test::Result r(name);
585✔
897

898
   try {
899
      check_fun(r);
508✔
900
   } catch(const Botan_Tests::Test_Aborted&) {
×
901
      // pass, failure was already noted in the responsible `require`
902
   } catch(const std::exception& ex) {
×
903
      r.test_failure("failed unexpectedly", ex.what());
×
904
   } catch(...) {
×
905
      r.test_failure("failed with unknown exception");
×
906
   }
907

908
   return r;
508✔
909
}
×
910

911
}  // namespace Botan_Tests
912

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