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

randombit / botan / 20295000893

17 Dec 2025 07:24AM UTC coverage: 90.52% (+0.2%) from 90.36%
20295000893

Pull #5167

github

web-flow
Merge 70b91cb18 into 3d96b675e
Pull Request #5167: Changes to reduce unnecessary inclusions

101154 of 111748 relevant lines covered (90.52%)

12785105.95 hits per line

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

88.7
/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
#include <botan/assert.h>
12
#include <botan/exceptn.h>
13
#include <botan/hex.h>
14
#include <botan/symkey.h>
15
#include <botan/types.h>
16
#include <deque>
17
#include <functional>
18
#include <iosfwd>
19
#include <map>
20
#include <memory>
21
#include <optional>
22
#include <set>
23
#include <span>
24
#include <sstream>
25
#include <string>
26
#include <variant>
27
#include <vector>
28

29
namespace Botan {
30

31
class RandomNumberGenerator;
32

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

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

41
}  // namespace Botan
42

43
namespace Botan_Tests {
44

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

49
class Test_Error : public Botan::Exception {
50
   public:
51
      explicit Test_Error(const std::string& what) : Exception("Test error", what) {}
1✔
52

53
      Botan::ErrorType error_type() const noexcept override { return Botan::ErrorType::Unknown; }
×
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;
1✔
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.begin(), skip_tests.end()),
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::set<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
      std::map<std::string, std::string> report_properties() const;
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,519,912✔
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,534✔
153

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

179
namespace detail {
180

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

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

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

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

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

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

207
}  // namespace detail
208

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

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

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

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

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

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

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

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

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

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

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

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

264
            std::string result_string() const;
265

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

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

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

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

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

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

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

304
            void note_missing(const std::string& whatever);
305

306
            bool test_success(const std::string& note = "");
307

308
            bool test_failure(const std::string& err);
309

310
            bool test_failure(const std::string& what, const std::string& error);
311

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

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

319
            bool confirm(const std::string& what, bool expr, bool expected = true) {
164,483✔
320
               return test_eq(what, expr, expected);
164,154✔
321
            }
322

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

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

338
            template <typename T>
339
            bool test_is_eq(const std::string& what, const T& produced, const T& expected) {
863,079✔
340
               std::ostringstream out;
863,079✔
341
               out << m_who << " " << what;
863,079✔
342

343
               if(produced == expected) {
863,070✔
344
                  out << " produced expected result";
863,077✔
345
                  return test_success(out.str());
863,077✔
346
               } else {
347
                  out << " produced unexpected result '" << to_string(produced) << "' expected '" << to_string(expected)
348
                      << "'";
7✔
349
                  return test_failure(out.str());
2✔
350
               }
351
            }
863,079✔
352

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

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

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

373
            bool test_is_nonempty(const std::string& what_is_it, const std::string& to_examine);
374

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

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

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

382
            bool test_eq(const std::string& what,
383
                         const Botan::OctetString& produced,
384
                         const Botan::OctetString& expected);
385

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

391
            template <typename I1, typename I2>
392
            bool test_int_eq(const std::string& what, I1 x, I2 y) {
3,972✔
393
               return test_eq(what, static_cast<size_t>(x), static_cast<size_t>(y));
3,972✔
394
            }
395

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

410
            bool test_lt(const std::string& what, size_t produced, size_t expected);
411
            bool test_lte(const std::string& what, size_t produced, size_t expected);
412
            bool test_gt(const std::string& what, size_t produced, size_t expected);
413
            bool test_gte(const std::string& what, size_t produced, size_t expected);
414

415
            template <typename T>
416
            bool test_rc_ok(const std::string& func, T rc) {
2,354✔
417
               static_assert(std::is_integral_v<T>, "Integer required.");
418

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

427
               return test_success();
2,353✔
428
            }
429

430
            template <typename T>
431
            bool test_rc_fail(const std::string& func, const std::string& why, T rc) {
25✔
432
               static_assert(std::is_integral_v<T>, "Integer required.");
433

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

442
               return test_success();
24✔
443
            }
444

445
            bool test_rc(const std::string& func, int expected, int rc);
446

447
            bool test_rc_init(const std::string& func, int rc);
448

449
            bool test_ne(const std::string& what, size_t produced, size_t expected);
450

451
            bool test_ne(const std::string& what, const std::string& str1, const std::string& str2);
452

453
#if defined(BOTAN_HAS_BIGINT)
454
            bool test_eq(const std::string& what, const BigInt& produced, const BigInt& expected);
455
            bool test_ne(const std::string& what, const BigInt& produced, const BigInt& expected);
456
#endif
457

458
#if defined(BOTAN_HAS_LEGACY_EC_POINT)
459
            bool test_eq(const std::string& what, const Botan::EC_Point& a, const Botan::EC_Point& b);
460
#endif
461

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

469
            bool test_ne(const std::string& what,
470
                         const uint8_t produced[],
471
                         size_t produced_len,
472
                         const uint8_t expected[],
473
                         size_t expected_len);
474

475
            bool test_eq(const std::string& what,
120,356✔
476
                         std::span<const uint8_t> produced,
477
                         std::span<const uint8_t> expected) {
478
               return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
120,356✔
479
            }
480

481
            bool test_eq(const std::string& producer,
108,966✔
482
                         const std::string& what,
483
                         std::span<const uint8_t> produced,
484
                         std::span<const uint8_t> expected) {
485
               return test_eq(
108,966✔
486
                  producer.c_str(), what, produced.data(), produced.size(), expected.data(), expected.size());
108,966✔
487
            }
488

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

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

501
            bool test_ne(const std::string& what,
3,407✔
502
                         std::span<const uint8_t> produced,
503
                         std::span<const uint8_t> expected) {
504
               return test_ne(what, produced.data(), produced.size(), expected.data(), expected.size());
3,407✔
505
            }
506

507
         private:
508
            class ThrowExpectations {
509
               public:
510
                  explicit ThrowExpectations(std::function<void()> fn) : m_fn(std::move(fn)) {}
98,420✔
511

512
                  ThrowExpectations(const ThrowExpectations&) = delete;
513
                  ThrowExpectations& operator=(const ThrowExpectations&) = delete;
514
                  ThrowExpectations(ThrowExpectations&&) = default;
515
                  ThrowExpectations& operator=(ThrowExpectations&&) = default;
516

517
                  ~ThrowExpectations() { BOTAN_ASSERT_NOMSG(m_consumed); }
92,871✔
518

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

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

531
                  template <typename ExT>
532
                  ThrowExpectations& expect_exception_type() {
43,472✔
533
                     BOTAN_ASSERT_NOMSG(!m_expect_success);
43,472✔
534
                     m_expected_exception_check_fn = [](const std::exception_ptr& e) {
86,944✔
535
                        try {
536
                           if(e) {
43,472✔
537
                              std::rethrow_exception(e);
86,944✔
538
                           }
539
                        } catch(const ExT&) {
43,472✔
540
                           return true;
541
                        } catch(...) {
2✔
542
                           return false;
543
                        }
544
                        return false;
545
                     };
546
                     return *this;
43,472✔
547
                  }
548

549
                  bool check(const std::string& test_name, Test::Result& result);
550

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

559
         public:
560
            bool test_throws(const std::string& what, const std::function<void()>& fn);
561

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

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

566
            template <typename ExceptionT>
567
            bool test_throws(const std::string& what, const std::function<void()>& fn) {
43,457✔
568
               return ThrowExpectations(fn).expect_exception_type<ExceptionT>().check(what, *this);
86,914✔
569
            }
570

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

577
            void set_ns_consumed(uint64_t ns) { m_ns_taken = ns; }
47,967✔
578

579
            void start_timer();
580
            void end_timer();
581

582
            void set_code_location(CodeLocation where) { m_where = where; }
50,401✔
583

584
            const std::optional<CodeLocation>& code_location() const { return m_where; }
52,909✔
585

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

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

615
      virtual ~Test();
616

617
      Test();
618
      Test(const Test& other) = delete;
619
      Test(Test&& other) = default;
620
      Test& operator=(const Test& other) = delete;
621
      Test& operator=(Test&& other) = delete;
622

623
      virtual std::vector<Test::Result> run() = 0;
624

625
      virtual std::vector<std::string> possible_providers(const std::string& alg);
626

627
      void initialize(std::string test_name, CodeLocation location);
628

629
      const std::string& test_name() const { return m_test_name; }
19✔
630

631
      Botan::RandomNumberGenerator& rng() const;
632

633
      const std::optional<CodeLocation>& registration_location() const { return m_registration_location; }
50,401✔
634

635
      /// @p smoke_test are run first in an unfiltered test run
636
      static void register_test(const std::string& category,
637
                                const std::string& name,
638
                                bool smoke_test,
639
                                bool needs_serialization,
640
                                std::function<std::unique_ptr<Test>()> maker_fn);
641

642
      static std::set<std::string> registered_tests();
643
      static std::set<std::string> registered_test_categories();
644
      static std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
645
                                                              const std::set<std::string>& to_be_skipped);
646

647
      static std::unique_ptr<Test> get_test(const std::string& test_name);
648
      static bool test_needs_serialization(const std::string& test_name);
649

650
      static std::string data_dir(const std::string& subdir);
651
      static std::vector<std::string> files_in_data_dir(const std::string& subdir);
652
      static std::string data_file(const std::string& file);
653
      static std::string data_file_as_temporary_copy(const std::string& what);
654

655
      static std::string format_time(uint64_t nanoseconds);
656

657
      static std::vector<uint8_t> mutate_vec(const std::vector<uint8_t>& v,
658
                                             Botan::RandomNumberGenerator& rng,
659
                                             bool maybe_resize = false,
660
                                             size_t min_offset = 0);
661

662
      static void set_test_options(const Test_Options& opts);
663

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

666
      static const Test_Options& options() { return m_opts; }
667

668
      static bool run_long_tests() { return options().run_long_tests(); }
2,871✔
669

670
      static bool run_memory_intensive_tests() { return options().run_memory_intensive_tests(); }
1✔
671

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

674
      static std::string temp_file_name(const std::string& basename);
675
      static bool copy_file(const std::string& from, const std::string& to);
676

677
      static std::vector<std::string> provider_filter(const std::vector<std::string>& providers);
678

679
      static std::string read_data_file(const std::string& path);
680
      static std::vector<uint8_t> read_binary_data_file(const std::string& path);
681

682
      static std::unique_ptr<Botan::RandomNumberGenerator> new_rng(std::string_view test_name);
683
      static std::shared_ptr<Botan::RandomNumberGenerator> new_shared_rng(std::string_view test_name);
684

685
      static std::string random_password(Botan::RandomNumberGenerator& rng);
686
      static size_t random_index(Botan::RandomNumberGenerator& rng, size_t max);
687
      static uint64_t timestamp();  // nanoseconds arbitrary epoch
688

689
      static std::vector<Test::Result> flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists);
690

691
   private:
692
      static Test_Options m_opts;
693
      static std::string m_test_rng_seed;
694

695
      /// The string ID that was used to register this test
696
      std::string m_test_name;
697
      /// The source file location where the test was registered
698
      std::optional<CodeLocation> m_registration_location;
699
      /// The test-specific RNG state
700
      mutable std::unique_ptr<Botan::RandomNumberGenerator> m_test_rng;
701
};
702

703
/*
704
* Register the test with the runner
705
*/
706
template <typename Test_Class>
707
class TestClassRegistration {
708
   public:
709
      TestClassRegistration(const std::string& category,
378✔
710
                            const std::string& name,
711
                            bool smoke_test,
712
                            bool needs_serialization,
713
                            const CodeLocation& registration_location) {
714
         Test::register_test(category, name, smoke_test, needs_serialization, [=] {
1,843✔
715
            auto test = std::make_unique<Test_Class>();
378✔
716
            test->initialize(name, registration_location);
756✔
717
            return test;
378✔
718
         });
×
719
      }
378✔
720
};
721

722
// NOLINTBEGIN(*-macro-usage)
723

724
#define BOTAN_REGISTER_TEST(category, name, Test_Class) \
725
   /* NOLINTNEXTLINE(cert-err58-cpp) */                 \
726
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, false, {__FILE__, __LINE__})
727
#define BOTAN_REGISTER_SERIALIZED_TEST(category, name, Test_Class) \
728
   /* NOLINTNEXTLINE(cert-err58-cpp) */                            \
729
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, true, {__FILE__, __LINE__})
730
#define BOTAN_REGISTER_SMOKE_TEST(category, name, Test_Class) \
731
   /* NOLINTNEXTLINE(cert-err58-cpp) */                       \
732
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, false, {__FILE__, __LINE__})
733
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST(category, name, Test_Class) \
734
   /* NOLINTNEXTLINE(cert-err58-cpp) */                                  \
735
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, true, {__FILE__, __LINE__})
736

737
// NOLINTEND(*-macro-usage)
738

739
typedef Test::Result (*test_fn)();
740
typedef std::vector<Test::Result> (*test_fn_vec)();
741

742
class FnTest : public Test {
743
   private:
744
      using TestFnVariant = std::variant<test_fn, test_fn_vec>;
745

746
      template <typename TestFn>
747
      std::vector<TestFnVariant> make_variant_vector(TestFn fn) {
34✔
748
         using T = std::decay_t<decltype(fn)>;
749
         static_assert(std::is_same_v<T, test_fn> || std::is_same_v<T, test_fn_vec>,
750
                       "functions passed to BOTAN_REGISTER_TEST_FN must either return a "
751
                       "single Test::Result or a std::vector of Test::Result");
752
         return {fn};
34✔
753
      }
754

755
      template <typename TestFn, typename... TestFns>
756
      std::vector<TestFnVariant> make_variant_vector(const TestFn& fn, const TestFns&... fns) {
31✔
757
         auto functions = make_variant_vector(fns...);
31✔
758
         functions.emplace_back(fn);
31✔
759
         return functions;
31✔
760
      }
×
761

762
   public:
763
      template <typename... TestFns>
764
      explicit FnTest(TestFns... fns) : m_fns(make_variant_vector(fns...)) {}
34✔
765

766
      std::vector<Test::Result> run() override {
34✔
767
         std::vector<Test::Result> result;
34✔
768

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

785
         return result;
34✔
786
      }
×
787

788
   private:
789
      std::vector<TestFnVariant> m_fns;
790
};
791

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

809
// NOLINTBEGIN(*-macro-usage)
810

811
#define BOTAN_REGISTER_TEST_FN_IMPL(category, name, smoke_test, needs_serialization, fn0, ...) \
812
   /* NOLINTNEXTLINE(cert-err58-cpp) */                                                        \
813
   static const TestFnRegistration register_##fn0(                                             \
814
      category, name, smoke_test, needs_serialization, {__FILE__, __LINE__}, fn0 __VA_OPT__(, ) __VA_ARGS__)
815

816
#define BOTAN_REGISTER_TEST_FN(category, name, ...) \
817
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, false, false, __VA_ARGS__)
818
#define BOTAN_REGISTER_SMOKE_TEST_FN(category, name, ...) \
819
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, true, false, __VA_ARGS__)
820
#define BOTAN_REGISTER_SERIALIZED_TEST_FN(category, name, ...) \
821
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, false, true, __VA_ARGS__)
822
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST_FN(category, name, ...) \
823
   BOTAN_REGISTER_TEST_FN_IMPL(category, name, true, true, __VA_ARGS__)
824

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

827
class VarMap {
360✔
828
   public:
829
      void clear() { m_vars.clear(); }
33,997✔
830

831
      void add(const std::string& key, const std::string& value) { m_vars[key] = value; }
154,995✔
832

833
      bool has_key(const std::string& key) const { return m_vars.count(key) == 1; }
421,692✔
834

835
      bool get_req_bool(const std::string& key) const;
836

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

840
      std::vector<std::vector<uint8_t>> get_req_bin_list(const std::string& key) const;
841

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

847
      std::string get_req_str(const std::string& key) const;
848
      std::string get_opt_str(const std::string& key, const std::string& def_value) const;
849

850
      size_t get_req_sz(const std::string& key) const;
851

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

856
      size_t get_opt_sz(const std::string& key, size_t def_value) const;
857

858
      uint64_t get_opt_u64(const std::string& key, uint64_t def_value) const;
859

860
   private:
861
      std::map<std::string, std::string> m_vars;
862
};
863

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

885
      virtual bool clear_between_callbacks() const { return true; }
33,193✔
886

887
      std::vector<Test::Result> run() override;
888

889
   protected:
890
      std::string get_next_line();
891

892
      virtual Test::Result run_one_test(const std::string& header, const VarMap& vars) = 0;
893
      // Called before run_one_test
894
      virtual bool skip_this_test(const std::string& header, const VarMap& vars);
895

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

898
   private:
899
      std::string m_data_src;
900
      std::set<std::string> m_required_keys;
901
      std::set<std::string> m_optional_keys;
902
      std::string m_output_key;
903

904
      bool m_first = true;
905
      std::unique_ptr<std::istream> m_cur;
906
      std::string m_cur_src_name;
907
      std::deque<std::string> m_srcs;
908
      std::vector<std::string> m_cpu_flags;
909
};
910

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

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

952
   return r;
508✔
953
}
×
954

955
}  // namespace Botan_Tests
956

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