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

randombit / botan / 5134090420

31 May 2023 03:12PM UTC coverage: 91.721% (-0.3%) from 91.995%
5134090420

push

github

randombit
Merge GH #3565 Disable noisy/pointless pylint warnings

76048 of 82912 relevant lines covered (91.72%)

11755290.1 hits per line

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

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

28
namespace Botan {
29

30
#if defined(BOTAN_HAS_BIGINT)
31
class BigInt;
32
#endif
33

34
#if defined(BOTAN_HAS_EC_CURVE_GFP)
35
class EC_Point;
36
#endif
37

38
}  // namespace Botan
39

40
namespace Botan_Tests {
41

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

46
class Test_Error : public Botan::Exception {
47
   public:
48
      explicit Test_Error(const std::string& what) : Exception("Test error", what) {}
1✔
49

50
      Botan::ErrorType error_type() const noexcept override { return Botan::ErrorType::Unknown; }
×
51
};
52

53
class Test_Aborted final : public Test_Error {
54
   public:
55
      explicit Test_Aborted(const std::string& what) : Test_Error(what) {}
×
56
};
57

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

62
      Test_Options(const std::vector<std::string>& requested_tests,
1✔
63
                   const std::vector<std::string>& skip_tests,
64
                   const std::string& data_dir,
65
                   const std::string& pkcs11_lib,
66
                   const std::string& provider,
67
                   const std::string& drbg_seed,
68
                   const std::string& xml_results_dir,
69
                   const std::vector<std::string>& report_properties,
70
                   size_t test_runs,
71
                   size_t test_threads,
72
                   bool verbose,
73
                   bool log_success,
74
                   bool run_online_tests,
75
                   bool run_long_tests,
76
                   bool run_memory_intensive_tests,
77
                   bool abort_on_first_fail) :
1✔
78
            m_requested_tests(requested_tests),
1✔
79
            m_skip_tests(skip_tests.begin(), skip_tests.end()),
1✔
80
            m_data_dir(data_dir),
1✔
81
            m_pkcs11_lib(pkcs11_lib),
1✔
82
            m_provider(provider),
1✔
83
            m_drbg_seed(drbg_seed),
1✔
84
            m_xml_results_dir(xml_results_dir),
1✔
85
            m_report_properties(report_properties),
1✔
86
            m_test_runs(test_runs),
1✔
87
            m_test_threads(test_threads),
1✔
88
            m_verbose(verbose),
1✔
89
            m_log_success(log_success),
1✔
90
            m_run_online_tests(run_online_tests),
1✔
91
            m_run_long_tests(run_long_tests),
1✔
92
            m_run_memory_intensive_tests(run_memory_intensive_tests),
1✔
93
            m_abort_on_first_fail(abort_on_first_fail) {}
1✔
94

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

97
      const std::set<std::string>& skip_tests() const { return m_skip_tests; }
1✔
98

99
      const std::string& data_dir() const { return m_data_dir; }
100

101
      const std::string& pkcs11_lib() const { return m_pkcs11_lib; }
3✔
102

103
      const std::string& provider() const { return m_provider; }
2✔
104

105
      const std::string& drbg_seed() const { return m_drbg_seed; }
1✔
106

107
      const std::string& xml_results_dir() const { return m_xml_results_dir; }
1✔
108

109
      std::map<std::string, std::string> report_properties() const;
110

111
      size_t test_runs() const { return m_test_runs; }
4✔
112

113
      size_t test_threads() const { return m_test_threads; }
3✔
114

115
      bool log_success() const { return m_log_success; }
2,985,535✔
116

117
      bool run_online_tests() const { return m_run_online_tests; }
2✔
118

119
      bool run_long_tests() const { return m_run_long_tests; }
2,334✔
120

121
      bool run_memory_intensive_tests() const { return m_run_memory_intensive_tests; }
1✔
122

123
      bool abort_on_first_fail() const { return m_abort_on_first_fail; }
25✔
124

125
      bool verbose() const { return m_verbose; }
1,682✔
126

127
   private:
128
      std::vector<std::string> m_requested_tests;
129
      std::set<std::string> m_skip_tests;
130
      std::string m_data_dir;
131
      std::string m_pkcs11_lib;
132
      std::string m_provider;
133
      std::string m_drbg_seed;
134
      std::string m_xml_results_dir;
135
      std::vector<std::string> m_report_properties;
136
      size_t m_test_runs;
137
      size_t m_test_threads;
138
      bool m_verbose;
139
      bool m_log_success;
140
      bool m_run_online_tests;
141
      bool m_run_long_tests;
142
      bool m_run_memory_intensive_tests;
143
      bool m_abort_on_first_fail;
144
};
145

146
namespace detail {
147

148
template <typename, typename = void>
149
constexpr bool has_Botan_to_string = false;
150
template <typename T>
151
constexpr bool has_Botan_to_string<T, std::void_t<decltype(Botan::to_string(std::declval<T>()))>> = true;
152

153
template <typename, typename = void>
154
constexpr bool has_std_to_string = false;
155
template <typename T>
156
constexpr bool has_std_to_string<T, std::void_t<decltype(std::to_string(std::declval<T>()))>> = true;
157

158
template <typename, typename = void>
159
constexpr bool has_ostream_operator = false;
160
template <typename T>
161
constexpr bool
162
   has_ostream_operator<T, std::void_t<decltype(operator<<(std::declval<std::ostringstream&>(), std::declval<T>()))>> =
163
      true;
164

165
template <typename T>
166
struct is_optional : std::false_type {};
167

168
template <typename T>
169
struct is_optional<std::optional<T>> : std::true_type {};
170

171
template <typename T>
172
constexpr bool is_optional_v = is_optional<T>::value;
173

174
}  // namespace detail
175

176
/**
177
 * A code location consisting of the source file path and a line
178
 */
179
struct CodeLocation {
470,119✔
180
      std::string path;
181
      unsigned int line;
182
};
183

184
/*
185
* A generic test which returns a set of results when run.
186
* The tests may not all have the same type (for example test
187
* "block" returns results for "AES-128" and "AES-256").
188
*
189
* For most test cases you want Text_Based_Test derived below
190
*/
191
class Test {
311✔
192
   public:
193
      /*
194
      * Some number of test results, all associated with who()
195
      */
196
      class Result final {
197
         public:
198
            explicit Result(std::string who) : m_who(std::move(who)), m_timestamp(std::chrono::system_clock::now()) {}
125,968✔
199

200
            /**
201
             * This 'consolidation constructor' creates a single test result from
202
             * a vector of downstream test result objects.
203
             */
204
            Result(std::string who, const std::vector<Result>& downstream_results);
205

206
            size_t tests_passed() const { return m_tests_passed; }
8,304✔
207

208
            size_t tests_failed() const { return m_fail_log.size(); }
60,273✔
209

210
            size_t tests_run() const { return tests_passed() + tests_failed(); }
8,304✔
211

212
            bool any_results() const { return tests_run() > 0; }
213

214
            const std::string& who() const { return m_who; }
201,172✔
215

216
            const std::vector<std::string>& failures() const { return m_fail_log; }
1,656✔
217

218
            const std::vector<std::string>& notes() const { return m_log; }
1,656✔
219

220
            std::optional<std::chrono::nanoseconds> elapsed_time() const {
1,656✔
221
               if(m_ns_taken == 0) {
1,656✔
222
                  return std::nullopt;
223
               } else {
224
                  return std::chrono::nanoseconds(m_ns_taken);
978✔
225
               }
226
            }
227

228
            const std::chrono::system_clock::time_point& timestamp() const { return m_timestamp; }
1,656✔
229

230
            std::string result_string() const;
231

232
            static Result Failure(const std::string& who, const std::string& what) {
1✔
233
               Result r(who);
1✔
234
               r.test_failure(what);
1✔
235
               return r;
1✔
236
            }
×
237

238
            static Result Note(const std::string& who, const std::string& what) {
×
239
               Result r(who);
×
240
               r.test_note(what);
×
241
               return r;
×
242
            }
×
243

244
            static Result OfExpectedFailure(bool expecting_failure, const Test::Result& result) {
245
               if(!expecting_failure) {
246
                  return result;
247
               }
248

249
               if(result.tests_failed() == 0) {
250
                  Result r = result;
251
                  r.test_failure("Expected this test to fail, but it did not");
252
                  return r;
253
               } else {
254
                  Result r(result.who());
255
                  r.test_note("Got expected failure");
256
                  return r;
257
               }
258
            }
259

260
            void merge(const Result& other, bool ignore_test_name = false);
261

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

264
            template <typename Alloc>
265
            void test_note(const std::string& who, const std::vector<uint8_t, Alloc>& vec) {
12✔
266
               const std::string hex = Botan::hex_encode(vec);
12✔
267
               return test_note(who, hex.c_str());
12✔
268
            }
12✔
269

270
            void note_missing(const std::string& thing);
271

272
            bool test_success(const std::string& note = "");
273

274
            bool test_failure(const std::string& err);
275

276
            bool test_failure(const std::string& what, const std::string& error);
277

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

280
            template <typename Alloc>
281
            void test_failure(const std::string& what, const std::vector<uint8_t, Alloc>& buf) {
1✔
282
               test_failure(what, buf.data(), buf.size());
1✔
283
            }
1✔
284

285
            bool confirm(const std::string& what, bool expr, bool expected = true) {
125,364✔
286
               return test_eq(what, expr, expected);
125,215✔
287
            }
288

289
            /**
290
             * Require a condition, throw Test_Aborted otherwise
291
             * Note: works best when combined with CHECK scopes!
292
             */
293
            void require(const std::string& what, bool expr, bool expected = true) {
149✔
294
               if(!confirm(what, expr, expected)) {
149✔
295
                  throw Test_Aborted("test aborted, because required condition was not met: " + what);
×
296
               }
297
            }
149✔
298

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

304
            template <typename T>
305
            bool test_is_eq(const std::string& what, const T& produced, const T& expected) {
479,541✔
306
               std::ostringstream out;
479,541✔
307
               out << m_who << " " << what;
479,541✔
308

309
               if(produced == expected) {
479,532✔
310
                  out << " produced expected result";
479,539✔
311
                  return test_success(out.str());
959,078✔
312
               } else {
313
                  out << " produced unexpected result '" << to_string(produced) << "' expected '" << to_string(expected)
314
                      << "'";
7✔
315
                  return test_failure(out.str());
4✔
316
               }
317
            }
479,541✔
318

319
            template <typename T>
320
            bool test_not_null(const std::string& what, const T& ptr) {
25✔
321
               if(ptr == nullptr)
25✔
322
                  return test_failure(what + " was null");
×
323
               else
324
                  return test_success(what + " was not null");
50✔
325
            }
326

327
            template <typename T>
328
            bool test_not_nullopt(const std::string& what, std::optional<T> val) {
9✔
329
               if(val == std::nullopt)
9✔
330
                  return test_failure(what + " was nullopt");
×
331
               else
332
                  return test_success(what + " was not nullopt");
18✔
333
            }
334

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

337
            bool test_is_nonempty(const std::string& what_is_it, const std::string& to_examine);
338

339
            bool test_eq(const std::string& what, const std::string& produced, const std::string& expected);
340

341
            bool test_eq(const std::string& what, bool produced, bool expected);
342

343
            bool test_eq(const std::string& what, size_t produced, size_t expected);
344
            bool test_eq_sz(const std::string& what, size_t produced, size_t expected);
345

346
            bool test_eq(const std::string& what,
347
                         const Botan::OctetString& produced,
348
                         const Botan::OctetString& expected);
349

350
            template <typename I1, typename I2>
351
            bool test_int_eq(I1 x, I2 y, const char* what) {
52✔
352
               return test_eq(what, static_cast<size_t>(x), static_cast<size_t>(y));
68✔
353
            }
354

355
            template <typename I1, typename I2>
356
            bool test_int_eq(const std::string& what, I1 x, I2 y) {
3,889✔
357
               return test_eq(what.c_str(), static_cast<size_t>(x), static_cast<size_t>(y));
7,730✔
358
            }
359

360
            bool test_lt(const std::string& what, size_t produced, size_t expected);
361
            bool test_lte(const std::string& what, size_t produced, size_t expected);
362
            bool test_gt(const std::string& what, size_t produced, size_t expected);
363
            bool test_gte(const std::string& what, size_t produced, size_t expected);
364

365
            template <typename T>
366
            bool test_rc_ok(const std::string& func, T rc) {
874✔
367
               static_assert(std::is_integral<T>::value, "Integer required.");
368

369
               if(rc != 0) {
874✔
370
                  std::ostringstream err;
1✔
371
                  err << m_who;
1✔
372
                  err << " " << func;
1✔
373
                  err << " unexpectedly failed with error code " << rc;
1✔
374
                  return test_failure(err.str());
1✔
375
               }
1✔
376

377
               return test_success();
873✔
378
            }
379

380
            template <typename T>
381
            bool test_rc_fail(const std::string& func, const std::string& why, T rc) {
22✔
382
               static_assert(std::is_integral<T>::value, "Integer required.");
383

384
               if(rc == 0) {
22✔
385
                  std::ostringstream err;
1✔
386
                  err << m_who;
1✔
387
                  err << " call to " << func << " unexpectedly succeeded";
1✔
388
                  err << " expecting failure because " << why;
1✔
389
                  return test_failure(err.str());
1✔
390
               }
1✔
391

392
               return test_success();
21✔
393
            }
394

395
            bool test_rc(const std::string& func, int expected, int rc);
396

397
            bool test_rc_init(const std::string& func, int rc);
398

399
            bool test_ne(const std::string& what, size_t produced, size_t expected);
400

401
            bool test_ne(const std::string& what, const std::string& str1, const std::string& str2);
402

403
#if defined(BOTAN_HAS_BIGINT)
404
            bool test_eq(const std::string& what, const BigInt& produced, const BigInt& expected);
405
            bool test_ne(const std::string& what, const BigInt& produced, const BigInt& expected);
406
#endif
407

408
#if defined(BOTAN_HAS_EC_CURVE_GFP)
409
            bool test_eq(const std::string& what, const Botan::EC_Point& a, const Botan::EC_Point& b);
410
#endif
411

412
            bool test_eq(const char* producer,
413
                         const std::string& what,
414
                         const uint8_t produced[],
415
                         size_t produced_len,
416
                         const uint8_t expected[],
417
                         size_t expected_len);
418

419
            bool test_ne(const std::string& what,
420
                         const uint8_t produced[],
421
                         size_t produced_len,
422
                         const uint8_t expected[],
423
                         size_t expected_len);
424

425
            template <typename Alloc1, typename Alloc2>
426
            bool test_eq(const std::string& what,
42,324✔
427
                         const std::vector<uint8_t, Alloc1>& produced,
428
                         const std::vector<uint8_t, Alloc2>& expected) {
429
               return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
42,324✔
430
            }
431

432
            template <typename Alloc1, typename Alloc2>
433
            bool test_eq(const std::string& producer,
92,434✔
434
                         const std::string& what,
435
                         const std::vector<uint8_t, Alloc1>& produced,
436
                         const std::vector<uint8_t, Alloc2>& expected) {
437
               return test_eq(
92,434✔
438
                  producer.c_str(), what, produced.data(), produced.size(), expected.data(), expected.size());
92,434✔
439
            }
440

441
            template <typename Alloc>
442
            bool test_eq(const std::string& what,
405✔
443
                         const std::vector<uint8_t, Alloc>& produced,
444
                         const char* expected_hex) {
445
               const std::vector<uint8_t> expected = Botan::hex_decode(expected_hex);
405✔
446
               return test_eq(nullptr, what, produced.data(), produced.size(), expected.data(), expected.size());
405✔
447
            }
405✔
448

449
            template <typename Alloc1, typename Alloc2>
450
            bool test_ne(const std::string& what,
1,945✔
451
                         const std::vector<uint8_t, Alloc1>& produced,
452
                         const std::vector<uint8_t, Alloc2>& expected) {
453
               return test_ne(what, produced.data(), produced.size(), expected.data(), expected.size());
1,945✔
454
            }
455

456
         private:
457
            class ThrowExpectations {
458
               public:
459
                  ThrowExpectations(std::function<void()> fn) :
46,065✔
460
                        m_fn(std::move(fn)), m_expect_success(false), m_consumed(false) {}
92,087✔
461

462
                  ThrowExpectations(const ThrowExpectations&) = delete;
463
                  ThrowExpectations& operator=(const ThrowExpectations&) = delete;
464
                  ThrowExpectations(ThrowExpectations&&) = default;
465
                  ThrowExpectations& operator=(ThrowExpectations&&) = default;
466

467
                  ~ThrowExpectations() { BOTAN_ASSERT_NOMSG(m_consumed); }
46,065✔
468

469
                  ThrowExpectations& expect_success() {
61✔
470
                     BOTAN_ASSERT_NOMSG(!m_expected_message && !m_expected_exception_type);
61✔
471
                     m_expect_success = true;
61✔
472
                     return *this;
61✔
473
                  }
474

475
                  ThrowExpectations& expect_message(const std::string& message) {
169✔
476
                     BOTAN_ASSERT_NOMSG(!m_expect_success);
169✔
477
                     m_expected_message = message;
169✔
478
                     return *this;
169✔
479
                  }
480

481
                  template <typename ExT>
482
                  ThrowExpectations& expect_exception_type() {
43✔
483
                     BOTAN_ASSERT_NOMSG(!m_expect_success);
43✔
484
                     m_expected_exception_type = typeid(ExT);
43✔
485
                     return *this;
43✔
486
                  }
487

488
                  bool check(const std::string& test_name, Test::Result& result);
489

490
               private:
491
                  std::function<void()> m_fn;
492
                  bool m_expect_success;
493
                  std::optional<std::string> m_expected_message;
494
                  std::optional<std::type_index> m_expected_exception_type;
495
                  bool m_consumed;
496
            };
497

498
         public:
499
            bool test_throws(const std::string& what, const std::function<void()>& fn);
500

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

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

505
            template <typename ExceptionT>
506
            bool test_throws(const std::string& what, const std::function<void()>& fn) {
28✔
507
               return ThrowExpectations(fn).expect_exception_type<ExceptionT>().check(what, *this);
56✔
508
            }
509

510
            template <typename ExceptionT>
511
            bool test_throws(const std::string& what, const std::string& expected, const std::function<void()>& fn) {
15✔
512
               return ThrowExpectations(fn).expect_exception_type<ExceptionT>().expect_message(expected).check(what,
30✔
513
                                                                                                               *this);
15✔
514
            }
515

516
            void set_ns_consumed(uint64_t ns) { m_ns_taken = ns; }
43,643✔
517

518
            void start_timer();
519
            void end_timer();
520

521
            void set_code_location(CodeLocation where) { m_where = std::move(where); }
45,172✔
522

523
            const std::optional<CodeLocation>& code_location() const { return m_where; }
46,828✔
524

525
         private:
526
            template <typename T>
527
            std::string to_string(const T& v) {
2✔
528
               if constexpr(detail::is_optional_v<T>)
529
                  return (v.has_value()) ? to_string(v.value()) : std::string("std::nullopt");
×
530
               else if constexpr(detail::has_Botan_to_string<T>)
531
                  return Botan::to_string(v);
×
532
               else if constexpr(detail::has_ostream_operator<T>) {
533
                  std::ostringstream oss;
2✔
534
                  oss << v;
2✔
535
                  return oss.str();
2✔
536
               } else if constexpr(detail::has_std_to_string<T>)
2✔
537
                  return std::to_string(v);
2✔
538
               else
539
                  return "<?>";
×
540
            }
541

542
         private:
543
            std::string m_who;
544
            std::optional<CodeLocation> m_where;
545
            std::chrono::system_clock::time_point m_timestamp;
546
            uint64_t m_started = 0;
547
            uint64_t m_ns_taken = 0;
548
            size_t m_tests_passed = 0;
549
            std::vector<std::string> m_fail_log;
550
            std::vector<std::string> m_log;
551
      };
552

553
      virtual ~Test() = default;
×
554
      virtual std::vector<Test::Result> run() = 0;
555

556
      virtual std::vector<std::string> possible_providers(const std::string&);
557

558
      void set_registration_location(CodeLocation location) { m_registration_location = std::move(location); }
312✔
559

560
      const std::optional<CodeLocation>& registration_location() const { return m_registration_location; }
45,172✔
561

562
      /// @p smoke_test are run first in an unfiltered test run
563
      static void register_test(std::string category,
564
                                std::string name,
565
                                bool smoke_test,
566
                                bool needs_serialization,
567
                                std::function<std::unique_ptr<Test>()> maker_fn);
568

569
      static std::set<std::string> registered_tests();
570
      static std::set<std::string> registered_test_categories();
571
      static std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
572
                                                              const std::set<std::string>& to_be_skipped);
573

574
      static std::unique_ptr<Test> get_test(const std::string& test_name);
575
      static bool test_needs_serialization(const std::string& test_name);
576

577
      static std::string data_file(const std::string& what);
578
      static std::string data_file_as_temporary_copy(const std::string& what);
579

580
      static std::string format_time(uint64_t nanoseconds);
581

582
      static std::string format_time(const std::chrono::nanoseconds nanoseconds) {
1✔
583
         return format_time(nanoseconds.count());
1✔
584
      }
585

586
      template <typename Alloc>
587
      static std::vector<uint8_t, Alloc> mutate_vec(const std::vector<uint8_t, Alloc>& v,
67,191✔
588
                                                    bool maybe_resize = false,
589
                                                    size_t min_offset = 0) {
590
         auto& rng = Test::rng();
67,191✔
591

592
         std::vector<uint8_t, Alloc> r = v;
67,191✔
593

594
         if(maybe_resize && (r.empty() || rng.next_byte() < 32)) {
71,513✔
595
            // TODO: occasionally truncate, insert at random index
596
            const size_t add = 1 + (rng.next_byte() % 16);
877✔
597
            r.resize(r.size() + add);
877✔
598
            rng.randomize(&r[r.size() - add], add);
68,068✔
599
         }
600

601
         if(r.size() > min_offset) {
67,191✔
602
            const size_t offset = std::max<size_t>(min_offset, rng.next_byte() % r.size());
65,791✔
603
            const uint8_t perturb = rng.next_nonzero_byte();
65,791✔
604
            r[offset] ^= perturb;
65,791✔
605
         }
606

607
         return r;
67,191✔
608
      }
×
609

610
      static void set_test_options(const Test_Options& opts);
611

612
      static void set_test_rng(std::shared_ptr<Botan::RandomNumberGenerator> rng);
613

614
      static const Test_Options& options() { return m_opts; }
615

616
      static bool run_long_tests() { return options().run_long_tests(); }
2,334✔
617

618
      static bool run_memory_intensive_tests() { return options().run_memory_intensive_tests(); }
1✔
619

620
      static const std::string& data_dir() { return options().data_dir(); }
442✔
621

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

624
      static std::string temp_file_name(const std::string& basename);
625
      static bool copy_file(const std::string& from, const std::string& to);
626

627
      static std::vector<std::string> provider_filter(const std::vector<std::string>& providers);
628

629
      static std::string read_data_file(const std::string& path);
630
      static std::vector<uint8_t> read_binary_data_file(const std::string& path);
631

632
      static Botan::RandomNumberGenerator& rng();
633
      static std::shared_ptr<Botan::RandomNumberGenerator> rng_as_shared();
634
      static std::string random_password();
635
      static uint64_t timestamp();  // nanoseconds arbitrary epoch
636

637
      static std::vector<Test::Result> flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists);
638

639
   private:
640
      static Test_Options m_opts;
641
      static std::shared_ptr<Botan::RandomNumberGenerator> m_test_rng;
642

643
      std::optional<CodeLocation> m_registration_location;  /// The source file location where the test was registered
644
};
645

646
/*
647
* Register the test with the runner
648
*/
649
template <typename Test_Class>
650
class TestClassRegistration {
651
   public:
652
      TestClassRegistration(std::string category,
297✔
653
                            std::string name,
654
                            bool smoke_test,
655
                            bool needs_serialization,
656
                            CodeLocation registration_location) {
657
         Test::register_test(std::move(category), std::move(name), smoke_test, needs_serialization, [=] {
2,337✔
658
            auto test = std::make_unique<Test_Class>();
297✔
659
            test->set_registration_location(registration_location);
297✔
660
            return test;
297✔
661
         });
×
662
      }
297✔
663
};
664

665
#define BOTAN_REGISTER_TEST(category, name, Test_Class) \
666
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, false, {__FILE__, __LINE__})
667
#define BOTAN_REGISTER_SERIALIZED_TEST(category, name, Test_Class) \
668
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, false, true, {__FILE__, __LINE__})
669
#define BOTAN_REGISTER_SMOKE_TEST(category, name, Test_Class) \
670
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, false, {__FILE__, __LINE__})
671
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST(category, name, Test_Class) \
672
   const TestClassRegistration<Test_Class> reg_##Test_Class##_tests(category, name, true, true, {__FILE__, __LINE__})
673

674
typedef Test::Result (*test_fn)();
675
typedef std::vector<Test::Result> (*test_fn_vec)();
676

677
class FnTest : public Test {
678
   private:
679
      using TestFnVariant = std::variant<test_fn, test_fn_vec>;
680

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

690
      template <typename TestFn, typename... TestFns>
691
      std::vector<TestFnVariant> make_variant_vector(const TestFn& fn, const TestFns&... fns) {
23✔
692
         auto functions = make_variant_vector(fns...);
23✔
693
         functions.emplace_back(fn);
23✔
694
         return functions;
23✔
695
      }
×
696

697
   public:
698
      template <typename... TestFns>
699
      FnTest(TestFns... fns) : m_fns(make_variant_vector(fns...)) {}
15✔
700

701
      std::vector<Test::Result> run() override {
15✔
702
         std::vector<Test::Result> result;
15✔
703

704
         for(auto fn_variant = m_fns.crbegin(); fn_variant != m_fns.crend(); ++fn_variant) {
53✔
705
            std::visit(
76✔
706
               [&](auto&& fn) {
38✔
707
                  using T = std::decay_t<decltype(fn)>;
708
                  if constexpr(std::is_same_v<T, test_fn>) {
709
                     result.emplace_back(fn());
38✔
710
                  } else {
711
                     const auto results = fn();
34✔
712
                     result.insert(result.end(), results.begin(), results.end());
34✔
713
                  }
34✔
714
               },
38✔
715
               *fn_variant);
38✔
716
         }
717

718
         return result;
15✔
719
      }
×
720

721
   private:
722
      std::vector<TestFnVariant> m_fns;
723
};
724

725
class TestFnRegistration {
726
   public:
727
      template <typename... TestFns>
728
      TestFnRegistration(std::string category,
15✔
729
                         std::string name,
730
                         bool smoke_test,
731
                         bool needs_serialization,
732
                         CodeLocation registration_location,
733
                         TestFns... fn) {
734
         Test::register_test(std::move(category), std::move(name), smoke_test, needs_serialization, [=] {
104✔
735
            auto test = std::make_unique<FnTest>(fn...);
15✔
736
            test->set_registration_location(std::move(registration_location));
15✔
737
            return test;
15✔
738
         });
×
739
      }
15✔
740
};
741

742
#define BOTAN_REGISTER_TEST_FN(category, name, ...) \
743
   static const TestFnRegistration reg_##fn_name(category, name, false, false, {__FILE__, __LINE__}, __VA_ARGS__)
744
#define BOTAN_REGISTER_SMOKE_TEST_FN(category, name, ...) \
745
   static const TestFnRegistration reg_##fn_name(category, name, true, false, {__FILE__, __LINE__}, __VA_ARGS__)
746
#define BOTAN_REGISTER_SERIALIZED_TEST_FN(category, name, ...) \
747
   static const TestFnRegistration reg_##fn_name(category, name, false, true {__FILE__, __LINE__}, __VA_ARGS__)
748
#define BOTAN_REGISTER_SERIALIZED_SMOKE_TEST_FN(category, name, ...) \
749
   static const TestFnRegistration reg_##fn_name(category, name, true, true {__FILE__, __LINE__}, __VA_ARGS__)
750

751
class VarMap {
294✔
752
   public:
753
      void clear() { m_vars.clear(); }
29,825✔
754

755
      void add(const std::string& key, const std::string& value) { m_vars[key] = value; }
139,597✔
756

757
      bool has_key(const std::string& key) const { return m_vars.count(key) == 1; }
392,403✔
758

759
      bool get_req_bool(const std::string& key) const;
760

761
      std::vector<uint8_t> get_req_bin(const std::string& key) const;
762
      std::vector<uint8_t> get_opt_bin(const std::string& key) const;
763

764
      std::vector<std::vector<uint8_t>> get_req_bin_list(const std::string& key) const;
765

766
#if defined(BOTAN_HAS_BIGINT)
767
      Botan::BigInt get_req_bn(const std::string& key) const;
768
      Botan::BigInt get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const;
769
#endif
770

771
      std::string get_req_str(const std::string& key) const;
772
      std::string get_opt_str(const std::string& key, const std::string& def_value) const;
773

774
      size_t get_req_sz(const std::string& key) const;
775

776
      uint8_t get_req_u8(const std::string& key) const;
777
      uint32_t get_req_u32(const std::string& key) const;
778
      uint64_t get_req_u64(const std::string& key) const;
779

780
      size_t get_opt_sz(const std::string& key, const size_t def_value) const;
781

782
      uint64_t get_opt_u64(const std::string& key, const uint64_t def_value) const;
783

784
   private:
785
      std::unordered_map<std::string, std::string> m_vars;
786
};
787

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

809
      virtual bool clear_between_callbacks() const { return true; }
29,235✔
810

811
      std::vector<Test::Result> run() override;
812

813
   protected:
814
      std::string get_next_line();
815

816
      virtual Test::Result run_one_test(const std::string& header, const VarMap& vars) = 0;
817
      // Called before run_one_test
818
      virtual bool skip_this_test(const std::string& header, const VarMap& vars);
819

820
      virtual std::vector<Test::Result> run_final_tests() { return std::vector<Test::Result>(); }
138✔
821

822
   private:
823
      std::string m_data_src;
824
      std::set<std::string> m_required_keys;
825
      std::set<std::string> m_optional_keys;
826
      std::string m_output_key;
827

828
      bool m_first = true;
829
      std::unique_ptr<std::istream> m_cur;
830
      std::string m_cur_src_name;
831
      std::deque<std::string> m_srcs;
832
      std::vector<uint64_t> m_cpu_flags;
833
};
834

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

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

876
   return r;
272✔
877
}
×
878

879
}  // namespace Botan_Tests
880

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