testc.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. #ifdef HAVE_CONFIG_H
  2. #include "config.h"
  3. #endif /* HAVE_CONFIG_H */
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <assert.h>
  7. #include <string.h>
  8. #include <fcntl.h>
  9. #include <unistd.h>
  10. #include <dlfcn.h>
  11. #include <sys/types.h>
  12. #include <sys/wait.h>
  13. #include <sys/uio.h>
  14. #include <errno.h>
  15. #include <sys/stat.h>
  16. #include <errno.h>
  17. #if WITH_INTERNAL_GETOPT
  18. #include "libc/getopt.h"
  19. #else
  20. #ifdef HAVE_GETOPT_H
  21. #include <getopt.h>
  22. #endif
  23. #endif
  24. #if HAVE_LOCALE_H
  25. #include <locale.h>
  26. #endif
  27. #if HAVE_LANGINFO_CODESET
  28. #include <langinfo.h>
  29. #endif
  30. #include "faux/faux.h"
  31. #include "faux/str.h"
  32. #include "faux/list.h"
  33. #include "faux/testc_helpers.h"
  34. #ifndef VERSION
  35. #define VERSION 1.0.0
  36. #endif
  37. #define QUOTE(t) #t
  38. #define version(v) printf("%s\n", v)
  39. // Version of testc API (not version of programm)
  40. #define TESTC_VERSION_MAJOR_DEFAULT 1
  41. #define TESTC_VERSION_MINOR_DEFAULT 0
  42. #define SYM_TESTC_VERSION_MAJOR "testc_version_major"
  43. #define SYM_TESTC_VERSION_MINOR "testc_version_minor"
  44. #define SYM_TESTC_MODULE "testc_module"
  45. #define CHUNK_SIZE 1024
  46. #define TEST_OUTPUT_LIMIT 1024 * CHUNK_SIZE
  47. // Command line options */
  48. struct opts_s {
  49. bool_t debug;
  50. bool_t preserve_tmp;
  51. faux_list_t *so_list;
  52. };
  53. typedef struct opts_s opts_t;
  54. static opts_t *opts_parse(int argc, char *argv[]);
  55. static void opts_free(opts_t *opts);
  56. static void help(int status, const char *argv0);
  57. static int exec_test(int (*test_sym)(void), faux_list_t **buf_list);
  58. static void print_test_output(faux_list_t *buf_list);
  59. int main(int argc, char *argv[]) {
  60. opts_t *opts = NULL; // Command line options
  61. faux_list_node_t *iter = NULL;
  62. char *so = NULL; // Shared object name
  63. // Return value will be negative on any error or failed test.
  64. // It doesn't mean that any error will break the processing.
  65. // The following vars are error statistics.
  66. unsigned int total_modules = 0; // Number of processed shared objects
  67. unsigned int total_broken_modules = 0; // Module processing errors
  68. unsigned int total_tests = 0; // Total number of tests
  69. unsigned int total_broken_tests = 0; // Something is wrong with test
  70. unsigned int total_failed_tests = 0; // Total number of failed tests
  71. unsigned int total_interrupted_tests = 0; // Number of interrupted tests
  72. unsigned int total_errors = 0; // Sum of all errors
  73. #if HAVE_LOCALE_H
  74. // Set current locale
  75. setlocale(LC_ALL, "");
  76. #endif
  77. // Parse command line options
  78. opts = opts_parse(argc, argv);
  79. if (!opts) {
  80. fprintf(stderr, "Error: Can't parse command line options\n");
  81. return -1;
  82. }
  83. // Main loop. Iterate through the list of shared objects
  84. iter = faux_list_head(opts->so_list);
  85. while ((so = faux_list_each(&iter))) {
  86. void *so_handle = NULL;
  87. char testc_tmpdir[] = "/tmp/testc-XXXXXX";
  88. // Module symbols
  89. unsigned char testc_version_major = TESTC_VERSION_MAJOR_DEFAULT;
  90. unsigned char testc_version_minor = TESTC_VERSION_MINOR_DEFAULT;
  91. unsigned char *testc_version = NULL;
  92. const char *(*testc_module)[2] = NULL;
  93. // Module statistics
  94. unsigned int module_tests = 0;
  95. unsigned int module_broken_tests = 0;
  96. unsigned int module_failed_tests = 0;
  97. unsigned int module_interrupted_tests = 0;
  98. unsigned int module_errors = 0; // Sum of all errors
  99. total_modules++; // Statistics
  100. printf("--------------------------------------------------------------------------------\n");
  101. // Open shared object
  102. so_handle = dlopen(so, RTLD_LAZY | RTLD_LOCAL);
  103. if (!so_handle) {
  104. fprintf(stderr, "Error: "
  105. "Can't open module \"%s\"... "
  106. "Skipped\n", so);
  107. total_broken_modules++; // Statistics
  108. continue;
  109. }
  110. // Get testc API version from module
  111. testc_version = dlsym(so_handle, SYM_TESTC_VERSION_MAJOR);
  112. if (!testc_version) {
  113. fprintf(stderr, "Warning: "
  114. "Can't get API version for module \"%s\"... "
  115. "Use defaults\n", so);
  116. } else {
  117. testc_version_major = *testc_version;
  118. testc_version = dlsym(so_handle,
  119. SYM_TESTC_VERSION_MINOR);
  120. if (!testc_version) {
  121. fprintf(stderr, "Warning: "
  122. "Can't get API minor version"
  123. " for module \"%s\"... "
  124. "Use '0'\n", so);
  125. testc_version_minor = 0;
  126. } else {
  127. testc_version_minor = *testc_version;
  128. }
  129. }
  130. if ((testc_version_major > TESTC_VERSION_MAJOR_DEFAULT) ||
  131. ((testc_version_major == TESTC_VERSION_MAJOR_DEFAULT) &&
  132. (testc_version_minor >TESTC_VERSION_MINOR_DEFAULT))) {
  133. fprintf(stderr, "Error: "
  134. "Unsupported API v%u.%u for module \"%s\"... "
  135. "Skipped\n",
  136. testc_version_major, testc_version_minor, so);
  137. total_broken_modules++; // Statistics
  138. continue;
  139. }
  140. // Get testing functions list from module
  141. testc_module = dlsym(so_handle, SYM_TESTC_MODULE);
  142. if (!testc_module) {
  143. fprintf(stderr, "Error: "
  144. "Can't get test list for module \"%s\"... "
  145. "Skipped\n", so);
  146. total_broken_modules++; // Statistics
  147. continue;
  148. }
  149. printf("Processing module \"%s\" v%u.%u ...\n", so,
  150. testc_version_major, testc_version_minor);
  151. // Create tmpdir for current shared object
  152. if (!mkdtemp(testc_tmpdir)) {
  153. fprintf(stderr, "Warning: "
  154. "Can't create tmp dir for module \"%s\"... "
  155. "Ignored\n", so);
  156. }
  157. if (opts->preserve_tmp) {
  158. fprintf(stderr, "Warning: "
  159. "Temp dir \"%s\" will be preserved\n",
  160. testc_tmpdir);
  161. }
  162. // Iterate through testing functions list
  163. while ((*testc_module)[0]) {
  164. const char *test_name = NULL;
  165. const char *test_desc = NULL;
  166. int (*test_sym)(void);
  167. int wstatus = 0; // Test's retval
  168. char *result_str = NULL;
  169. char *attention_str = NULL;
  170. faux_list_t *buf_list = NULL;
  171. char *tmpdir = NULL; // tmp dir for current test
  172. // Get name and description of testing function
  173. test_name = (*testc_module)[0];
  174. test_desc = (*testc_module)[1];
  175. if (!test_desc) // Description can be NULL
  176. test_desc = "";
  177. testc_module++; // Next test
  178. module_tests++; // Statistics
  179. // Get address of testing function by symbol name
  180. test_sym = (int (*)(void))dlsym(so_handle, test_name);
  181. if (!test_sym) {
  182. fprintf(stderr, "Error: "
  183. "Can't find symbol \"%s\"... "
  184. "Skipped\n", test_name);
  185. module_broken_tests++; // Statistics
  186. continue;
  187. }
  188. // Create tmp dir for current test and set TESTC_TMPDIR
  189. tmpdir = faux_str_sprintf("%s/test%03u",
  190. testc_tmpdir, module_tests);
  191. if (tmpdir) {
  192. if (mkdir(tmpdir, 0755) < 0) {
  193. fprintf(stderr, "Warning: "
  194. "Can't create temp dir \"%s\": %s\n",
  195. tmpdir, strerror(errno));
  196. }
  197. setenv(FAUX_TESTC_TMPDIR_ENV, tmpdir, 1);
  198. } else {
  199. fprintf(stderr, "Warning: "
  200. "Can't generate name for temp dir\n");
  201. }
  202. // Execute testing function
  203. wstatus = exec_test(test_sym, &buf_list);
  204. // Analyze testing function return code
  205. // Normal exit
  206. if (WIFEXITED(wstatus)) {
  207. // Success
  208. if (WEXITSTATUS(wstatus) == 0) {
  209. result_str = faux_str_dup("success");
  210. attention_str = faux_str_dup("");
  211. // Failed
  212. } else {
  213. result_str = faux_str_sprintf(
  214. "failed (%d)",
  215. (int)((signed char)((unsigned char)WEXITSTATUS(wstatus))));
  216. attention_str = faux_str_dup("(!) ");
  217. module_failed_tests++; // Statistics
  218. }
  219. // Terminated by signal
  220. } else if (WIFSIGNALED(wstatus)) {
  221. result_str = faux_str_sprintf("terminated (%d)",
  222. WTERMSIG(wstatus));
  223. attention_str = faux_str_dup("[!] ");
  224. module_interrupted_tests++; // Statistics
  225. // Stopped by unknown conditions
  226. } else {
  227. result_str = faux_str_dup("unknown");
  228. attention_str = faux_str_dup("[!] ");
  229. module_broken_tests++; // Statistics
  230. }
  231. // Print test execution report
  232. printf("%sTest #%03u %s() %s: %s\n",
  233. attention_str, module_tests,
  234. test_name, test_desc, result_str);
  235. faux_str_free(result_str);
  236. faux_str_free(attention_str);
  237. // Print test output if error or debug
  238. if (!WIFEXITED(wstatus) ||
  239. WEXITSTATUS(wstatus) != 0 ||
  240. opts->debug) {
  241. if (opts->preserve_tmp) {
  242. fprintf(stderr, "Info: "
  243. "Test's temp dir is \"%s\"\n",
  244. tmpdir);
  245. }
  246. if (faux_list_len(buf_list) > 0)
  247. printf("~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ \n");
  248. print_test_output(buf_list);
  249. if (faux_list_len(buf_list) > 0)
  250. printf("~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ \n");
  251. }
  252. faux_list_free(buf_list);
  253. // Remove test's tmp dir
  254. if (!opts->preserve_tmp)
  255. faux_rm(tmpdir);
  256. faux_str_free(tmpdir);
  257. }
  258. dlclose(so_handle);
  259. so_handle = NULL;
  260. // Remove module's tmp dir
  261. if (!opts->preserve_tmp)
  262. faux_rm(testc_tmpdir);
  263. // Report module statistics
  264. printf("Module tests: %u\n", module_tests);
  265. printf("Module broken tests: %u\n", module_broken_tests);
  266. printf("Module failed tests: %u\n", module_failed_tests);
  267. printf("Module interrupted tests: %u\n", module_interrupted_tests);
  268. module_errors =
  269. module_broken_tests +
  270. module_failed_tests +
  271. module_interrupted_tests;
  272. printf("Module errors: %u\n", module_errors);
  273. // Gather total statistics
  274. total_tests += module_tests;
  275. total_broken_tests += module_broken_tests;
  276. total_failed_tests += module_failed_tests;
  277. total_interrupted_tests += module_interrupted_tests;
  278. }
  279. opts_free(opts);
  280. // Report total statistics
  281. printf("================================================================================\n");
  282. printf("Total modules: %u\n", total_modules);
  283. printf("Total broken modules: %u\n", total_broken_modules);
  284. printf("Total tests: %u\n", total_tests);
  285. printf("Total broken_tests: %u\n", total_broken_tests);
  286. printf("Total failed tests: %u\n", total_failed_tests);
  287. printf("Total interrupted tests: %u\n", total_interrupted_tests);
  288. total_errors =
  289. total_broken_modules +
  290. total_broken_tests +
  291. total_failed_tests +
  292. total_interrupted_tests;
  293. printf("Total errors: %u\n", total_errors);
  294. if (total_errors > 0)
  295. return -1;
  296. return 0;
  297. }
  298. static void free_iov(struct iovec *iov) {
  299. faux_free(iov->iov_base);
  300. faux_free(iov);
  301. }
  302. static faux_list_t *read_test_output(int fd, size_t limit) {
  303. struct iovec *iov = NULL;
  304. size_t total_len = 0;
  305. faux_list_t *buf_list = NULL; // Buffer list
  306. buf_list = faux_list_new(
  307. FAUX_LIST_UNSORTED, FAUX_LIST_NONUNIQUE,
  308. NULL, NULL, (void (*)(void *))free_iov);
  309. do {
  310. ssize_t bytes_readed = 0;
  311. iov = faux_zmalloc(sizeof(*iov));
  312. assert(iov);
  313. iov->iov_len = CHUNK_SIZE;
  314. iov->iov_base = faux_malloc(iov->iov_len);
  315. assert(iov->iov_base);
  316. do {
  317. bytes_readed = readv(fd, iov, 1);
  318. } while ((bytes_readed < 0) && (errno == EINTR));
  319. if (bytes_readed <= 0) { /* Error or EOF */
  320. free_iov(iov);
  321. break;
  322. }
  323. iov->iov_len = bytes_readed;
  324. faux_list_add(buf_list, iov);
  325. total_len += iov->iov_len;
  326. } while (total_len < limit);
  327. return buf_list;
  328. }
  329. static void print_test_output(faux_list_t *buf_list) {
  330. faux_list_node_t *iter = NULL;
  331. struct iovec *iov = NULL;
  332. iter = faux_list_head(buf_list);
  333. while ((iov = faux_list_each(&iter))) {
  334. faux_write_block(STDOUT_FILENO, iov->iov_base, iov->iov_len);
  335. }
  336. }
  337. /** Executes testing function
  338. *
  339. * Function fork() and executes testing function.
  340. *
  341. * @param [in] test_sym Testing function.
  342. * @param [in] buf_list
  343. * @return Testing function return value
  344. */
  345. static int exec_test(int (*test_sym)(void), faux_list_t **buf_list) {
  346. pid_t pid = -1;
  347. int wstatus = -1;
  348. int pipefd[2];
  349. faux_list_t *blist = NULL;
  350. if (pipe(pipefd))
  351. return -1;
  352. pid = fork();
  353. assert(pid != -1);
  354. if (pid == -1)
  355. return -1;
  356. // Child
  357. if (pid == 0) {
  358. dup2(pipefd[1], 1);
  359. dup2(pipefd[1], 2);
  360. close(pipefd[0]);
  361. close(pipefd[1]);
  362. _exit(test_sym());
  363. }
  364. // Parent
  365. close(pipefd[1]);
  366. blist = read_test_output(pipefd[0], TEST_OUTPUT_LIMIT);
  367. // The pipe closing can lead to test interruption when output length
  368. // limit is exceeded. But it's ok because it saves us from iternal
  369. // loops. It doesn't saves from silent iternal loops.
  370. close(pipefd[0]);
  371. if (blist)
  372. *buf_list = blist;
  373. while (waitpid(pid, &wstatus, 0) != pid);
  374. return wstatus;
  375. }
  376. /** @brief Frees allocated opts_t structure
  377. *
  378. * @param [in] opts Allocated opts_t structure.
  379. */
  380. static void opts_free(opts_t *opts) {
  381. assert(opts);
  382. if (!opts)
  383. return;
  384. faux_list_free(opts->so_list);
  385. faux_free(opts);
  386. }
  387. /** @brief Allocates new opts_t structure
  388. *
  389. * Allocates structure that stores parse command line options.
  390. *
  391. * @return Allocated and initialized opts_t structure.
  392. * @warning The returned opts_t structure must be freed later by opts_free().
  393. */
  394. static opts_t *opts_new(void) {
  395. opts_t *opts = NULL;
  396. opts = faux_zmalloc(sizeof(*opts));
  397. assert(opts);
  398. if (!opts)
  399. return NULL;
  400. opts->debug = BOOL_FALSE;
  401. opts->preserve_tmp = BOOL_FALSE;
  402. // Members of list are static strings from argv so don't free() it
  403. opts->so_list = faux_list_new(FAUX_LIST_UNSORTED, FAUX_LIST_UNIQUE,
  404. (faux_list_cmp_fn)strcmp, NULL, NULL);
  405. if (!opts->so_list) {
  406. opts_free(opts);
  407. return NULL;
  408. }
  409. return opts;
  410. }
  411. /** @brief Parse command line options
  412. *
  413. * Function allocates opts_t structure, parses command line options and
  414. * fills opts_t structure.
  415. *
  416. * @param [in] argc Standard argc argument.
  417. * @param [in] argv Standard argv argument.
  418. * @return Filled opts_t structure with parsed command line options.
  419. * @warning The returned opts_t structure must be freed later by opts_free().
  420. */
  421. static opts_t *opts_parse(int argc, char *argv[]) {
  422. opts_t *opts = NULL;
  423. static const char *shortopts = "hvdt";
  424. #ifdef HAVE_GETOPT_LONG
  425. static const struct option longopts[] = {
  426. {"help", 0, NULL, 'h'},
  427. {"version", 0, NULL, 'v'},
  428. {"debug", 0, NULL, 'd'},
  429. {"preserve-tmp", 0, NULL, 't'},
  430. {NULL, 0, NULL, 0}
  431. };
  432. #endif
  433. opts = opts_new();
  434. if (!opts)
  435. return NULL;
  436. optind = 1;
  437. while (1) {
  438. int opt;
  439. #ifdef HAVE_GETOPT_LONG
  440. opt = getopt_long(argc, argv, shortopts, longopts, NULL);
  441. #else
  442. opt = getopt(argc, argv, shortopts);
  443. #endif
  444. if (-1 == opt)
  445. break;
  446. switch (opt) {
  447. case 'd':
  448. opts->debug = BOOL_TRUE;
  449. break;
  450. case 't':
  451. opts->preserve_tmp = BOOL_TRUE;
  452. break;
  453. case 'h':
  454. help(0, argv[0]);
  455. exit(0);
  456. break;
  457. case 'v':
  458. version(VERSION);
  459. exit(0);
  460. break;
  461. default:
  462. help(-1, argv[0]);
  463. exit(-1);
  464. break;
  465. }
  466. }
  467. if (optind < argc) {
  468. int i = 0;
  469. for (i = optind; i < argc; i++)
  470. faux_list_add(opts->so_list, argv[i]);
  471. } else {
  472. help(-1, argv[0]);
  473. exit(-1);
  474. }
  475. return opts;
  476. }
  477. /** @brief Prints help
  478. *
  479. * @param [in] status If status is not '0' consider help printing as a reaction
  480. * to error and print appropriate message. If status is '0' then print general
  481. * help information.
  482. * @param [in] argv0 The argv[0] argument i.e. programm name
  483. */
  484. static void help(int status, const char *argv0) {
  485. const char *name = NULL;
  486. if (!argv0)
  487. return;
  488. // Find the basename
  489. name = strrchr(argv0, '/');
  490. if (name)
  491. name++;
  492. else
  493. name = argv0;
  494. if (status != 0) {
  495. fprintf(stderr, "Try `%s -h' for more information.\n",
  496. name);
  497. } else {
  498. printf("Usage: %s [options] <so_object> [so_object] ...\n", name);
  499. printf("Unit test helper for C code.\n");
  500. printf("Options:\n");
  501. printf("\t-v, --version\tPrint version.\n");
  502. printf("\t-h, --help\tPrint this help.\n");
  503. printf("\t-d, --debug\tDebug mode. Show output for all tests.\n");
  504. printf("\t-t, --preserve-tmp\tPreserve test's tmp files.\n");
  505. }
  506. }