testutil.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include "testutil.h"
  10. #include <assert.h>
  11. #include <stdlib.h>
  12. #include <stdio.h>
  13. #include "e_os.h"
  14. /*
  15. * Declares the structures needed to register each test case function.
  16. */
  17. typedef struct test_info {
  18. const char *test_case_name;
  19. int (*test_fn) ();
  20. int (*param_test_fn)(int idx);
  21. int num;
  22. } TEST_INFO;
  23. static TEST_INFO all_tests[1024];
  24. static int num_tests = 0;
  25. /*
  26. * A parameterised tests runs a loop of test cases.
  27. * |num_test_cases| counts the total number of test cases
  28. * across all tests.
  29. */
  30. static int num_test_cases = 0;
  31. void add_test(const char *test_case_name, int (*test_fn) ())
  32. {
  33. assert(num_tests != OSSL_NELEM(all_tests));
  34. all_tests[num_tests].test_case_name = test_case_name;
  35. all_tests[num_tests].test_fn = test_fn;
  36. all_tests[num_tests].num = -1;
  37. ++num_test_cases;
  38. ++num_tests;
  39. }
  40. void add_all_tests(const char *test_case_name, int(*test_fn)(int idx),
  41. int num)
  42. {
  43. assert(num_tests != OSSL_NELEM(all_tests));
  44. all_tests[num_tests].test_case_name = test_case_name;
  45. all_tests[num_tests].param_test_fn = test_fn;
  46. all_tests[num_tests].num = num;
  47. ++num_tests;
  48. num_test_cases += num;
  49. }
  50. int run_tests(const char *test_prog_name)
  51. {
  52. int num_failed = 0;
  53. int i, j;
  54. printf("%s: %d test case%s\n", test_prog_name, num_test_cases,
  55. num_test_cases == 1 ? "" : "s");
  56. for (i = 0; i != num_tests; ++i) {
  57. if (all_tests[i].num == -1) {
  58. if (!all_tests[i].test_fn()) {
  59. printf("** %s failed **\n--------\n",
  60. all_tests[i].test_case_name);
  61. ++num_failed;
  62. }
  63. } else {
  64. for (j = 0; j < all_tests[i].num; j++) {
  65. if (!all_tests[i].param_test_fn(j)) {
  66. printf("** %s failed test %d\n--------\n",
  67. all_tests[i].test_case_name, j);
  68. ++num_failed;
  69. }
  70. }
  71. }
  72. }
  73. if (num_failed != 0) {
  74. printf("%s: %d test%s failed (out of %d)\n", test_prog_name,
  75. num_failed, num_failed != 1 ? "s" : "", num_test_cases);
  76. return EXIT_FAILURE;
  77. }
  78. printf(" All tests passed.\n");
  79. return EXIT_SUCCESS;
  80. }