testc.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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("OK");
  210. attention_str = faux_str_dup("");
  211. // Failed
  212. } else {
  213. result_str = faux_str_sprintf(
  214. "FAIL (%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("SIGNAL (%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("\n");
  265. printf("Module tests: %u\n", module_tests);
  266. printf("Module broken tests: %u\n", module_broken_tests);
  267. printf("Module failed tests: %u\n", module_failed_tests);
  268. printf("Module interrupted tests: %u\n", module_interrupted_tests);
  269. module_errors =
  270. module_broken_tests +
  271. module_failed_tests +
  272. module_interrupted_tests;
  273. printf("Module errors: %u\n", module_errors);
  274. // Gather total statistics
  275. total_tests += module_tests;
  276. total_broken_tests += module_broken_tests;
  277. total_failed_tests += module_failed_tests;
  278. total_interrupted_tests += module_interrupted_tests;
  279. }
  280. opts_free(opts);
  281. // Report total statistics
  282. printf("================================================================================\n");
  283. printf("Total modules: %u\n", total_modules);
  284. printf("Total broken modules: %u\n", total_broken_modules);
  285. printf("Total tests: %u\n", total_tests);
  286. printf("Total broken_tests: %u\n", total_broken_tests);
  287. printf("Total failed tests: %u\n", total_failed_tests);
  288. printf("Total interrupted tests: %u\n", total_interrupted_tests);
  289. total_errors =
  290. total_broken_modules +
  291. total_broken_tests +
  292. total_failed_tests +
  293. total_interrupted_tests;
  294. printf("Total errors: %u\n", total_errors);
  295. if (total_errors > 0)
  296. return -1;
  297. return 0;
  298. }
  299. static void free_iov(struct iovec *iov) {
  300. faux_free(iov->iov_base);
  301. faux_free(iov);
  302. }
  303. static faux_list_t *read_test_output(int fd, size_t limit) {
  304. struct iovec *iov = NULL;
  305. size_t total_len = 0;
  306. faux_list_t *buf_list = NULL; // Buffer list
  307. buf_list = faux_list_new(
  308. FAUX_LIST_UNSORTED, FAUX_LIST_NONUNIQUE,
  309. NULL, NULL, (void (*)(void *))free_iov);
  310. do {
  311. ssize_t bytes_readed = 0;
  312. iov = faux_zmalloc(sizeof(*iov));
  313. assert(iov);
  314. iov->iov_len = CHUNK_SIZE;
  315. iov->iov_base = faux_malloc(iov->iov_len);
  316. assert(iov->iov_base);
  317. do {
  318. bytes_readed = readv(fd, iov, 1);
  319. } while ((bytes_readed < 0) && (errno == EINTR));
  320. if (bytes_readed <= 0) { /* Error or EOF */
  321. free_iov(iov);
  322. break;
  323. }
  324. iov->iov_len = bytes_readed;
  325. faux_list_add(buf_list, iov);
  326. total_len += iov->iov_len;
  327. } while (total_len < limit);
  328. return buf_list;
  329. }
  330. static void print_test_output(faux_list_t *buf_list) {
  331. faux_list_node_t *iter = NULL;
  332. struct iovec *iov = NULL;
  333. iter = faux_list_head(buf_list);
  334. while ((iov = faux_list_each(&iter))) {
  335. faux_write_block(STDOUT_FILENO, iov->iov_base, iov->iov_len);
  336. }
  337. }
  338. /** Executes testing function
  339. *
  340. * Function fork() and executes testing function.
  341. *
  342. * @param [in] test_sym Testing function.
  343. * @param [in] buf_list
  344. * @return Testing function return value
  345. */
  346. static int exec_test(int (*test_sym)(void), faux_list_t **buf_list) {
  347. pid_t pid = -1;
  348. int wstatus = -1;
  349. int pipefd[2];
  350. faux_list_t *blist = NULL;
  351. if (pipe(pipefd))
  352. return -1;
  353. pid = fork();
  354. assert(pid != -1);
  355. if (pid == -1)
  356. return -1;
  357. // Child
  358. if (pid == 0) {
  359. dup2(pipefd[1], 1);
  360. dup2(pipefd[1], 2);
  361. close(pipefd[0]);
  362. close(pipefd[1]);
  363. _exit(test_sym());
  364. }
  365. // Parent
  366. close(pipefd[1]);
  367. blist = read_test_output(pipefd[0], TEST_OUTPUT_LIMIT);
  368. // The pipe closing can lead to test interruption when output length
  369. // limit is exceeded. But it's ok because it saves us from iternal
  370. // loops. It doesn't saves from silent iternal loops.
  371. close(pipefd[0]);
  372. if (blist)
  373. *buf_list = blist;
  374. while (waitpid(pid, &wstatus, 0) != pid);
  375. return wstatus;
  376. }
  377. /** @brief Frees allocated opts_t structure
  378. *
  379. * @param [in] opts Allocated opts_t structure.
  380. */
  381. static void opts_free(opts_t *opts) {
  382. assert(opts);
  383. if (!opts)
  384. return;
  385. faux_list_free(opts->so_list);
  386. faux_free(opts);
  387. }
  388. /** @brief Allocates new opts_t structure
  389. *
  390. * Allocates structure that stores parse command line options.
  391. *
  392. * @return Allocated and initialized opts_t structure.
  393. * @warning The returned opts_t structure must be freed later by opts_free().
  394. */
  395. static opts_t *opts_new(void) {
  396. opts_t *opts = NULL;
  397. opts = faux_zmalloc(sizeof(*opts));
  398. assert(opts);
  399. if (!opts)
  400. return NULL;
  401. opts->debug = BOOL_FALSE;
  402. opts->preserve_tmp = BOOL_FALSE;
  403. // Members of list are static strings from argv so don't free() it
  404. opts->so_list = faux_list_new(FAUX_LIST_UNSORTED, FAUX_LIST_UNIQUE,
  405. (faux_list_cmp_fn)strcmp, NULL, NULL);
  406. if (!opts->so_list) {
  407. opts_free(opts);
  408. return NULL;
  409. }
  410. return opts;
  411. }
  412. /** @brief Parse command line options
  413. *
  414. * Function allocates opts_t structure, parses command line options and
  415. * fills opts_t structure.
  416. *
  417. * @param [in] argc Standard argc argument.
  418. * @param [in] argv Standard argv argument.
  419. * @return Filled opts_t structure with parsed command line options.
  420. * @warning The returned opts_t structure must be freed later by opts_free().
  421. */
  422. static opts_t *opts_parse(int argc, char *argv[]) {
  423. opts_t *opts = NULL;
  424. static const char *shortopts = "hvdt";
  425. #ifdef HAVE_GETOPT_LONG
  426. static const struct option longopts[] = {
  427. {"help", 0, NULL, 'h'},
  428. {"version", 0, NULL, 'v'},
  429. {"debug", 0, NULL, 'd'},
  430. {"preserve-tmp", 0, NULL, 't'},
  431. {NULL, 0, NULL, 0}
  432. };
  433. #endif
  434. opts = opts_new();
  435. if (!opts)
  436. return NULL;
  437. optind = 1;
  438. while (1) {
  439. int opt;
  440. #ifdef HAVE_GETOPT_LONG
  441. opt = getopt_long(argc, argv, shortopts, longopts, NULL);
  442. #else
  443. opt = getopt(argc, argv, shortopts);
  444. #endif
  445. if (-1 == opt)
  446. break;
  447. switch (opt) {
  448. case 'd':
  449. opts->debug = BOOL_TRUE;
  450. break;
  451. case 't':
  452. opts->preserve_tmp = BOOL_TRUE;
  453. break;
  454. case 'h':
  455. help(0, argv[0]);
  456. exit(0);
  457. break;
  458. case 'v':
  459. version(VERSION);
  460. exit(0);
  461. break;
  462. default:
  463. help(-1, argv[0]);
  464. exit(-1);
  465. break;
  466. }
  467. }
  468. if (optind < argc) {
  469. int i = 0;
  470. for (i = optind; i < argc; i++)
  471. faux_list_add(opts->so_list, argv[i]);
  472. } else {
  473. help(-1, argv[0]);
  474. exit(-1);
  475. }
  476. return opts;
  477. }
  478. /** @brief Prints help
  479. *
  480. * @param [in] status If status is not '0' consider help printing as a reaction
  481. * to error and print appropriate message. If status is '0' then print general
  482. * help information.
  483. * @param [in] argv0 The argv[0] argument i.e. programm name
  484. */
  485. static void help(int status, const char *argv0) {
  486. const char *name = NULL;
  487. if (!argv0)
  488. return;
  489. // Find the basename
  490. name = strrchr(argv0, '/');
  491. if (name)
  492. name++;
  493. else
  494. name = argv0;
  495. if (status != 0) {
  496. fprintf(stderr, "Try `%s -h' for more information.\n",
  497. name);
  498. } else {
  499. printf("Usage: %s [options] <so_object> [so_object] ...\n", name);
  500. printf("Unit test helper for C code.\n");
  501. printf("Options:\n");
  502. printf("\t-v, --version\tPrint version.\n");
  503. printf("\t-h, --help\tPrint this help.\n");
  504. printf("\t-d, --debug\tDebug mode. Show output for all tests.\n");
  505. printf("\t-t, --preserve-tmp\tPreserve test's tmp files.\n");
  506. }
  507. }