testc.c 15 KB

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