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

randombit / botan / 21240376859

22 Jan 2026 07:50AM UTC coverage: 90.071% (-0.004%) from 90.075%
21240376859

push

github

web-flow
Merge pull request #5254 from Rohde-Schwarz/chore/tls_does_not_depend_on_secp

Avoid hard dependency on `pcurves_secp*` in the TLS module

102101 of 113356 relevant lines covered (90.07%)

11524547.86 hits per line

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

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

8
#ifndef BOTAN_TESTS_H_
9
#define BOTAN_TESTS_H_
10

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

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

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

32
namespace Botan {
33

34
class RandomNumberGenerator;
35

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

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

44
}  // namespace Botan
45

46
namespace Botan_Tests {
47

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

52
class Test_Error : public Botan::Exception {
53
   public:
54
      explicit Test_Error(const std::string& what) : Exception("Test error", what) {}
1✔
55

56
      Botan::ErrorType error_type() const noexcept override { return Botan::ErrorType::Unknown; }
×
57
};
58

59
class Test_Aborted final : public Test_Error {
60
   public:
61
      explicit Test_Aborted(const std::string& what) : Test_Error(what) {}
×
62
};
63

64
class Test_Options {
65
   public:
66
      Test_Options() = default;
67

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

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

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

117
      const std::string& data_dir() const { return m_data_dir; }
118

119
      const std::string& pkcs11_lib() const { return m_pkcs11_lib; }
3✔
120

121
      const std::string& provider() const { return m_provider; }
2✔
122

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

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

127
      uint32_t tpm2_persistent_rsa_handle() const { return static_cast<uint32_t>(m_tpm2_persistent_rsa_handle); }
2✔
128

129
      uint32_t tpm2_persistent_ecc_handle() const { return static_cast<uint32_t>(m_tpm2_persistent_ecc_handle); }
2✔
130

131
      const std::string& tpm2_persistent_auth_value() const { return m_tpm2_persistent_auth_value; }
132

133
      const std::string& drbg_seed() const { return m_drbg_seed; }
1✔
134

135
      const std::string& xml_results_dir() const { return m_xml_results_dir; }
1✔
136

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

139
      size_t test_runs() const { return m_test_runs; }
4✔
140

141
      size_t test_threads() const { return m_test_threads; }
3✔
142

143
      bool log_success() const { return m_log_success; }
3,610,568✔
144

145
      bool run_online_tests() const { return m_run_online_tests; }
2✔
146

147
      bool run_long_tests() const { return m_run_long_tests; }
2,871✔
148

149
      bool run_memory_intensive_tests() const { return m_run_memory_intensive_tests; }
1✔
150

151
      bool abort_on_first_fail() const { return m_abort_on_first_fail; }
25✔
152

153
      bool no_stdout() const { return m_no_stdout; }
1✔
154

155
      bool verbose() const { return m_verbose; }
2,541✔
156

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

182
namespace detail {
183

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

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

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

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

204
template <typename T>
205
struct is_optional<std::optional<T>> : std::true_type {};
206

207
template <typename T>
208
constexpr bool is_optional_v = is_optional<T>::value;
209

210
}  // namespace detail
211

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

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

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

242
            size_t tests_passed() const { return m_tests_passed; }
12,585✔
243

244
            size_t tests_failed() const { return m_fail_log.size(); }
68,749✔
245

246
            size_t tests_run() const { return tests_passed() + tests_failed(); }
12,585✔
247

248
            bool any_results() const { return tests_run() > 0; }
249

250
            const std::string& who() const { return m_who; }
234,961✔
251

252
            const std::vector<std::string>& failures() const { return m_fail_log; }
2,515✔
253

254
            const std::vector<std::string>& notes() const { return m_log; }
2,515✔
255

256
            std::optional<uint64_t> elapsed_time() const {
2,515✔
257
               if(m_ns_taken == 0) {
2,515✔
258
                  return std::nullopt;
259
               } else {
260
                  return m_ns_taken;
1,472✔
261
               }
262
            }
263

264
            // Nanoseconds since epoch
265
            uint64_t timestamp() const { return m_timestamp; }
2,515✔
266

267
            std::string result_string() const;
268

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

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

281
            static Result OfExpectedFailure(bool expecting_failure, const Test::Result& result) {
282
               if(!expecting_failure) {
283
                  return result;
284
               }
285

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

297
            void merge(const Result& other, bool ignore_test_name = false);
298

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

301
            template <typename Alloc>
302
            void test_note(const std::string& who, const std::vector<uint8_t, Alloc>& vec) {
12✔
303
               const std::string hex = Botan::hex_encode(vec);
12✔
304
               return test_note(who, hex.c_str());
12✔
305
            }
12✔
306

307
            void note_missing(const std::string& whatever);
308

309
            bool test_success(const std::string& note = "");
310

311
            bool test_failure(const std::string& err);
312

313
            bool test_failure(const std::string& what, const std::string& error);
314

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

317
            template <typename Alloc>
318
            void test_failure(const std::string& what, const std::vector<uint8_t, Alloc>& buf) {
1✔
319
               test_failure(what, buf.data(), buf.size());
1✔
320
            }
1✔
321

322
            bool confirm(const std::string& what, bool expr, bool expected = true) {
173,644✔
323
               return test_eq(what, expr, expected);
173,315✔
324
            }
325

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

336
            template <typename T>
337
            bool test_is_eq(const T& produced, const T& expected) {
369✔
338
               return test_is_eq("comparison", produced, expected);
369✔
339
            }
340

341
            template <typename T>
342
            bool test_is_eq(const std::string& what, const T& produced, const T& expected) {
902,403✔
343
               std::ostringstream out;
902,403✔
344
               out << m_who << " " << what;
902,403✔
345

346
               if(produced == expected) {
902,394✔
347
                  out << " produced expected result";
902,401✔
348
                  return test_success(out.str());
902,401✔
349
               } else {
350
                  out << " produced unexpected result '" << to_string(produced) << "' expected '" << to_string(expected)
351
                      << "'";
7✔
352
                  return test_failure(out.str());
2✔
353
               }
354
            }
902,403✔
355

356
            template <typename T>
357
            bool test_not_null(const std::string& what, const T& ptr) {
1,735✔
358
               if(ptr == nullptr) {
1,735✔
359
                  return test_failure(what + " was null");
×
360
               } else {
361
                  return test_success(what + " was not null");
1,735✔
362
               }
363
            }
364

365
            template <typename T>
366
            bool test_not_nullopt(const std::string& what, const std::optional<T>& val) {
10✔
367
               if(val == std::nullopt) {
10✔
368
                  return test_failure(what + " was nullopt");
×
369
               } else {
370
                  return test_success(what + " was not nullopt");
10✔
371
               }
372
            }
373

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

376
            bool test_is_nonempty(const std::string& what_is_it, const std::string& to_examine);
377

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

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

382
            bool test_eq(const std::string& what, size_t produced, size_t expected);
383
            bool test_eq_sz(const std::string& what, size_t produced, size_t expected);
384

385
            bool test_eq(const std::string& what,
386
                         const Botan::OctetString& produced,
387
                         const Botan::OctetString& expected);
388

389
            template <typename I1, typename I2>
390
            bool test_int_eq(I1 x, I2 y, const char* what) {
59✔
391
               return test_eq(what, static_cast<size_t>(x), static_cast<size_t>(y));
59✔
392
            }
393

394
            template <typename I1, typename I2>
395
            bool test_int_eq(const std::string& what, I1 x, I2 y) {
5,186✔
396
               return test_eq(what, static_cast<size_t>(x), static_cast<size_t>(y));
5,186✔
397
            }
398

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

413
            bool test_lt(const std::string& what, size_t produced, size_t expected);
414
            bool test_lte(const std::string& what, size_t produced, size_t expected);
415
            bool test_gt(const std::string& what, size_t produced, size_t expected);
416
            bool test_gte(const std::string& what, size_t produced, size_t expected);
417

418
            template <typename T>
419
            bool test_rc_ok(const std::string& func, T rc) {
2,846✔
420
               static_assert(std::is_integral_v<T>, "Integer required.");
421

422
               if(rc != 0) {
2,846✔
423
                  std::ostringstream err;
1✔
424
                  err << m_who;
1✔
425
                  err << " " << func;
1✔
426
                  err << " unexpectedly failed with error code " << rc;
1✔
427
                  return test_failure(err.str());
1✔
428
               }
1✔
429

430
               return test_success();
2,845✔
431
            }
432

433
            template <typename T>
434
            bool test_rc_fail(const std::string& func, const std::string& why, T rc) {
27✔
435
               static_assert(std::is_integral_v<T>, "Integer required.");
436

437
               if(rc == 0) {
27✔
438
                  std::ostringstream err;
1✔
439
                  err << m_who;
1✔
440
                  err << " call to " << func << " unexpectedly succeeded";
1✔
441
                  err << " expecting failure because " << why;
1✔
442
                  return test_failure(err.str());
1✔
443
               }
1✔
444

445
               return test_success();
26✔
446
            }
447

448
            bool test_rc(const std::string& func, int expected, int rc);
449

450
            bool test_rc_init(const std::string& func, int rc);
451

452
            bool test_ne(const std::string& what, size_t produced, size_t expected);
453

454
            bool test_ne(const std::string& what, const std::string& str1, const std::string& str2);
455

456
#if defined(BOTAN_HAS_BIGINT)
457
            bool test_eq(const std::string& what, const BigInt& produced, const BigInt& expected);
458
            bool test_ne(const std::string& what, const BigInt& produced, const BigInt& expected);
459
#endif
460

461
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
462
            bool test_eq(const std::string& what, const Botan::EC_Point& a, const Botan::EC_Point& b);
463
#endif
464

465
            bool test_eq(const char* producer,
466
                         const std::string& what,
467
                         const uint8_t produced[],
468
                         size_t produced_size,
469
                         const uint8_t expected[],
470
                         size_t expected_size);
471

472
            bool test_ne(const std::string& what,
473
                         const uint8_t produced[],
474
                         size_t produced_len,
475
                         const uint8_t expected[],
476
                         size_t expected_len);
477

478
            bool test_eq(const std::string& what,
131,260✔
479
                         std::span<const uint8_t> produced,
480
                         std::span<const uint8_t> expected) {
481
               return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
131,260✔
482
            }
483

484
            bool test_eq(const std::string& producer,
112,124✔
485
                         const std::string& what,
486
                         std::span<const uint8_t> produced,
487
                         std::span<const uint8_t> expected) {
488
               return test_eq(
112,124✔
489
                  producer.c_str(), what, produced.data(), produced.size(), expected.data(), expected.size());
112,124✔
490
            }
491

492
            bool test_eq(const std::string& what, std::span<const uint8_t> produced, const char* expected_hex) {
425✔
493
               const std::vector<uint8_t> expected = Botan::hex_decode(expected_hex);
425✔
494
               return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
425✔
495
            }
425✔
496

497
            template <std::size_t N>
498
            bool test_eq(const std::string& what,
2,440✔
499
                         const std::array<uint8_t, N>& produced,
500
                         const std::array<uint8_t, N>& expected) {
501
               return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
2,440✔
502
            }
503

504
            bool test_ne(const std::string& what,
3,400✔
505
                         std::span<const uint8_t> produced,
506
                         std::span<const uint8_t> expected) {
507
               return test_ne(what, produced.data(), produced.size(), expected.data(), expected.size());
3,400✔
508
            }
509

510
         private:
511
            class ThrowExpectations {
512
               public:
513
                  explicit ThrowExpectations(std::function<void()> fn) : m_fn(std::move(fn)) {}
135,348✔
514

515
                  ThrowExpectations(const ThrowExpectations&) = delete;
516
                  ThrowExpectations& operator=(const ThrowExpectations&) = delete;
517
                  ThrowExpectations(ThrowExpectations&&) = default;
518
                  ThrowExpectations& operator=(ThrowExpectations&&) = default;
519

520
                  ~ThrowExpectations() { BOTAN_ASSERT_NOMSG(m_consumed); }
129,799✔
521

522
                  ThrowExpectations& expect_success() {
1,645✔
523
                     BOTAN_ASSERT_NOMSG(!m_expected_message && !m_expected_exception_check_fn);
1,645✔
524
                     m_expect_success = true;
1,645✔
525
                     return *this;
1,645✔
526
                  }
527

528
                  ThrowExpectations& expect_message(const std::string& message) {
189✔
529
                     BOTAN_ASSERT_NOMSG(!m_expect_success);
189✔
530
                     m_expected_message = message;
189✔
531
                     return *this;
189✔
532
                  }
533

534
                  template <typename ExT>
535
                  ThrowExpectations& expect_exception_type() {
61,936✔
536
                     BOTAN_ASSERT_NOMSG(!m_expect_success);
61,936✔
537
                     m_expected_exception_check_fn = [](const std::exception_ptr& e) {
123,872✔
538
                        try {
539
                           if(e) {
61,936✔
540
                              std::rethrow_exception(e);
123,872✔
541
                           }
542
                        } catch(const ExT&) {
61,936✔
543
                           return true;
544
                        } catch(...) {
2✔
545
                           return false;
546
                        }
547
                        return false;
548
                     };
549
                     return *this;
61,936✔
550
                  }
551

552
                  bool check(const std::string& test_name, Test::Result& result);
553

554
               private:
555
                  std::function<void()> m_fn;
556
                  std::optional<std::string> m_expected_message;
557
                  std::function<bool(std::exception_ptr)> m_expected_exception_check_fn;
558
                  bool m_expect_success = false;
559
                  bool m_consumed = false;
560
            };
561

562
         public:
563
            bool test_throws(const std::string& what, const std::function<void()>& fn);
564

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

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

569
            template <typename ExceptionT>
570
            bool test_throws(const std::string& what, const std::function<void()>& fn) {
61,921✔
571
               return ThrowExpectations(fn).expect_exception_type<ExceptionT>().check(what, *this);
123,842✔
572
            }
573

574
            template <typename ExceptionT>
575
            bool test_throws(const std::string& what, const std::string& expected, const std::function<void()>& fn) {
15✔
576
               return ThrowExpectations(fn).expect_exception_type<ExceptionT>().expect_message(expected).check(what,
30✔
577
                                                                                                               *this);
15✔
578
            }
579

580
            void set_ns_consumed(uint64_t ns) { m_ns_taken = ns; }
48,104✔
581

582
            void start_timer();
583
            void end_timer();
584

585
            void set_code_location(CodeLocation where) { m_where = where; }
50,545✔
586

587
            const std::optional<CodeLocation>& code_location() const { return m_where; }
53,060✔
588

589
         private:
590
            template <typename T>
591
            std::string to_string(const T& v) {
2✔
592
               if constexpr(detail::is_optional_v<T>) {
593
                  return (v.has_value()) ? to_string(v.value()) : std::string("std::nullopt");
×
594
               } else if constexpr(detail::has_Botan_to_string<T>) {
595
                  return Botan::to_string(v);
596
               } else if constexpr(detail::has_ostream_operator<T>) {
597
                  std::ostringstream oss;
2✔
598
                  oss << v;
2✔
599
                  return oss.str();
2✔
600
               } else if constexpr(detail::has_std_to_string<T>) {
2✔
601
                  return std::to_string(v);
2✔
602
               } else {
603
                  return "<?>";
×
604
               }
605
            }
606

607
         private:
608
            std::string m_who;
609
            std::optional<CodeLocation> m_where;
610
            uint64_t m_timestamp;
611
            uint64_t m_started = 0;
612
            uint64_t m_ns_taken = 0;
613
            size_t m_tests_passed = 0;
614
            std::vector<std::string> m_fail_log;
615
            std::vector<std::string> m_log;
616
      };
617

618
      virtual ~Test();
619

620
      Test();
621
      Test(const Test& other) = delete;
622
      Test(Test&& other) = default;
623
      Test& operator=(const Test& other) = delete;
624
      Test& operator=(Test&& other) = delete;
625

626
      virtual std::vector<Test::Result> run() = 0;
627

628
      virtual std::vector<std::string> possible_providers(const std::string& alg);
629

630
      void initialize(std::string test_name, CodeLocation location);
631

632
      const std::string& test_name() const { return m_test_name; }
23✔
633

634
      Botan::RandomNumberGenerator& rng() const;
635

636
      /**
637
       * Use this if a test needs some supported EC group but it is not relevant
638
       * which one exactly. This tries to find a commonly used group that is
639
       * both supported in this build and as small as possible (for test speed).
640
       *
641
       * If @p preferred_groups is non-empty, a group from that list is chosen
642
       *
643
       * @returns the name of a supported EC group, or std::nullopt if no
644
       *          supported EC group could be found for this build
645
       */
646
      static std::optional<std::string> supported_ec_group_name(std::vector<std::string> preferred_groups = {});
647

648
      const std::optional<CodeLocation>& registration_location() const { return m_registration_location; }
50,545✔
649

650
      /// @p smoke_test are run first in an unfiltered test run
651
      static void register_test(const std::string& category,
652
                                const std::string& name,
653
                                bool smoke_test,
654
                                bool needs_serialization,
655
                                std::function<std::unique_ptr<Test>()> maker_fn);
656

657
      static std::vector<std::string> registered_tests();
658
      static std::vector<std::string> registered_test_categories();
659

660
      static std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
661
                                                              const std::vector<std::string>& to_be_skipped);
662

663
      static std::unique_ptr<Test> get_test(const std::string& test_name);
664
      static bool test_needs_serialization(const std::string& test_name);
665

666
      static std::string data_dir(const std::string& subdir);
667
      static std::vector<std::string> files_in_data_dir(const std::string& subdir);
668
      static std::string data_file(const std::string& file);
669
      static std::string data_file_as_temporary_copy(const std::string& what);
670

671
      static std::string format_time(uint64_t nanoseconds);
672

673
      static std::vector<uint8_t> mutate_vec(const std::vector<uint8_t>& v,
674
                                             Botan::RandomNumberGenerator& rng,
675
                                             bool maybe_resize = false,
676
                                             size_t min_offset = 0);
677

678
      static void set_test_options(const Test_Options& opts);
679

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

682
      static const Test_Options& options() { return m_opts; }
683

684
      static bool run_long_tests() { return options().run_long_tests(); }
2,871✔
685

686
      static bool run_memory_intensive_tests() { return options().run_memory_intensive_tests(); }
1✔
687

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

690
      static std::string temp_file_name(const std::string& basename);
691
      static bool copy_file(const std::string& from, const std::string& to);
692

693
      static std::vector<std::string> provider_filter(const std::vector<std::string>& providers);
694

695
      static std::string read_data_file(const std::string& path);
696
      static std::vector<uint8_t> read_binary_data_file(const std::string& path);
697

698
      static std::unique_ptr<Botan::RandomNumberGenerator> new_rng(std::string_view test_name);
699
      static std::shared_ptr<Botan::RandomNumberGenerator> new_shared_rng(std::string_view test_name);
700

701
      static std::string random_password(Botan::RandomNumberGenerator& rng);
702
      static size_t random_index(Botan::RandomNumberGenerator& rng, size_t max);
703
      static uint64_t timestamp();  // nanoseconds arbitrary epoch
704

705
      static std::vector<Test::Result> flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists);
706

707
   private:
708
      static Test_Options m_opts;
709
      static std::string m_test_rng_seed;
710

711
      /// The string ID that was used to register this test
712
      std::string m_test_name;
713
      /// The source file location where the test was registered
714
      std::optional<CodeLocation> m_registration_location;
715
      /// The test-specific RNG state
716
      mutable std::unique_ptr<Botan::RandomNumberGenerator> m_test_rng;
717
};
718

719
/*
720
* Register the test with the runner
721
*/
722
template <typename Test_Class>
723
class TestClassRegistration {
724
   public:
725
      TestClassRegistration(const std::string& category,
384✔
726
                            const std::string& name,
727
                            bool smoke_test,
728
                            bool needs_serialization,
729
                            const CodeLocation& registration_location) {
730
         Test::register_test(category, name, smoke_test, needs_serialization, [=] {
1,874✔
731
            auto test = std::make_unique<Test_Class>();
384✔
732
            test->initialize(name, registration_location);
768✔
733
            return test;
384✔
734
         });
×
735
      }
384✔
736
};
737

738
// NOLINTBEGIN(*-macro-usage)
739

740
#define BOTAN_REGISTER_TEST(category, name, Test_Class) \
741
   /* NOLINTNEXTLINE(cert-err58-cpp) */                 \
742
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, false, {__FILE__, __LINE__})
743
#define BOTAN_REGISTER_SERIALIZED_TEST(category, name, Test_Class) \
744
   /* NOLINTNEXTLINE(cert-err58-cpp) */                            \
745
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, true, {__FILE__, __LINE__})
746
#define BOTAN_REGISTER_SMOKE_TEST(category, name, Test_Class) \
747
   /* NOLINTNEXTLINE(cert-err58-cpp) */                       \
748
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, false, {__FILE__, __LINE__})
749
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST(category, name, Test_Class) \
750
   /* NOLINTNEXTLINE(cert-err58-cpp) */                                  \
751
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, true, {__FILE__, __LINE__})
752

753
// NOLINTEND(*-macro-usage)
754

755
typedef Test::Result (*test_fn)();
756
typedef std::vector<Test::Result> (*test_fn_vec)();
757

758
class FnTest : public Test {
759
   private:
760
      using TestFnVariant = std::variant<test_fn, test_fn_vec>;
761

762
      template <typename TestFn>
763
      std::vector<TestFnVariant> make_variant_vector(TestFn fn) {
34✔
764
         using T = std::decay_t<decltype(fn)>;
765
         static_assert(std::is_same_v<T, test_fn> || std::is_same_v<T, test_fn_vec>,
766
                       "functions passed to BOTAN_REGISTER_TEST_FN must either return a "
767
                       "single Test::Result or a std::vector of Test::Result");
768
         return {fn};
34✔
769
      }
770

771
      template <typename TestFn, typename... TestFns>
772
      std::vector<TestFnVariant> make_variant_vector(const TestFn& fn, const TestFns&... fns) {
31✔
773
         auto functions = make_variant_vector(fns...);
31✔
774
         functions.emplace_back(fn);
31✔
775
         return functions;
31✔
776
      }
×
777

778
   public:
779
      template <typename... TestFns>
780
      explicit FnTest(TestFns... fns) : m_fns(make_variant_vector(fns...)) {}
34✔
781

782
      std::vector<Test::Result> run() override {
34✔
783
         std::vector<Test::Result> result;
34✔
784

785
         // TODO(Botan4) use std::ranges::reverse_view here once available (need newer Clang)
786
         // NOLINTNEXTLINE(modernize-loop-convert)
787
         for(auto fn_variant = m_fns.crbegin(); fn_variant != m_fns.crend(); ++fn_variant) {
99✔
788
            std::visit(
65✔
789
               [&](auto&& fn) {
130✔
790
                  using T = std::decay_t<decltype(fn)>;
791
                  if constexpr(std::is_same_v<T, test_fn>) {
792
                     result.emplace_back(fn());
7✔
793
                  } else {
794
                     const auto results = fn();
58✔
795
                     result.insert(result.end(), results.begin(), results.end());
58✔
796
                  }
58✔
797
               },
65✔
798
               *fn_variant);
65✔
799
         }
800

801
         return result;
34✔
802
      }
×
803

804
   private:
805
      std::vector<TestFnVariant> m_fns;
806
};
807

808
class TestFnRegistration {
809
   public:
810
      template <typename... TestFns>
811
      TestFnRegistration(const std::string& category,
34✔
812
                         const std::string& name,
813
                         bool smoke_test,
814
                         bool needs_serialization,
815
                         const CodeLocation& registration_location,
816
                         TestFns... fn) {
817
         Test::register_test(category, name, smoke_test, needs_serialization, [=] {
125✔
818
            auto test = std::make_unique<FnTest>(fn...);
34✔
819
            test->initialize(name, registration_location);
68✔
820
            return test;
34✔
821
         });
×
822
      }
34✔
823
};
824

825
// NOLINTBEGIN(*-macro-usage)
826

827
#define BOTAN_REGISTER_TEST_FN_IMPL(category, name, smoke_test, needs_serialization, fn0, ...) \
828
   /* NOLINTNEXTLINE(cert-err58-cpp) */                                                        \
829
   static const TestFnRegistration register_##fn0(                                             \
830
      category, name, smoke_test, needs_serialization, {__FILE__, __LINE__}, fn0 __VA_OPT__(, ) __VA_ARGS__)
831

832
#define BOTAN_REGISTER_TEST_FN(category, name, ...) \
833
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, false, false, __VA_ARGS__)
834
#define BOTAN_REGISTER_SMOKE_TEST_FN(category, name, ...) \
835
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, true, false, __VA_ARGS__)
836
#define BOTAN_REGISTER_SERIALIZED_TEST_FN(category, name, ...) \
837
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, false, true, __VA_ARGS__)
838
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST_FN(category, name, ...) \
839
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, true, true, __VA_ARGS__)
840

841
// NOLINTEND(*-macro-usage)
842

843
class VarMap {
180✔
844
   public:
845
      bool has_key(const std::string& key) const;
846

847
      bool get_req_bool(const std::string& key) const;
848

849
      std::vector<uint8_t> get_req_bin(const std::string& key) const;
850
      std::vector<uint8_t> get_opt_bin(const std::string& key) const;
851

852
      std::vector<std::vector<uint8_t>> get_req_bin_list(const std::string& key) const;
853

854
#if defined(BOTAN_HAS_BIGINT)
855
      Botan::BigInt get_req_bn(const std::string& key) const;
856
      Botan::BigInt get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const;
857
#endif
858

859
      std::string get_req_str(const std::string& key) const;
860
      std::string get_opt_str(const std::string& key, const std::string& def_value) const;
861

862
      size_t get_req_sz(const std::string& key) const;
863

864
      uint8_t get_req_u8(const std::string& key) const;
865
      uint32_t get_req_u32(const std::string& key) const;
866
      uint64_t get_req_u64(const std::string& key) const;
867

868
      size_t get_opt_sz(const std::string& key, size_t def_value) const;
869

870
      uint64_t get_opt_u64(const std::string& key, uint64_t def_value) const;
871

872
      void clear();
873

874
      void add(const std::string& key, const std::string& value);
875

876
   private:
877
      std::optional<std::string> get_var(const std::string& key) const;
878

879
      std::vector<std::pair<std::string, std::string>> m_vars;
880
};
881

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

903
      Text_Based_Test(const Text_Based_Test& other) = delete;
904
      Text_Based_Test(Text_Based_Test&& other) = default;
905
      Text_Based_Test& operator=(const Text_Based_Test& other) = delete;
906
      Text_Based_Test& operator=(Text_Based_Test&& other) = delete;
907

908
      ~Text_Based_Test() override;
909

910
      virtual bool clear_between_callbacks() const { return true; }
33,329✔
911

912
      std::vector<Test::Result> run() override;
913

914
   private:
915
      virtual Test::Result run_one_test(const std::string& header, const VarMap& vars) = 0;
916
      // Called before run_one_test
917
      virtual bool skip_this_test(const std::string& header, const VarMap& vars);
918

919
      virtual std::vector<Test::Result> run_final_tests() { return std::vector<Test::Result>(); }
171✔
920

921
   private:
922
      class Text_Based_Test_Data;
923
      std::unique_ptr<Text_Based_Test_Data> m_data;
924
};
925

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

957
   try {
958
      check_fun(r);
508✔
959
   } catch(const Botan_Tests::Test_Aborted&) {
×
960
      // pass, failure was already noted in the responsible `require`
961
   } catch(const std::exception& ex) {
×
962
      r.test_failure("failed unexpectedly", ex.what());
×
963
   } catch(...) {
×
964
      r.test_failure("failed with unknown exception");
×
965
   }
966

967
   return r;
508✔
968
}
×
969

970
}  // namespace Botan_Tests
971

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