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

randombit / botan / 5123321399

30 May 2023 04:06PM UTC coverage: 92.213% (+0.004%) from 92.209%
5123321399

Pull #3558

github

web-flow
Merge dd72f7389 into 057bcbc35
Pull Request #3558: Add braces around all if/else statements

75602 of 81986 relevant lines covered (92.21%)

11859779.3 hits per line

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

80.6
/src/tests/tests.cpp
1
/*
2
* (C) 2014,2015 Jack Lloyd
3
*
4
* Botan is released under the Simplified BSD License (see license.txt)
5
*/
6

7
#include "tests.h"
8

9
#include <botan/hex.h>
10
#include <botan/internal/cpuid.h>
11
#include <botan/internal/filesystem.h>
12
#include <botan/internal/parsing.h>
13
#include <botan/internal/stl_util.h>
14
#include <fstream>
15
#include <iomanip>
16
#include <sstream>
17

18
#if defined(BOTAN_HAS_BIGINT)
19
   #include <botan/bigint.h>
20
#endif
21

22
#if defined(BOTAN_HAS_EC_CURVE_GFP)
23
   #include <botan/ec_point.h>
24
#endif
25

26
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
27
   #include <stdlib.h>
28
   #include <unistd.h>
29
#endif
30

31
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)
32
   #include <version>
33
   #if defined(__cpp_lib_filesystem)
34
      #include <filesystem>
35
   #endif
36
#endif
37

38
namespace Botan_Tests {
39

40
void Test::Result::merge(const Result& other, bool ignore_test_name) {
104,789✔
41
   if(who() != other.who()) {
104,789✔
42
      if(!ignore_test_name) {
48✔
43
         throw Test_Error("Merging tests from different sources");
×
44
      }
45

46
      // When deliberately merging results with different names, the code location is
47
      // likely inconsistent and must be discarded.
48
      m_where.reset();
48✔
49
   } else {
50
      m_where = other.m_where;
104,741✔
51
   }
52

53
   m_timestamp = std::min(m_timestamp, other.m_timestamp);
104,789✔
54
   m_ns_taken += other.m_ns_taken;
104,789✔
55
   m_tests_passed += other.m_tests_passed;
104,789✔
56
   m_fail_log.insert(m_fail_log.end(), other.m_fail_log.begin(), other.m_fail_log.end());
104,789✔
57
   m_log.insert(m_log.end(), other.m_log.begin(), other.m_log.end());
104,789✔
58
}
104,789✔
59

60
void Test::Result::start_timer() {
744✔
61
   if(m_started == 0) {
744✔
62
      m_started = Test::timestamp();
744✔
63
   }
64
}
744✔
65

66
void Test::Result::end_timer() {
828✔
67
   if(m_started > 0) {
828✔
68
      m_ns_taken += Test::timestamp() - m_started;
1,486✔
69
      m_started = 0;
743✔
70
   }
71
}
828✔
72

73
void Test::Result::test_note(const std::string& note, const char* extra) {
2,677✔
74
   if(!note.empty()) {
2,677✔
75
      std::ostringstream out;
2,677✔
76
      out << who() << " " << note;
2,677✔
77
      if(extra) {
2,677✔
78
         out << ": " << extra;
12✔
79
      }
80
      m_log.push_back(out.str());
2,677✔
81
   }
2,677✔
82
}
2,677✔
83

84
void Test::Result::note_missing(const std::string& whatever) {
275✔
85
   static std::set<std::string> s_already_seen;
275✔
86

87
   if(!s_already_seen.contains(whatever)) {
275✔
88
      test_note("Skipping tests due to missing " + whatever);
5✔
89
      s_already_seen.insert(whatever);
5✔
90
   }
91
}
275✔
92

93
bool Test::Result::ThrowExpectations::check(const std::string& test_name, Test::Result& result) {
46,055✔
94
   m_consumed = true;
46,055✔
95

96
   try {
46,055✔
97
      m_fn();
46,055✔
98
      if(!m_expect_success) {
62✔
99
         return result.test_failure(test_name + " failed to throw expected exception");
4✔
100
      }
101
   } catch(const std::exception& ex) {
45,993✔
102
      if(m_expect_success) {
45,991✔
103
         return result.test_failure(test_name + " threw unexpected exception: " + ex.what());
2✔
104
      }
105
      if(m_expected_exception_type.has_value() && m_expected_exception_type.value() != typeid(ex)) {
45,990✔
106
         return result.test_failure(test_name + " threw unexpected exception: " + ex.what());
4✔
107
      }
108
      if(m_expected_message.has_value() && m_expected_message.value() != ex.what()) {
45,988✔
109
         return result.test_failure(test_name + " threw exception with unexpected message (expected: '" +
3✔
110
                                    m_expected_message.value() + "', got: '" + ex.what() + "')");
3✔
111
      }
112
   } catch(...) {
45,993✔
113
      if(m_expect_success || m_expected_exception_type.has_value() || m_expected_message.has_value()) {
2✔
114
         return result.test_failure(test_name + " threw unexpected unknown exception");
1✔
115
      }
116
   }
2✔
117

118
   return result.test_success(test_name + " behaved as expected");
92,096✔
119
}
120

121
bool Test::Result::test_throws(const std::string& what, const std::function<void()>& fn) {
45,797✔
122
   return ThrowExpectations(fn).check(what, *this);
91,594✔
123
}
124

125
bool Test::Result::test_throws(const std::string& what, const std::string& expected, const std::function<void()>& fn) {
154✔
126
   return ThrowExpectations(fn).expect_message(expected).check(what, *this);
308✔
127
}
128

129
bool Test::Result::test_no_throw(const std::string& what, const std::function<void()>& fn) {
61✔
130
   return ThrowExpectations(fn).expect_success().check(what, *this);
122✔
131
}
132

133
bool Test::Result::test_success(const std::string& note) {
2,985,320✔
134
   if(Test::options().log_success()) {
2,985,213✔
135
      test_note(note);
×
136
   }
137
   ++m_tests_passed;
2,985,320✔
138
   return true;
398,933✔
139
}
140

141
bool Test::Result::test_failure(const std::string& what, const std::string& error) {
1✔
142
   return test_failure(who() + " " + what + " with error " + error);
2✔
143
}
144

145
void Test::Result::test_failure(const std::string& what, const uint8_t buf[], size_t buf_len) {
1✔
146
   test_failure(who() + ": " + what + " buf len " + std::to_string(buf_len) + " value " +
2✔
147
                Botan::hex_encode(buf, buf_len));
1✔
148
}
1✔
149

150
bool Test::Result::test_failure(const std::string& err) {
25✔
151
   m_fail_log.push_back(err);
25✔
152

153
   if(Test::options().abort_on_first_fail() && m_who != "Failing Test") {
25✔
154
      std::abort();
×
155
   }
156
   return false;
25✔
157
}
158

159
bool Test::Result::test_ne(const std::string& what,
1,942✔
160
                           const uint8_t produced[],
161
                           size_t produced_len,
162
                           const uint8_t expected[],
163
                           size_t expected_len) {
164
   if(produced_len == expected_len && Botan::same_mem(produced, expected, expected_len)) {
2,137✔
165
      return test_failure(who() + ": " + what + " produced matching");
4✔
166
   }
167
   return test_success();
3,880✔
168
}
169

170
bool Test::Result::test_eq(const char* producer,
169,020✔
171
                           const std::string& what,
172
                           const uint8_t produced[],
173
                           size_t produced_size,
174
                           const uint8_t expected[],
175
                           size_t expected_size) {
176
   if(produced_size == expected_size && Botan::same_mem(produced, expected, expected_size)) {
338,039✔
177
      return test_success();
338,038✔
178
   }
179

180
   std::ostringstream err;
1✔
181

182
   err << who();
1✔
183

184
   if(producer) {
1✔
185
      err << " producer '" << producer << "'";
×
186
   }
187

188
   err << " unexpected result for " << what;
1✔
189

190
   if(produced_size != expected_size) {
1✔
191
      err << " produced " << produced_size << " bytes expected " << expected_size;
1✔
192
   }
193

194
   std::vector<uint8_t> xor_diff(std::min(produced_size, expected_size));
2✔
195
   size_t bytes_different = 0;
1✔
196

197
   for(size_t i = 0; i != xor_diff.size(); ++i) {
4✔
198
      xor_diff[i] = produced[i] ^ expected[i];
3✔
199
      bytes_different += (xor_diff[i] > 0);
3✔
200
   }
201

202
   err << "\nProduced: " << Botan::hex_encode(produced, produced_size)
1✔
203
       << "\nExpected: " << Botan::hex_encode(expected, expected_size);
3✔
204

205
   if(bytes_different > 0) {
1✔
206
      err << "\nXOR Diff: " << Botan::hex_encode(xor_diff);
1✔
207
   }
208

209
   return test_failure(err.str());
2✔
210
}
1✔
211

212
bool Test::Result::test_is_nonempty(const std::string& what_is_it, const std::string& to_examine) {
29,010✔
213
   if(to_examine.empty()) {
29,010✔
214
      return test_failure(what_is_it + " was empty");
1✔
215
   }
216
   return test_success();
58,018✔
217
}
218

219
bool Test::Result::test_eq(const std::string& what, const std::string& produced, const std::string& expected) {
61,162✔
220
   return test_is_eq(what, produced, expected);
61,162✔
221
}
222

223
bool Test::Result::test_eq(const std::string& what, const char* produced, const char* expected) {
20✔
224
   return test_is_eq(what, std::string(produced), std::string(expected));
34✔
225
}
226

227
bool Test::Result::test_eq(const std::string& what, size_t produced, size_t expected) {
125,385✔
228
   return test_is_eq(what, produced, expected);
125,385✔
229
}
230

231
bool Test::Result::test_eq_sz(const std::string& what, size_t produced, size_t expected) {
665✔
232
   return test_is_eq(what, produced, expected);
665✔
233
}
234

235
bool Test::Result::test_eq(const std::string& what,
107✔
236
                           const Botan::OctetString& produced,
237
                           const Botan::OctetString& expected) {
238
   std::ostringstream out;
107✔
239
   out << m_who << " " << what;
107✔
240

241
   if(produced == expected) {
107✔
242
      out << " produced expected result " << produced.to_string();
214✔
243
      return test_success(out.str());
214✔
244
   } else {
245
      out << " produced unexpected result '" << produced.to_string() << "' expected '" << expected.to_string() << "'";
×
246
      return test_failure(out.str());
×
247
   }
248
}
107✔
249

250
bool Test::Result::test_lt(const std::string& what, size_t produced, size_t expected) {
4,928✔
251
   if(produced >= expected) {
4,928✔
252
      std::ostringstream err;
1✔
253
      err << m_who << " " << what;
1✔
254
      err << " unexpected result " << produced << " >= " << expected;
1✔
255
      return test_failure(err.str());
1✔
256
   }
1✔
257

258
   return test_success();
9,854✔
259
}
260

261
bool Test::Result::test_lte(const std::string& what, size_t produced, size_t expected) {
1,017,710✔
262
   if(produced > expected) {
1,017,710✔
263
      std::ostringstream err;
1✔
264
      err << m_who << " " << what << " unexpected result " << produced << " > " << expected;
1✔
265
      return test_failure(err.str());
1✔
266
   }
1✔
267

268
   return test_success();
2,035,418✔
269
}
270

271
bool Test::Result::test_gte(const std::string& what, size_t produced, size_t expected) {
1,129,925✔
272
   if(produced < expected) {
1,129,925✔
273
      std::ostringstream err;
1✔
274
      err << m_who;
1✔
275
      err << " " << what;
1✔
276
      err << " unexpected result " << produced << " < " << expected;
1✔
277
      return test_failure(err.str());
1✔
278
   }
1✔
279

280
   return test_success();
2,259,848✔
281
}
282

283
bool Test::Result::test_gt(const std::string& what, size_t produced, size_t expected) {
14,382✔
284
   if(produced <= expected) {
14,382✔
285
      std::ostringstream err;
×
286
      err << m_who;
×
287
      err << " " << what;
×
288
      err << " unexpected result " << produced << " <= " << expected;
×
289
      return test_failure(err.str());
×
290
   }
×
291

292
   return test_success();
28,764✔
293
}
294

295
bool Test::Result::test_ne(const std::string& what, const std::string& str1, const std::string& str2) {
25✔
296
   if(str1 != str2) {
25✔
297
      return test_success(str1 + " != " + str2);
63✔
298
   }
299

300
   return test_failure(who() + " " + what + " produced matching strings " + str1);
2✔
301
}
302

303
bool Test::Result::test_ne(const std::string& what, size_t produced, size_t expected) {
9✔
304
   if(produced != expected) {
9✔
305
      return test_success();
16✔
306
   }
307

308
   std::ostringstream err;
1✔
309
   err << who() << " " << what << " produced " << produced << " unexpected value";
1✔
310
   return test_failure(err.str());
1✔
311
}
1✔
312

313
#if defined(BOTAN_HAS_BIGINT)
314
bool Test::Result::test_eq(const std::string& what, const BigInt& produced, const BigInt& expected) {
10,523✔
315
   return test_is_eq(what, produced, expected);
10,523✔
316
}
317

318
bool Test::Result::test_ne(const std::string& what, const BigInt& produced, const BigInt& expected) {
96✔
319
   if(produced != expected) {
96✔
320
      return test_success();
190✔
321
   }
322

323
   std::ostringstream err;
1✔
324
   err << who() << " " << what << " produced " << produced << " prohibited value";
1✔
325
   return test_failure(err.str());
1✔
326
}
1✔
327
#endif
328

329
#if defined(BOTAN_HAS_EC_CURVE_GFP)
330
bool Test::Result::test_eq(const std::string& what, const Botan::EC_Point& a, const Botan::EC_Point& b) {
3,135✔
331
   //return test_is_eq(what, a, b);
332
   if(a == b) {
3,135✔
333
      return test_success();
6,270✔
334
   }
335

336
   std::ostringstream err;
×
337
   err << who() << " " << what << " a=(" << a.get_affine_x() << "," << a.get_affine_y() << ")"
×
338
       << " b=(" << b.get_affine_x() << "," << b.get_affine_y();
×
339
   return test_failure(err.str());
×
340
}
×
341
#endif
342

343
bool Test::Result::test_eq(const std::string& what, bool produced, bool expected) {
281,181✔
344
   return test_is_eq(what, produced, expected);
281,181✔
345
}
346

347
bool Test::Result::test_rc_init(const std::string& func, int rc) {
36✔
348
   if(rc == 0) {
36✔
349
      return test_success();
72✔
350
   } else {
351
      std::ostringstream msg;
×
352
      msg << m_who;
×
353
      msg << " " << func;
×
354

355
      // -40 is BOTAN_FFI_ERROR_NOT_IMPLEMENTED
356
      if(rc == -40) {
×
357
         msg << " returned not implemented";
×
358
      } else {
359
         msg << " unexpectedly failed with error code " << rc;
×
360
      }
361

362
      if(rc == -40) {
×
363
         this->test_note(msg.str());
×
364
      } else {
365
         this->test_failure(msg.str());
×
366
      }
367
      return false;
×
368
   }
×
369
}
370

371
bool Test::Result::test_rc(const std::string& func, int expected, int rc) {
231✔
372
   if(expected != rc) {
231✔
373
      std::ostringstream err;
1✔
374
      err << m_who;
1✔
375
      err << " call to " << func << " unexpectedly returned " << rc;
1✔
376
      err << " but expecting " << expected;
1✔
377
      return test_failure(err.str());
1✔
378
   }
1✔
379

380
   return test_success();
460✔
381
}
382

383
std::vector<std::string> Test::possible_providers(const std::string& /*unused*/) {
×
384
   return Test::provider_filter({"base"});
×
385
}
386

387
//static
388
std::string Test::format_time(uint64_t ns) {
975✔
389
   std::ostringstream o;
975✔
390

391
   if(ns > 1000000000) {
975✔
392
      o << std::setprecision(2) << std::fixed << ns / 1000000000.0 << " sec";
136✔
393
   } else {
394
      o << std::setprecision(2) << std::fixed << ns / 1000000.0 << " msec";
839✔
395
   }
396

397
   return o.str();
1,950✔
398
}
975✔
399

400
Test::Result::Result(std::string who, const std::vector<Result>& downstream_results) : Result(std::move(who)) {
20✔
401
   for(const auto& result : downstream_results) {
58✔
402
      merge(result, true /* ignore non-matching test names */);
48✔
403
   }
404
}
10✔
405

406
// TODO: this should move to `StdoutReporter`
407
std::string Test::Result::result_string() const {
1,668✔
408
   const bool verbose = Test::options().verbose();
1,668✔
409

410
   if(tests_run() == 0 && !verbose) {
1,668✔
411
      return "";
13✔
412
   }
413

414
   std::ostringstream report;
1,655✔
415

416
   report << who() << " ran ";
1,655✔
417

418
   if(tests_run() == 0) {
1,655✔
419
      report << "ZERO";
×
420
   } else {
421
      report << tests_run();
1,655✔
422
   }
423
   report << " tests";
1,655✔
424

425
   if(m_ns_taken > 0) {
1,655✔
426
      report << " in " << format_time(m_ns_taken);
1,948✔
427
   }
428

429
   if(tests_failed()) {
1,655✔
430
      report << " " << tests_failed() << " FAILED";
25✔
431
   } else {
432
      report << " all ok";
1,630✔
433
   }
434

435
   report << "\n";
1,655✔
436

437
   for(size_t i = 0; i != m_fail_log.size(); ++i) {
1,680✔
438
      report << "Failure " << (i + 1) << ": " << m_fail_log[i];
25✔
439
      if(m_where) {
25✔
440
         report << " (at " << m_where->path << ":" << m_where->line << ")";
×
441
      }
442
      report << "\n";
25✔
443
   }
444

445
   if(!m_fail_log.empty() || tests_run() == 0 || verbose) {
1,655✔
446
      for(size_t i = 0; i != m_log.size(); ++i) {
25✔
447
         report << "Note " << (i + 1) << ": " << m_log[i] << "\n";
×
448
      }
449
   }
450

451
   return report.str();
1,655✔
452
}
1,655✔
453

454
namespace {
455

456
class Test_Registry {
457
   public:
458
      static Test_Registry& instance() {
934✔
459
         static Test_Registry registry;
935✔
460
         return registry;
934✔
461
      }
462

463
      void register_test(std::string category,
311✔
464
                         std::string name,
465
                         bool smoke_test,
466
                         bool needs_serialization,
467
                         std::function<std::unique_ptr<Test>()> maker_fn) {
468
         if(m_tests.contains(name)) {
311✔
469
            throw Test_Error("Duplicate registration of test '" + name + "'");
×
470
         }
471

472
         if(m_tests.contains(category)) {
311✔
473
            throw Test_Error("'" + category + "' cannot be used as category, test exists");
×
474
         }
475

476
         if(m_categories.contains(name)) {
311✔
477
            throw Test_Error("'" + name + "' cannot be used as test name, category exists");
×
478
         }
479

480
         if(smoke_test) {
311✔
481
            m_smoke_tests.push_back(name);
10✔
482
         }
483

484
         if(needs_serialization) {
311✔
485
            m_mutexed_tests.push_back(name);
17✔
486
         }
487

488
         m_tests.emplace(name, std::move(maker_fn));
311✔
489
         m_categories.emplace(std::move(category), std::move(name));
311✔
490
      }
311✔
491

492
      std::unique_ptr<Test> get_test(const std::string& test_name) const {
311✔
493
         auto i = m_tests.find(test_name);
311✔
494
         if(i != m_tests.end()) {
311✔
495
            return i->second();
311✔
496
         }
497
         return nullptr;
×
498
      }
499

500
      std::set<std::string> registered_tests() const { return Botan::map_keys_as_set(m_tests); }
×
501

502
      std::set<std::string> registered_test_categories() const { return Botan::map_keys_as_set(m_categories); }
×
503

504
      std::vector<std::string> filter_registered_tests(const std::vector<std::string>& requested,
1✔
505
                                                       const std::set<std::string>& to_be_skipped) {
506
         std::vector<std::string> result;
1✔
507

508
         // TODO: this is O(n^2), but we have a relatively small number of tests.
509
         auto insert_if_not_exists_and_not_skipped = [&](const std::string& test_name) {
312✔
510
            if(!Botan::value_exists(result, test_name) && to_be_skipped.find(test_name) == to_be_skipped.end()) {
311✔
511
               result.push_back(test_name);
301✔
512
            }
513
         };
312✔
514

515
         if(requested.empty()) {
1✔
516
            /*
517
            If nothing was requested on the command line, run everything. First
518
            run the "essentials" to smoke test, then everything else in
519
            alphabetical order.
520
            */
521
            result = m_smoke_tests;
1✔
522
            for(const auto& [test_name, _] : m_tests) {
312✔
523
               insert_if_not_exists_and_not_skipped(test_name);
311✔
524
            }
525
         } else {
526
            for(const auto& r : requested) {
×
527
               if(m_tests.find(r) != m_tests.end()) {
×
528
                  insert_if_not_exists_and_not_skipped(r);
×
529
               } else if(auto elems = m_categories.equal_range(r); elems.first != m_categories.end()) {
×
530
                  for(; elems.first != elems.second; ++elems.first) {
×
531
                     insert_if_not_exists_and_not_skipped(elems.first->second);
×
532
                  }
533
               } else {
534
                  throw Botan_Tests::Test_Error("Unknown test suite or category: " + r);
×
535
               }
536
            }
537
         }
538

539
         return result;
1✔
540
      }
×
541

542
      bool needs_serialization(const std::string& test_name) const {
311✔
543
         return Botan::value_exists(m_mutexed_tests, test_name);
311✔
544
      }
545

546
   private:
547
      Test_Registry() = default;
1✔
548

549
   private:
550
      std::map<std::string, std::function<std::unique_ptr<Test>()>> m_tests;
551
      std::multimap<std::string, std::string> m_categories;
552
      std::vector<std::string> m_smoke_tests;
553
      std::vector<std::string> m_mutexed_tests;
554
};
555

556
}  // namespace
557

558
// static Test:: functions
559

560
//static
561
void Test::register_test(std::string category,
311✔
562
                         std::string name,
563
                         bool smoke_test,
564
                         bool needs_serialization,
565
                         std::function<std::unique_ptr<Test>()> maker_fn) {
566
   Test_Registry::instance().register_test(
933✔
567
      std::move(category), std::move(name), smoke_test, needs_serialization, std::move(maker_fn));
933✔
568
}
311✔
569

570
//static
571
uint64_t Test::timestamp() {
88,773✔
572
   auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
88,773✔
573
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
88,769✔
574
}
575

576
//static
577
std::vector<Test::Result> Test::flatten_result_lists(std::vector<std::vector<Test::Result>> result_lists) {
4✔
578
   std::vector<Test::Result> results;
4✔
579
   for(auto& result_list : result_lists) {
24✔
580
      for(auto& result : result_list) {
65✔
581
         results.emplace_back(std::move(result));
45✔
582
      }
583
   }
584
   return results;
4✔
585
}
×
586

587
//static
588
std::set<std::string> Test::registered_tests() { return Test_Registry::instance().registered_tests(); }
×
589

590
//static
591
std::set<std::string> Test::registered_test_categories() {
×
592
   return Test_Registry::instance().registered_test_categories();
×
593
}
594

595
//static
596
std::unique_ptr<Test> Test::get_test(const std::string& test_name) {
311✔
597
   return Test_Registry::instance().get_test(test_name);
311✔
598
}
599

600
//static
601
bool Test::test_needs_serialization(const std::string& test_name) {
311✔
602
   return Test_Registry::instance().needs_serialization(test_name);
311✔
603
}
604

605
//static
606
std::vector<std::string> Test::filter_registered_tests(const std::vector<std::string>& requested,
1✔
607
                                                       const std::set<std::string>& to_be_skipped) {
608
   return Test_Registry::instance().filter_registered_tests(requested, to_be_skipped);
1✔
609
}
610

611
//static
612
std::string Test::temp_file_name(const std::string& basename) {
21✔
613
   // TODO add a --tmp-dir option to the tests to specify where these files go
614

615
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
616

617
   // POSIX only calls for 6 'X' chars but OpenBSD allows arbitrary amount
618
   std::string mkstemp_basename = "/tmp/" + basename + ".XXXXXXXXXX";
21✔
619

620
   int fd = ::mkstemp(&mkstemp_basename[0]);
21✔
621

622
   // error
623
   if(fd < 0) {
21✔
624
      return "";
×
625
   }
626

627
   ::close(fd);
21✔
628

629
   return mkstemp_basename;
42✔
630
#else
631
   // For now just create the temp in the current working directory
632
   return basename;
633
#endif
634
}
21✔
635

636
bool Test::copy_file(const std::string& from, const std::string& to) {
1✔
637
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(__cpp_lib_filesystem)
638
   std::error_code ec;  // don't throw, just return false on error
1✔
639
   return std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec);
1✔
640
#else
641
   // TODO: implement fallbacks to POSIX or WIN32
642
   // ... but then again: it's 2023 and we're using C++20 :o)
643
   BOTAN_UNUSED(from, to);
644
   throw Botan::No_Filesystem_Access();
645
#endif
646
}
647

648
std::string Test::read_data_file(const std::string& path) {
24✔
649
   const std::string fsname = Test::data_file(path);
24✔
650
   std::ifstream file(fsname.c_str());
24✔
651
   if(!file.good()) {
24✔
652
      throw Test_Error("Error reading from " + fsname);
×
653
   }
654

655
   return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
24✔
656
}
48✔
657

658
std::vector<uint8_t> Test::read_binary_data_file(const std::string& path) {
33✔
659
   const std::string fsname = Test::data_file(path);
33✔
660
   std::ifstream file(fsname.c_str(), std::ios::binary);
33✔
661
   if(!file.good()) {
33✔
662
      throw Test_Error("Error reading from " + fsname);
×
663
   }
664

665
   std::vector<uint8_t> contents;
33✔
666

667
   while(file.good()) {
71✔
668
      std::vector<uint8_t> buf(4096);
38✔
669
      file.read(reinterpret_cast<char*>(buf.data()), buf.size());
38✔
670
      const size_t got = static_cast<size_t>(file.gcount());
38✔
671

672
      if(got == 0 && file.eof()) {
38✔
673
         break;
674
      }
675

676
      contents.insert(contents.end(), buf.data(), buf.data() + got);
38✔
677
   }
38✔
678

679
   return contents;
66✔
680
}
66✔
681

682
// static member variables of Test
683

684
Test_Options Test::m_opts;
685
std::shared_ptr<Botan::RandomNumberGenerator> Test::m_test_rng;
686

687
//static
688
void Test::set_test_options(const Test_Options& opts) { m_opts = opts; }
1✔
689

690
//static
691
void Test::set_test_rng(std::shared_ptr<Botan::RandomNumberGenerator> rng) { m_test_rng = std::move(rng); }
1✔
692

693
//static
694
std::string Test::data_file(const std::string& what) { return Test::data_dir() + "/" + what; }
498✔
695

696
//static
697
std::string Test::data_file_as_temporary_copy(const std::string& what) {
1✔
698
   auto tmp_basename = what;
1✔
699
   std::replace(tmp_basename.begin(), tmp_basename.end(), '/', '_');
1✔
700
   auto temp_file = temp_file_name("tmp-" + tmp_basename);
1✔
701
   if(temp_file.empty()) {
1✔
702
      return "";
×
703
   }
704
   if(!Test::copy_file(data_file(what), temp_file)) {
2✔
705
      return "";
×
706
   }
707
   return temp_file;
2✔
708
}
2✔
709

710
//static
711
std::vector<std::string> Test::provider_filter(const std::vector<std::string>& in) {
41,862✔
712
   if(m_opts.provider().empty()) {
41,862✔
713
      return in;
41,862✔
714
   }
715
   for(auto&& provider : in) {
×
716
      if(provider == m_opts.provider()) {
×
717
         return std::vector<std::string>{provider};
×
718
      }
719
   }
720
   return std::vector<std::string>{};
41,862✔
721
}
722

723
//static
724
Botan::RandomNumberGenerator& Test::rng() {
539,098✔
725
   if(!m_test_rng) {
539,098✔
726
      throw Test_Error("Test requires RNG but no RNG set with Test::set_test_rng");
×
727
   }
728
   return *m_test_rng;
539,098✔
729
}
730

731
//static
732
std::shared_ptr<Botan::RandomNumberGenerator> Test::rng_as_shared() {
107✔
733
   if(!m_test_rng) {
107✔
734
      throw Test_Error("Test requires RNG but no RNG set with Test::set_test_rng");
×
735
   }
736
   return m_test_rng;
107✔
737
}
738

739
std::string Test::random_password() {
84✔
740
   const size_t len = 1 + Test::rng().next_byte() % 32;
84✔
741
   return Botan::hex_encode(Test::rng().random_vec(len));
168✔
742
}
743

744
std::vector<std::vector<uint8_t>> VarMap::get_req_bin_list(const std::string& key) const {
12✔
745
   auto i = m_vars.find(key);
12✔
746
   if(i == m_vars.end()) {
12✔
747
      throw Test_Error("Test missing variable " + key);
×
748
   }
749

750
   std::vector<std::vector<uint8_t>> bin_list;
12✔
751

752
   for(auto&& part : Botan::split_on(i->second, ',')) {
62✔
753
      try {
50✔
754
         bin_list.push_back(Botan::hex_decode(part));
100✔
755
      } catch(std::exception& e) {
×
756
         std::ostringstream oss;
×
757
         oss << "Bad input '" << part << "'"
×
758
             << " in binary list key " << key << " - " << e.what();
×
759
         throw Test_Error(oss.str());
×
760
      }
×
761
   }
12✔
762

763
   return bin_list;
12✔
764
}
×
765

766
std::vector<uint8_t> VarMap::get_req_bin(const std::string& key) const {
130,271✔
767
   auto i = m_vars.find(key);
130,271✔
768
   if(i == m_vars.end()) {
130,271✔
769
      throw Test_Error("Test missing variable " + key);
×
770
   }
771

772
   try {
130,271✔
773
      return Botan::hex_decode(i->second);
130,271✔
774
   } catch(std::exception& e) {
×
775
      std::ostringstream oss;
×
776
      oss << "Bad input '" << i->second << "'"
×
777
          << " for key " << key << " - " << e.what();
×
778
      throw Test_Error(oss.str());
×
779
   }
×
780
}
781

782
std::string VarMap::get_opt_str(const std::string& key, const std::string& def_value) const {
13,538✔
783
   auto i = m_vars.find(key);
13,538✔
784
   if(i == m_vars.end()) {
13,538✔
785
      return def_value;
13,487✔
786
   }
787
   return i->second;
51✔
788
}
789

790
bool VarMap::get_req_bool(const std::string& key) const {
19✔
791
   auto i = m_vars.find(key);
19✔
792
   if(i == m_vars.end()) {
19✔
793
      throw Test_Error("Test missing variable " + key);
×
794
   }
795

796
   if(i->second == "true") {
19✔
797
      return true;
798
   } else if(i->second == "false") {
11✔
799
      return false;
800
   } else {
801
      throw Test_Error("Invalid boolean for key '" + key + "' value '" + i->second + "'");
×
802
   }
803
}
804

805
size_t VarMap::get_req_sz(const std::string& key) const {
4,368✔
806
   auto i = m_vars.find(key);
4,368✔
807
   if(i == m_vars.end()) {
4,368✔
808
      throw Test_Error("Test missing variable " + key);
×
809
   }
810
   return Botan::to_u32bit(i->second);
4,368✔
811
}
812

813
uint8_t VarMap::get_req_u8(const std::string& key) const {
17✔
814
   const size_t s = this->get_req_sz(key);
17✔
815
   if(s > 256) {
17✔
816
      throw Test_Error("Invalid " + key + " expected uint8_t got " + std::to_string(s));
×
817
   }
818
   return static_cast<uint8_t>(s);
17✔
819
}
820

821
uint32_t VarMap::get_req_u32(const std::string& key) const { return static_cast<uint32_t>(get_req_sz(key)); }
3✔
822

823
uint64_t VarMap::get_req_u64(const std::string& key) const {
13✔
824
   auto i = m_vars.find(key);
13✔
825
   if(i == m_vars.end()) {
13✔
826
      throw Test_Error("Test missing variable " + key);
×
827
   }
828
   try {
13✔
829
      return std::stoull(i->second);
13✔
830
   } catch(std::exception&) { throw Test_Error("Invalid u64 value '" + i->second + "'"); }
×
831
}
832

833
size_t VarMap::get_opt_sz(const std::string& key, const size_t def_value) const {
26,919✔
834
   auto i = m_vars.find(key);
26,919✔
835
   if(i == m_vars.end()) {
26,919✔
836
      return def_value;
837
   }
838
   return Botan::to_u32bit(i->second);
11,934✔
839
}
840

841
uint64_t VarMap::get_opt_u64(const std::string& key, const uint64_t def_value) const {
3,538✔
842
   auto i = m_vars.find(key);
3,538✔
843
   if(i == m_vars.end()) {
3,538✔
844
      return def_value;
845
   }
846
   try {
641✔
847
      return std::stoull(i->second);
3,538✔
848
   } catch(std::exception&) { throw Test_Error("Invalid u64 value '" + i->second + "'"); }
×
849
}
850

851
std::vector<uint8_t> VarMap::get_opt_bin(const std::string& key) const {
36,280✔
852
   auto i = m_vars.find(key);
36,280✔
853
   if(i == m_vars.end()) {
36,280✔
854
      return std::vector<uint8_t>();
36,280✔
855
   }
856

857
   try {
11,134✔
858
      return Botan::hex_decode(i->second);
11,134✔
859
   } catch(std::exception&) { throw Test_Error("Test invalid hex input '" + i->second + "'" + +" for key " + key); }
×
860
}
861

862
std::string VarMap::get_req_str(const std::string& key) const {
39,499✔
863
   auto i = m_vars.find(key);
39,499✔
864
   if(i == m_vars.end()) {
39,499✔
865
      throw Test_Error("Test missing variable " + key);
×
866
   }
867
   return i->second;
39,499✔
868
}
869

870
#if defined(BOTAN_HAS_BIGINT)
871
Botan::BigInt VarMap::get_req_bn(const std::string& key) const {
36,602✔
872
   auto i = m_vars.find(key);
36,602✔
873
   if(i == m_vars.end()) {
36,602✔
874
      throw Test_Error("Test missing variable " + key);
×
875
   }
876

877
   try {
36,602✔
878
      return Botan::BigInt(i->second);
36,602✔
879
   } catch(std::exception&) { throw Test_Error("Test invalid bigint input '" + i->second + "' for key " + key); }
×
880
}
881

882
Botan::BigInt VarMap::get_opt_bn(const std::string& key, const Botan::BigInt& def_value) const
80✔
883

884
{
885
   auto i = m_vars.find(key);
80✔
886
   if(i == m_vars.end()) {
80✔
887
      return def_value;
104✔
888
   }
889

890
   try {
56✔
891
      return Botan::BigInt(i->second);
56✔
892
   } catch(std::exception&) { throw Test_Error("Test invalid bigint input '" + i->second + "' for key " + key); }
×
893
}
894
#endif
895

896
Text_Based_Test::Text_Based_Test(const std::string& data_src,
147✔
897
                                 const std::string& required_keys_str,
898
                                 const std::string& optional_keys_str) :
147✔
899
      m_data_src(data_src) {
441✔
900
   if(required_keys_str.empty()) {
147✔
901
      throw Test_Error("Invalid test spec");
×
902
   }
903

904
   std::vector<std::string> required_keys = Botan::split_on(required_keys_str, ',');
147✔
905
   std::vector<std::string> optional_keys = Botan::split_on(optional_keys_str, ',');
147✔
906

907
   m_required_keys.insert(required_keys.begin(), required_keys.end());
147✔
908
   m_optional_keys.insert(optional_keys.begin(), optional_keys.end());
147✔
909
   m_output_key = required_keys.at(required_keys.size() - 1);
147✔
910
}
147✔
911

912
std::string Text_Based_Test::get_next_line() {
140,347✔
913
   while(true) {
140,566✔
914
      if(m_cur == nullptr || m_cur->good() == false) {
140,566✔
915
         if(m_srcs.empty()) {
374✔
916
            if(m_first) {
294✔
917
               const std::string full_path = Test::data_dir() + "/" + m_data_src;
147✔
918
               if(full_path.find(".vec") != std::string::npos) {
147✔
919
                  m_srcs.push_back(full_path);
136✔
920
               } else {
921
                  const auto fs = Botan::get_files_recursive(full_path);
11✔
922
                  m_srcs.assign(fs.begin(), fs.end());
11✔
923
                  if(m_srcs.empty()) {
11✔
924
                     throw Test_Error("Error reading test data dir " + full_path);
×
925
                  }
926
               }
11✔
927

928
               m_first = false;
147✔
929
            } else {
147✔
930
               return "";  // done
147✔
931
            }
932
         }
933

934
         m_cur = std::make_unique<std::ifstream>(m_srcs[0]);
307✔
935
         m_cur_src_name = m_srcs[0];
227✔
936

937
         // Reinit cpuid on new file if needed
938
         if(m_cpu_flags.empty() == false) {
227✔
939
            m_cpu_flags.clear();
12✔
940
            Botan::CPUID::initialize();
12✔
941
         }
942

943
         if(!m_cur->good()) {
227✔
944
            throw Test_Error("Could not open input file '" + m_cur_src_name);
×
945
         }
946

947
         m_srcs.pop_front();
227✔
948
      }
949

950
      while(m_cur->good()) {
204,347✔
951
         std::string line;
204,128✔
952
         std::getline(*m_cur, line);
204,128✔
953

954
         if(line.empty()) {
204,128✔
955
            continue;
50,461✔
956
         }
957

958
         if(line[0] == '#') {
153,667✔
959
            if(line.compare(0, 6, "#test ") == 0) {
13,483✔
960
               return line;
16✔
961
            } else {
962
               continue;
13,467✔
963
            }
964
         }
965

966
         return line;
280,384✔
967
      }
204,128✔
968
   }
969
}
970

971
namespace {
972

973
// strips leading and trailing but not internal whitespace
974
std::string strip_ws(const std::string& in) {
279,188✔
975
   const char* whitespace = " ";
279,188✔
976

977
   const auto first_c = in.find_first_not_of(whitespace);
279,188✔
978
   if(first_c == std::string::npos) {
279,188✔
979
      return "";
943✔
980
   }
981

982
   const auto last_c = in.find_last_not_of(whitespace);
278,245✔
983

984
   return in.substr(first_c, last_c - first_c + 1);
278,245✔
985
}
986

987
std::vector<uint64_t> parse_cpuid_bits(const std::vector<std::string>& tok) {
16✔
988
   std::vector<uint64_t> bits;
16✔
989
   for(size_t i = 1; i < tok.size(); ++i) {
55✔
990
      const std::vector<Botan::CPUID::CPUID_bits> more = Botan::CPUID::bit_from_string(tok[i]);
39✔
991
      bits.insert(bits.end(), more.begin(), more.end());
39✔
992
   }
39✔
993

994
   return bits;
16✔
995
}
×
996

997
}  // namespace
998

999
bool Text_Based_Test::skip_this_test(const std::string& /*header*/, const VarMap& /*vars*/) { return false; }
43,600✔
1000

1001
std::vector<Test::Result> Text_Based_Test::run() {
147✔
1002
   std::vector<Test::Result> results;
147✔
1003

1004
   std::string header, header_or_name = m_data_src;
147✔
1005
   VarMap vars;
147✔
1006
   size_t test_cnt = 0;
147✔
1007

1008
   while(true) {
140,347✔
1009
      const std::string line = get_next_line();
140,347✔
1010
      if(line.empty())  // EOF
140,347✔
1011
      {
1012
         break;
1013
      }
1014

1015
      if(line.compare(0, 6, "#test ") == 0) {
140,200✔
1016
         std::vector<std::string> pragma_tokens = Botan::split_on(line.substr(6), ' ');
16✔
1017

1018
         if(pragma_tokens.empty()) {
16✔
1019
            throw Test_Error("Empty pragma found in " + m_cur_src_name);
×
1020
         }
1021

1022
         if(pragma_tokens[0] != "cpuid") {
16✔
1023
            throw Test_Error("Unknown test pragma '" + line + "' in " + m_cur_src_name);
×
1024
         }
1025

1026
         m_cpu_flags = parse_cpuid_bits(pragma_tokens);
16✔
1027

1028
         continue;
16✔
1029
      } else if(line[0] == '#') {
140,200✔
1030
         throw Test_Error("Unknown test pragma '" + line + "' in " + m_cur_src_name);
×
1031
      }
1032

1033
      if(line[0] == '[' && line[line.size() - 1] == ']') {
140,184✔
1034
         header = line.substr(1, line.size() - 2);
590✔
1035
         header_or_name = header;
590✔
1036
         test_cnt = 0;
590✔
1037
         vars.clear();
590✔
1038
         continue;
590✔
1039
      }
1040

1041
      const std::string test_id = "test " + std::to_string(test_cnt);
139,594✔
1042

1043
      auto equal_i = line.find_first_of('=');
139,594✔
1044

1045
      if(equal_i == std::string::npos) {
139,594✔
1046
         results.push_back(Test::Result::Failure(header_or_name, "invalid input '" + line + "'"));
×
1047
         continue;
×
1048
      }
1049

1050
      std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1));
139,594✔
1051
      std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end()));
139,594✔
1052

1053
      if(!m_required_keys.contains(key) && !m_optional_keys.contains(key)) {
139,594✔
1054
         results.push_back(Test::Result::Failure(header_or_name, test_id + " failed unknown key " + key));
×
1055
      }
1056

1057
      vars.add(key, val);
139,594✔
1058

1059
      if(key == m_output_key) {
139,594✔
1060
         try {
43,641✔
1061
            for(auto& req_key : m_required_keys) {
224,719✔
1062
               if(!vars.has_key(req_key)) {
362,156✔
1063
                  results.push_back(
×
1064
                     Test::Result::Failure(header_or_name, test_id + " missing required key " + req_key));
×
1065
               }
1066
            }
1067

1068
            if(skip_this_test(header, vars)) {
43,641✔
1069
               continue;
×
1070
            }
1071

1072
            ++test_cnt;
43,641✔
1073

1074
            uint64_t start = Test::timestamp();
43,641✔
1075

1076
            Test::Result result = run_one_test(header, vars);
43,641✔
1077
            if(!m_cpu_flags.empty()) {
43,641✔
1078
               for(const auto& cpuid_u64 : m_cpu_flags) {
17,907✔
1079
                  Botan::CPUID::CPUID_bits cpuid_bit = static_cast<Botan::CPUID::CPUID_bits>(cpuid_u64);
12,317✔
1080
                  if(Botan::CPUID::has_cpuid_bit(cpuid_bit)) {
12,317✔
1081
                     Botan::CPUID::clear_cpuid_bit(cpuid_bit);
9,670✔
1082
                     // now re-run the test
1083
                     result.merge(run_one_test(header, vars));
9,670✔
1084
                  }
1085
               }
1086
               Botan::CPUID::initialize();
5,590✔
1087
            }
1088
            result.set_ns_consumed(Test::timestamp() - start);
43,641✔
1089

1090
            if(result.tests_failed()) {
43,641✔
1091
               std::ostringstream oss;
×
1092
               oss << "Test # " << test_cnt << " ";
×
1093
               if(!header.empty()) {
×
1094
                  oss << header << " ";
×
1095
               }
1096
               oss << "failed ";
×
1097

1098
               for(const auto& k : m_required_keys) {
×
1099
                  oss << k << "=" << vars.get_req_str(k) << " ";
×
1100
               }
1101

1102
               result.test_note(oss.str());
×
1103
            }
×
1104
            results.push_back(result);
43,641✔
1105
         } catch(std::exception& e) {
43,641✔
1106
            std::ostringstream oss;
×
1107
            oss << "Test # " << test_cnt << " ";
×
1108
            if(!header.empty()) {
×
1109
               oss << header << " ";
×
1110
            }
1111

1112
            for(const auto& k : m_required_keys) {
×
1113
               oss << k << "=" << vars.get_req_str(k) << " ";
×
1114
            }
1115

1116
            oss << "failed with exception '" << e.what() << "'";
×
1117

1118
            results.push_back(Test::Result::Failure(header_or_name, oss.str()));
×
1119
         }
×
1120

1121
         if(clear_between_callbacks()) {
43,641✔
1122
            vars.clear();
168,828✔
1123
         }
1124
      }
1125
   }
260,860✔
1126

1127
   if(results.empty()) {
147✔
1128
      return results;
1129
   }
1130

1131
   try {
147✔
1132
      std::vector<Test::Result> final_tests = run_final_tests();
147✔
1133
      results.insert(results.end(), final_tests.begin(), final_tests.end());
147✔
1134
   } catch(std::exception& e) {
147✔
1135
      results.push_back(Test::Result::Failure(header_or_name, "run_final_tests exception " + std::string(e.what())));
×
1136
   }
×
1137

1138
   m_first = true;
147✔
1139

1140
   return results;
147✔
1141
}
286✔
1142

1143
std::map<std::string, std::string> Test_Options::report_properties() const {
1✔
1144
   std::map<std::string, std::string> result;
1✔
1145

1146
   for(const auto& prop : m_report_properties) {
3✔
1147
      const auto colon = prop.find(':');
2✔
1148
      // props without a colon separator or without a name are not allowed
1149
      if(colon == std::string::npos || colon == 0) {
2✔
1150
         throw Test_Error("--report-properties should be of the form <key>:<value>,<key>:<value>,...");
×
1151
      }
1152

1153
      result.insert_or_assign(prop.substr(0, colon), prop.substr(colon + 1, prop.size() - colon - 1));
4✔
1154
   }
1155

1156
   return result;
1✔
1157
}
×
1158

1159
}  // namespace Botan_Tests
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

© 2025 Coveralls, Inc