Tweaked __ast_test_suite_assert_notify() and __ast_test_suite_event_notify() to be...
[asterisk/asterisk.git] / main / test.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2009-2010, Digium, Inc.
5  *
6  * David Vossel <dvossel@digium.com>
7  * Russell Bryant <russell@digium.com>
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*!
21  * \file
22  * \brief Unit Test Framework
23  *
24  * \author David Vossel <dvossel@digium.com>
25  * \author Russell Bryant <russell@digium.com>
26  */
27
28 /*** MODULEINFO
29         <support_level>core</support_level>
30  ***/
31
32 #include "asterisk.h"
33
34 ASTERISK_FILE_VERSION(__FILE__, "$Revision$");
35
36 #include "asterisk/_private.h"
37
38 #ifdef TEST_FRAMEWORK
39 #include "asterisk/test.h"
40 #include "asterisk/logger.h"
41 #include "asterisk/linkedlists.h"
42 #include "asterisk/utils.h"
43 #include "asterisk/cli.h"
44 #include "asterisk/term.h"
45 #include "asterisk/ast_version.h"
46 #include "asterisk/paths.h"
47 #include "asterisk/time.h"
48 #include "asterisk/manager.h"
49
50 /*! This array corresponds to the values defined in the ast_test_state enum */
51 static const char * const test_result2str[] = {
52         [AST_TEST_NOT_RUN] = "NOT RUN",
53         [AST_TEST_PASS]    = "PASS",
54         [AST_TEST_FAIL]    = "FAIL",
55 };
56
57 /*! holds all the information pertaining to a single defined test */
58 struct ast_test {
59         struct ast_test_info info;        /*!< holds test callback information */
60         /*!
61          * \brief Test defined status output from last execution
62          */
63         struct ast_str *status_str;
64         /*!
65          * \brief CLI arguments, if tests being run from the CLI
66          *
67          * If this is set, status updates from the tests will be sent to the
68          * CLI in addition to being saved off in status_str.
69          */
70         struct ast_cli_args *cli;
71         enum ast_test_result_state state; /*!< current test state */
72         unsigned int time;                /*!< time in ms test took */
73         ast_test_cb_t *cb;                /*!< test callback function */
74         AST_LIST_ENTRY(ast_test) entry;
75 };
76
77 /*! global structure containing both total and last test execution results */
78 static struct ast_test_execute_results {
79         unsigned int total_tests;  /*!< total number of tests, regardless if they have been executed or not */
80         unsigned int total_passed; /*!< total number of executed tests passed */
81         unsigned int total_failed; /*!< total number of executed tests failed */
82         unsigned int total_time;   /*!< total time of all executed tests */
83         unsigned int last_passed;  /*!< number of passed tests during last execution */
84         unsigned int last_failed;  /*!< number of failed tests during last execution */
85         unsigned int last_time;    /*!< total time of the last test execution */
86 } last_results;
87
88 enum test_mode {
89         TEST_ALL = 0,
90         TEST_CATEGORY = 1,
91         TEST_NAME_CATEGORY = 2,
92 };
93
94 /*! List of registered test definitions */
95 static AST_LIST_HEAD_STATIC(tests, ast_test);
96
97 static struct ast_test *test_alloc(ast_test_cb_t *cb);
98 static struct ast_test *test_free(struct ast_test *test);
99 static int test_insert(struct ast_test *test);
100 static struct ast_test *test_remove(ast_test_cb_t *cb);
101 static int test_cat_cmp(const char *cat1, const char *cat2);
102
103 void ast_test_debug(struct ast_test *test, const char *fmt, ...)
104 {
105         struct ast_str *buf = NULL;
106         va_list ap;
107
108         buf = ast_str_create(128);
109         if (!buf) {
110                 return;
111         }
112
113         va_start(ap, fmt);
114         ast_str_set_va(&buf, 0, fmt, ap);
115         va_end(ap);
116
117         if (test->cli) {
118                 ast_cli(test->cli->fd, "%s", ast_str_buffer(buf));
119         }
120
121         ast_free(buf);
122 }
123
124 int __ast_test_status_update(const char *file, const char *func, int line, struct ast_test *test, const char *fmt, ...)
125 {
126         struct ast_str *buf = NULL;
127         va_list ap;
128
129         if (!(buf = ast_str_create(128))) {
130                 return -1;
131         }
132
133         va_start(ap, fmt);
134         ast_str_set_va(&buf, 0, fmt, ap);
135         va_end(ap);
136
137         if (test->cli) {
138                 ast_cli(test->cli->fd, "[%s:%s:%d]: %s",
139                                 file, func, line, ast_str_buffer(buf));
140         }
141
142         ast_str_append(&test->status_str, 0, "[%s:%s:%d]: %s",
143                         file, func, line, ast_str_buffer(buf));
144
145         ast_free(buf);
146
147         return 0;
148 }
149
150 int ast_test_register(ast_test_cb_t *cb)
151 {
152         struct ast_test *test;
153
154         if (!cb) {
155                 ast_log(LOG_WARNING, "Attempted to register test without all required information\n");
156                 return -1;
157         }
158
159         if (!(test = test_alloc(cb))) {
160                 return -1;
161         }
162
163         if (test_insert(test)) {
164                 test_free(test);
165                 return -1;
166         }
167
168         return 0;
169 }
170
171 int ast_test_unregister(ast_test_cb_t *cb)
172 {
173         struct ast_test *test;
174
175         if (!(test = test_remove(cb))) {
176                 return -1; /* not found */
177         }
178
179         test_free(test);
180
181         return 0;
182 }
183
184 /*!
185  * \internal
186  * \brief executes a single test, storing the results in the test->result structure.
187  *
188  * \note The last_results structure which contains global statistics about test execution
189  * must be updated when using this function. See use in test_execute_multiple().
190  */
191 static void test_execute(struct ast_test *test)
192 {
193         struct timeval begin;
194
195         ast_str_reset(test->status_str);
196
197         begin = ast_tvnow();
198         test->state = test->cb(&test->info, TEST_EXECUTE, test);
199         test->time = ast_tvdiff_ms(ast_tvnow(), begin);
200 }
201
202 static void test_xml_entry(struct ast_test *test, FILE *f)
203 {
204         if (!f || !test || test->state == AST_TEST_NOT_RUN) {
205                 return;
206         }
207
208         fprintf(f, "\t<testcase time=\"%d.%d\" name=\"%s%s\"%s>\n",
209                         test->time / 1000, test->time % 1000,
210                         test->info.category, test->info.name,
211                         test->state == AST_TEST_PASS ? "/" : "");
212
213         if (test->state == AST_TEST_FAIL) {
214                 fprintf(f, "\t\t<failure><![CDATA[\n%s\n\t\t]]></failure>\n",
215                                 S_OR(ast_str_buffer(test->status_str), "NA"));
216                 fprintf(f, "\t</testcase>\n");
217         }
218
219 }
220
221 static void test_txt_entry(struct ast_test *test, FILE *f)
222 {
223         if (!f || !test) {
224                 return;
225         }
226
227         fprintf(f, "\nName:              %s\n", test->info.name);
228         fprintf(f,   "Category:          %s\n", test->info.category);
229         fprintf(f,   "Summary:           %s\n", test->info.summary);
230         fprintf(f,   "Description:       %s\n", test->info.description);
231         fprintf(f,   "Result:            %s\n", test_result2str[test->state]);
232         if (test->state != AST_TEST_NOT_RUN) {
233                 fprintf(f,   "Time:              %d\n", test->time);
234         }
235         if (test->state == AST_TEST_FAIL) {
236                 fprintf(f,   "Error Description: %s\n\n", S_OR(ast_str_buffer(test->status_str), "NA"));
237         }
238 }
239
240 /*!
241  * \internal
242  * \brief Executes registered unit tests
243  *
244  * \param name of test to run (optional)
245  * \param test category to run (optional)
246  * \param cli args for cli test updates (optional)
247  *
248  * \return number of tests executed.
249  *
250  * \note This function has three modes of operation
251  * -# When given a name and category, a matching individual test will execute if found.
252  * -# When given only a category all matching tests within that category will execute.
253  * -# If given no name or category all registered tests will execute.
254  */
255 static int test_execute_multiple(const char *name, const char *category, struct ast_cli_args *cli)
256 {
257         char result_buf[32] = { 0 };
258         struct ast_test *test = NULL;
259         enum test_mode mode = TEST_ALL; /* 3 modes, 0 = run all, 1 = only by category, 2 = only by name and category */
260         int execute = 0;
261         int res = 0;
262
263         if (!ast_strlen_zero(category)) {
264                 if (!ast_strlen_zero(name)) {
265                         mode = TEST_NAME_CATEGORY;
266                 } else {
267                         mode = TEST_CATEGORY;
268                 }
269         }
270
271         AST_LIST_LOCK(&tests);
272         /* clear previous execution results */
273         memset(&last_results, 0, sizeof(last_results));
274         AST_LIST_TRAVERSE(&tests, test, entry) {
275
276                 execute = 0;
277                 switch (mode) {
278                 case TEST_CATEGORY:
279                         if (!test_cat_cmp(test->info.category, category)) {
280                                 execute = 1;
281                         }
282                         break;
283                 case TEST_NAME_CATEGORY:
284                         if (!(test_cat_cmp(test->info.category, category)) && !(strcmp(test->info.name, name))) {
285                                 execute = 1;
286                         }
287                         break;
288                 case TEST_ALL:
289                         execute = 1;
290                 }
291
292                 if (execute) {
293                         if (cli) {
294                                 ast_cli(cli->fd, "START  %s - %s \n", test->info.category, test->info.name);
295                         }
296
297                         /* set the test status update argument. it is ok if cli is NULL */
298                         test->cli = cli;
299
300                         /* execute the test and save results */
301                         test_execute(test);
302
303                         test->cli = NULL;
304
305                         /* update execution specific counts here */
306                         last_results.last_time += test->time;
307                         if (test->state == AST_TEST_PASS) {
308                                 last_results.last_passed++;
309                         } else if (test->state == AST_TEST_FAIL) {
310                                 last_results.last_failed++;
311                         }
312
313                         if (cli) {
314                                 term_color(result_buf,
315                                         test_result2str[test->state],
316                                         (test->state == AST_TEST_FAIL) ? COLOR_RED : COLOR_GREEN,
317                                         0,
318                                         sizeof(result_buf));
319                                 ast_cli(cli->fd, "END    %s - %s Time: %s%dms Result: %s\n",
320                                         test->info.category,
321                                         test->info.name,
322                                         test->time ? "" : "<",
323                                         test->time ? test->time : 1,
324                                         result_buf);
325                         }
326                 }
327
328                 /* update total counts as well during this iteration
329                  * even if the current test did not execute this time */
330                 last_results.total_time += test->time;
331                 last_results.total_tests++;
332                 if (test->state != AST_TEST_NOT_RUN) {
333                         if (test->state == AST_TEST_PASS) {
334                                 last_results.total_passed++;
335                         } else {
336                                 last_results.total_failed++;
337                         }
338                 }
339         }
340         res = last_results.last_passed + last_results.last_failed;
341         AST_LIST_UNLOCK(&tests);
342
343         return res;
344 }
345
346 /*!
347  * \internal
348  * \brief Generate test results.
349  *
350  * \param name of test result to generate (optional)
351  * \param test category to generate (optional)
352  * \param path to xml file to generate. (optional)
353  * \param path to txt file to generate, (optional)
354  *
355  * \retval 0 success
356  * \retval -1 failure
357  *
358  * \note This function has three modes of operation.
359  * -# When given both a name and category, results will be generated for that single test.
360  * -# When given only a category, results for every test within the category will be generated.
361  * -# When given no name or category, results for every registered test will be generated.
362  *
363  * In order for the results to be generated, an xml and or txt file path must be provided.
364  */
365 static int test_generate_results(const char *name, const char *category, const char *xml_path, const char *txt_path)
366 {
367         enum test_mode mode = TEST_ALL;  /* 0 generate all, 1 generate by category only, 2 generate by name and category */
368         FILE *f_xml = NULL, *f_txt = NULL;
369         int res = 0;
370         struct ast_test *test = NULL;
371
372         /* verify at least one output file was given */
373         if (ast_strlen_zero(xml_path) && ast_strlen_zero(txt_path)) {
374                 return -1;
375         }
376
377         /* define what mode is to be used */
378         if (!ast_strlen_zero(category)) {
379                 if (!ast_strlen_zero(name)) {
380                         mode = TEST_NAME_CATEGORY;
381                 } else {
382                         mode = TEST_CATEGORY;
383                 }
384         }
385         /* open files for writing */
386         if (!ast_strlen_zero(xml_path)) {
387                 if (!(f_xml = fopen(xml_path, "w"))) {
388                         ast_log(LOG_WARNING, "Could not open file %s for xml test results\n", xml_path);
389                         res = -1;
390                         goto done;
391                 }
392         }
393         if (!ast_strlen_zero(txt_path)) {
394                 if (!(f_txt = fopen(txt_path, "w"))) {
395                         ast_log(LOG_WARNING, "Could not open file %s for text output of test results\n", txt_path);
396                         res = -1;
397                         goto done;
398                 }
399         }
400
401         AST_LIST_LOCK(&tests);
402         /* xml header information */
403         if (f_xml) {
404                 /*
405                  * http://confluence.atlassian.com/display/BAMBOO/JUnit+parsing+in+Bamboo
406                  */
407                 fprintf(f_xml, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
408                 fprintf(f_xml, "<testsuite errors=\"0\" time=\"%d.%d\" tests=\"%d\" "
409                                 "name=\"AsteriskUnitTests\">\n",
410                                 last_results.total_time / 1000, last_results.total_time % 1000,
411                                 last_results.total_tests);
412                 fprintf(f_xml, "\t<properties>\n");
413                 fprintf(f_xml, "\t\t<property name=\"version\" value=\"%s\"/>\n", ast_get_version());
414                 fprintf(f_xml, "\t</properties>\n");
415         }
416
417         /* txt header information */
418         if (f_txt) {
419                 fprintf(f_txt, "Asterisk Version:         %s\n", ast_get_version());
420                 fprintf(f_txt, "Asterisk Version Number:  %s\n", ast_get_version_num());
421                 fprintf(f_txt, "Number of Tests:          %d\n", last_results.total_tests);
422                 fprintf(f_txt, "Number of Tests Executed: %d\n", (last_results.total_passed + last_results.total_failed));
423                 fprintf(f_txt, "Passed Tests:             %d\n", last_results.total_passed);
424                 fprintf(f_txt, "Failed Tests:             %d\n", last_results.total_failed);
425                 fprintf(f_txt, "Total Execution Time:     %d\n", last_results.total_time);
426         }
427
428         /* export each individual test */
429         AST_LIST_TRAVERSE(&tests, test, entry) {
430                 switch (mode) {
431                 case TEST_CATEGORY:
432                         if (!test_cat_cmp(test->info.category, category)) {
433                                 test_xml_entry(test, f_xml);
434                                 test_txt_entry(test, f_txt);
435                         }
436                         break;
437                 case TEST_NAME_CATEGORY:
438                         if (!(strcmp(test->info.category, category)) && !(strcmp(test->info.name, name))) {
439                                 test_xml_entry(test, f_xml);
440                                 test_txt_entry(test, f_txt);
441                         }
442                         break;
443                 case TEST_ALL:
444                         test_xml_entry(test, f_xml);
445                         test_txt_entry(test, f_txt);
446                 }
447         }
448         AST_LIST_UNLOCK(&tests);
449
450 done:
451         if (f_xml) {
452                 fprintf(f_xml, "</testsuite>\n");
453                 fclose(f_xml);
454         }
455         if (f_txt) {
456                 fclose(f_txt);
457         }
458
459         return res;
460 }
461
462 /*!
463  * \internal
464  * \brief adds test to container sorted first by category then by name
465  *
466  * \retval 0 success
467  * \retval -1 failure
468  */
469 static int test_insert(struct ast_test *test)
470 {
471         /* This is a slow operation that may need to be optimized in the future
472          * as the test framework expands.  At the moment we are doing string
473          * comparisons on every item within the list to insert in sorted order. */
474
475         AST_LIST_LOCK(&tests);
476         AST_LIST_INSERT_SORTALPHA(&tests, test, entry, info.category);
477         AST_LIST_UNLOCK(&tests);
478
479         return 0;
480 }
481
482 /*!
483  * \internal
484  * \brief removes test from container
485  *
486  * \return ast_test removed from list on success, or NULL on failure
487  */
488 static struct ast_test *test_remove(ast_test_cb_t *cb)
489 {
490         struct ast_test *cur = NULL;
491
492         AST_LIST_LOCK(&tests);
493         AST_LIST_TRAVERSE_SAFE_BEGIN(&tests, cur, entry) {
494                 if (cur->cb == cb) {
495                         AST_LIST_REMOVE_CURRENT(entry);
496                         break;
497                 }
498         }
499         AST_LIST_TRAVERSE_SAFE_END;
500         AST_LIST_UNLOCK(&tests);
501
502         return cur;
503 }
504
505 /*!
506  * \brief compares two test categories to determine if cat1 resides in cat2
507  * \internal
508  *
509  * \retval 0 true
510  * \retval non-zero false
511  */
512
513 static int test_cat_cmp(const char *cat1, const char *cat2)
514 {
515         int len1 = 0;
516         int len2 = 0;
517
518         if (!cat1 || !cat2) {
519                 return -1;
520         }
521
522         len1 = strlen(cat1);
523         len2 = strlen(cat2);
524
525         if (len2 > len1) {
526                 return -1;
527         }
528
529         return strncmp(cat1, cat2, len2) ? 1 : 0;
530 }
531
532 /*!
533  * \internal
534  * \brief free an ast_test object and all it's data members
535  */
536 static struct ast_test *test_free(struct ast_test *test)
537 {
538         if (!test) {
539                 return NULL;
540         }
541
542         ast_free(test->status_str);
543         ast_free(test);
544
545         return NULL;
546 }
547
548 /*!
549  * \internal
550  * \brief allocate an ast_test object.
551  */
552 static struct ast_test *test_alloc(ast_test_cb_t *cb)
553 {
554         struct ast_test *test;
555
556         if (!cb || !(test = ast_calloc(1, sizeof(*test)))) {
557                 return NULL;
558         }
559
560         test->cb = cb;
561
562         test->cb(&test->info, TEST_INIT, test);
563
564         if (ast_strlen_zero(test->info.name)) {
565                 ast_log(LOG_WARNING, "Test has no name, test registration refused.\n");
566                 return test_free(test);
567         }
568
569         if (ast_strlen_zero(test->info.category)) {
570                 ast_log(LOG_WARNING, "Test %s has no category, test registration refused.\n",
571                                 test->info.name);
572                 return test_free(test);
573         }
574
575         if (test->info.category[0] != '/' || test->info.category[strlen(test->info.category) - 1] != '/') {
576                 ast_log(LOG_WARNING, "Test category '%s' for test '%s' is missing a leading or trailing slash.\n",
577                                 test->info.category, test->info.name);
578         }
579
580         if (ast_strlen_zero(test->info.summary)) {
581                 ast_log(LOG_WARNING, "Test %s%s has no summary, test registration refused.\n",
582                                 test->info.category, test->info.name);
583                 return test_free(test);
584         }
585
586         if (ast_strlen_zero(test->info.description)) {
587                 ast_log(LOG_WARNING, "Test %s%s has no description, test registration refused.\n",
588                                 test->info.category, test->info.name);
589                 return test_free(test);
590         }
591
592         if (!(test->status_str = ast_str_create(128))) {
593                 return test_free(test);
594         }
595
596         return test;
597 }
598
599 static char *complete_test_category(const char *line, const char *word, int pos, int state)
600 {
601         int which = 0;
602         int wordlen = strlen(word);
603         char *ret = NULL;
604         struct ast_test *test;
605
606         AST_LIST_LOCK(&tests);
607         AST_LIST_TRAVERSE(&tests, test, entry) {
608                 if (!strncasecmp(word, test->info.category, wordlen) && ++which > state) {
609                         ret = ast_strdup(test->info.category);
610                         break;
611                 }
612         }
613         AST_LIST_UNLOCK(&tests);
614         return ret;
615 }
616
617 static char *complete_test_name(const char *line, const char *word, int pos, int state, const char *category)
618 {
619         int which = 0;
620         int wordlen = strlen(word);
621         char *ret = NULL;
622         struct ast_test *test;
623
624         AST_LIST_LOCK(&tests);
625         AST_LIST_TRAVERSE(&tests, test, entry) {
626                 if (!test_cat_cmp(test->info.category, category) && (!strncasecmp(word, test->info.name, wordlen) && ++which > state)) {
627                         ret = ast_strdup(test->info.name);
628                         break;
629                 }
630         }
631         AST_LIST_UNLOCK(&tests);
632         return ret;
633 }
634
635 /* CLI commands */
636 static char *test_cli_show_registered(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
637 {
638 #define FORMAT "%-25.25s %-30.30s %-40.40s %-13.13s\n"
639         static const char * const option1[] = { "all", "category", NULL };
640         static const char * const option2[] = { "name", NULL };
641         struct ast_test *test = NULL;
642         int count = 0;
643         switch (cmd) {
644         case CLI_INIT:
645                 e->command = "test show registered";
646
647                 e->usage =
648                         "Usage: 'test show registered' can be used in three ways.\n"
649                         "       1. 'test show registered all' shows all registered tests\n"
650                         "       2. 'test show registered category [test category]' shows all tests in the given\n"
651                         "          category.\n"
652                         "       3. 'test show registered category [test category] name [test name]' shows all\n"
653                         "           tests in a given category matching a given name\n";
654                 return NULL;
655         case CLI_GENERATE:
656                 if (a->pos == 3) {
657                         return ast_cli_complete(a->word, option1, a->n);
658                 }
659                 if (a->pos == 4) {
660                         return complete_test_category(a->line, a->word, a->pos, a->n);
661                 }
662                 if (a->pos == 5) {
663                         return ast_cli_complete(a->word, option2, a->n);
664                 }
665                 if (a->pos == 6) {
666                         return complete_test_name(a->line, a->word, a->pos, a->n, a->argv[3]);
667                 }
668                 return NULL;
669         case CLI_HANDLER:
670                 if ((a->argc < 4) || (a->argc == 6) || (a->argc > 7) ||
671                         ((a->argc == 4) && strcmp(a->argv[3], "all")) ||
672                         ((a->argc == 7) && strcmp(a->argv[5], "name"))) {
673                         return CLI_SHOWUSAGE;
674                 }
675                 ast_cli(a->fd, FORMAT, "Category", "Name", "Summary", "Test Result");
676                 ast_cli(a->fd, FORMAT, "--------", "----", "-------", "-----------");
677                 AST_LIST_LOCK(&tests);
678                 AST_LIST_TRAVERSE(&tests, test, entry) {
679                         if ((a->argc == 4) ||
680                                  ((a->argc == 5) && !test_cat_cmp(test->info.category, a->argv[4])) ||
681                                  ((a->argc == 7) && !strcmp(test->info.category, a->argv[4]) && !strcmp(test->info.name, a->argv[6]))) {
682
683                                 ast_cli(a->fd, FORMAT, test->info.category, test->info.name,
684                                                 test->info.summary, test_result2str[test->state]);
685                                 count++;
686                         }
687                 }
688                 AST_LIST_UNLOCK(&tests);
689                 ast_cli(a->fd, FORMAT, "--------", "----", "-------", "-----------");
690                 ast_cli(a->fd, "\n%d Registered Tests Matched\n", count);
691         default:
692                 return NULL;
693         }
694
695         return CLI_SUCCESS;
696 }
697
698 static char *test_cli_execute_registered(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
699 {
700         static const char * const option1[] = { "all", "category", NULL };
701         static const char * const option2[] = { "name", NULL };
702
703         switch (cmd) {
704         case CLI_INIT:
705                 e->command = "test execute";
706                 e->usage =
707                         "Usage: test execute can be used in three ways.\n"
708                         "       1. 'test execute all' runs all registered tests\n"
709                         "       2. 'test execute category [test category]' runs all tests in the given\n"
710                         "          category.\n"
711                         "       3. 'test execute category [test category] name [test name]' runs all\n"
712                         "           tests in a given category matching a given name\n";
713                 return NULL;
714         case CLI_GENERATE:
715                 if (a->pos == 2) {
716                         return ast_cli_complete(a->word, option1, a->n);
717                 }
718                 if (a->pos == 3) {
719                         return complete_test_category(a->line, a->word, a->pos, a->n);
720                 }
721                 if (a->pos == 4) {
722                         return ast_cli_complete(a->word, option2, a->n);
723                 }
724                 if (a->pos == 5) {
725                         return complete_test_name(a->line, a->word, a->pos, a->n, a->argv[3]);
726                 }
727                 return NULL;
728         case CLI_HANDLER:
729
730                 if (a->argc < 3|| a->argc > 6) {
731                         return CLI_SHOWUSAGE;
732                 }
733
734                 if ((a->argc == 3) && !strcmp(a->argv[2], "all")) { /* run all registered tests */
735                         ast_cli(a->fd, "Running all available tests...\n\n");
736                         test_execute_multiple(NULL, NULL, a);
737                 } else if (a->argc == 4) { /* run only tests within a category */
738                         ast_cli(a->fd, "Running all available tests matching category %s\n\n", a->argv[3]);
739                         test_execute_multiple(NULL, a->argv[3], a);
740                 } else if (a->argc == 6) { /* run only a single test matching the category and name */
741                         ast_cli(a->fd, "Running all available tests matching category %s and name %s\n\n", a->argv[3], a->argv[5]);
742                         test_execute_multiple(a->argv[5], a->argv[3], a);
743                 } else {
744                         return CLI_SHOWUSAGE;
745                 }
746
747                 AST_LIST_LOCK(&tests);
748                 if (!(last_results.last_passed + last_results.last_failed)) {
749                         ast_cli(a->fd, "--- No Tests Found! ---\n");
750                 }
751                 ast_cli(a->fd, "\n%d Test(s) Executed  %d Passed  %d Failed\n",
752                         (last_results.last_passed + last_results.last_failed),
753                         last_results.last_passed,
754                         last_results.last_failed);
755                 AST_LIST_UNLOCK(&tests);
756         default:
757                 return NULL;
758         }
759
760         return CLI_SUCCESS;
761 }
762
763 static char *test_cli_show_results(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
764 {
765 #define FORMAT_RES_ALL1 "%s%s %-30.30s %-25.25s %-10.10s\n"
766 #define FORMAT_RES_ALL2 "%s%s %-30.30s %-25.25s %s%ums\n"
767         static const char * const option1[] = { "all", "failed", "passed", NULL };
768         char result_buf[32] = { 0 };
769         struct ast_test *test = NULL;
770         int failed = 0;
771         int passed = 0;
772         int mode;  /* 0 for show all, 1 for show fail, 2 for show passed */
773
774         switch (cmd) {
775         case CLI_INIT:
776                 e->command = "test show results";
777                 e->usage =
778                         "Usage: test show results can be used in three ways\n"
779                         "       1. 'test show results all' Displays results for all executed tests.\n"
780                         "       2. 'test show results passed' Displays results for all passed tests.\n"
781                         "       3. 'test show results failed' Displays results for all failed tests.\n";
782                 return NULL;
783         case CLI_GENERATE:
784                 if (a->pos == 3) {
785                         return ast_cli_complete(a->word, option1, a->n);
786                 }
787                 return NULL;
788         case CLI_HANDLER:
789
790                 /* verify input */
791                 if (a->argc != 4) {
792                         return CLI_SHOWUSAGE;
793                 } else if (!strcmp(a->argv[3], "passed")) {
794                         mode = 2;
795                 } else if (!strcmp(a->argv[3], "failed")) {
796                         mode = 1;
797                 } else if (!strcmp(a->argv[3], "all")) {
798                         mode = 0;
799                 } else {
800                         return CLI_SHOWUSAGE;
801                 }
802
803                 ast_cli(a->fd, FORMAT_RES_ALL1, "Result", "", "Name", "Category", "Time");
804                 AST_LIST_LOCK(&tests);
805                 AST_LIST_TRAVERSE(&tests, test, entry) {
806                         if (test->state == AST_TEST_NOT_RUN) {
807                                 continue;
808                         }
809                         test->state == AST_TEST_FAIL ? failed++ : passed++;
810                         if (!mode || ((mode == 1) && (test->state == AST_TEST_FAIL)) || ((mode == 2) && (test->state == AST_TEST_PASS))) {
811                                 /* give our results pretty colors */
812                                 term_color(result_buf, test_result2str[test->state],
813                                         (test->state == AST_TEST_FAIL) ? COLOR_RED : COLOR_GREEN,
814                                         0, sizeof(result_buf));
815
816                                 ast_cli(a->fd, FORMAT_RES_ALL2,
817                                         result_buf,
818                                         "  ",
819                                         test->info.name,
820                                         test->info.category,
821                                         test->time ? " " : "<",
822                                         test->time ? test->time : 1);
823                         }
824                 }
825                 AST_LIST_UNLOCK(&tests);
826
827                 ast_cli(a->fd, "%d Test(s) Executed  %d Passed  %d Failed\n", (failed + passed), passed, failed);
828         default:
829                 return NULL;
830         }
831         return CLI_SUCCESS;
832 }
833
834 static char *test_cli_generate_results(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
835 {
836         static const char * const option[] = { "xml", "txt", NULL };
837         const char *file = NULL;
838         const char *type = "";
839         int isxml = 0;
840         int res = 0;
841         struct ast_str *buf = NULL;
842         struct timeval time = ast_tvnow();
843
844         switch (cmd) {
845         case CLI_INIT:
846                 e->command = "test generate results";
847                 e->usage =
848                         "Usage: 'test generate results'\n"
849                         "       Generates test results in either xml or txt format. An optional \n"
850                         "       file path may be provided to specify the location of the xml or\n"
851                         "       txt file\n"
852                         "       \nExample usage:\n"
853                         "       'test generate results xml' this writes to a default file\n"
854                         "       'test generate results xml /path/to/file.xml' writes to specified file\n";
855                 return NULL;
856         case CLI_GENERATE:
857                 if (a->pos == 3) {
858                         return ast_cli_complete(a->word, option, a->n);
859                 }
860                 return NULL;
861         case CLI_HANDLER:
862
863                 /* verify input */
864                 if (a->argc < 4 || a->argc > 5) {
865                         return CLI_SHOWUSAGE;
866                 } else if (!strcmp(a->argv[3], "xml")) {
867                         type = "xml";
868                         isxml = 1;
869                 } else if (!strcmp(a->argv[3], "txt")) {
870                         type = "txt";
871                 } else {
872                         return CLI_SHOWUSAGE;
873                 }
874
875                 if (a->argc == 5) {
876                         file = a->argv[4];
877                 } else {
878                         if (!(buf = ast_str_create(256))) {
879                                 return NULL;
880                         }
881                         ast_str_set(&buf, 0, "%s/asterisk_test_results-%ld.%s", ast_config_AST_LOG_DIR, (long) time.tv_sec, type);
882
883                         file = ast_str_buffer(buf);
884                 }
885
886                 if (isxml) {
887                         res = test_generate_results(NULL, NULL, file, NULL);
888                 } else {
889                         res = test_generate_results(NULL, NULL, NULL, file);
890                 }
891
892                 if (!res) {
893                         ast_cli(a->fd, "Results Generated Successfully: %s\n", S_OR(file, ""));
894                 } else {
895                         ast_cli(a->fd, "Results Could Not Be Generated: %s\n", S_OR(file, ""));
896                 }
897
898                 ast_free(buf);
899         default:
900                 return NULL;
901         }
902
903         return CLI_SUCCESS;
904 }
905
906 static struct ast_cli_entry test_cli[] = {
907         AST_CLI_DEFINE(test_cli_show_registered,           "show registered tests"),
908         AST_CLI_DEFINE(test_cli_execute_registered,        "execute registered tests"),
909         AST_CLI_DEFINE(test_cli_show_results,              "show last test results"),
910         AST_CLI_DEFINE(test_cli_generate_results,          "generate test results to file"),
911 };
912
913 void __ast_test_suite_event_notify(const char *file, const char *func, int line, const char *state, const char *fmt, ...)
914 {
915         struct ast_str *buf = NULL;
916         va_list ap;
917
918         if (!(buf = ast_str_create(128))) {
919                 return;
920         }
921
922         va_start(ap, fmt);
923         ast_str_set_va(&buf, 0, fmt, ap);
924         va_end(ap);
925
926         manager_event(EVENT_FLAG_TEST, "TestEvent",
927                 "Type: StateChange\r\n"
928                 "State: %s\r\n"
929                 "AppFile: %s\r\n"
930                 "AppFunction: %s\r\n"
931                 "AppLine: %d\r\n"
932                 "%s\r\n",
933                 state, file, func, line, ast_str_buffer(buf));
934
935         ast_free(buf);
936 }
937
938 void __ast_test_suite_assert_notify(const char *file, const char *func, int line, const char *exp)
939 {
940         manager_event(EVENT_FLAG_TEST, "TestEvent",
941                 "Type: Assert\r\n"
942                 "AppFile: %s\r\n"
943                 "AppFunction: %s\r\n"
944                 "AppLine: %d\r\n"
945                 "Expression: %s\r\n",
946                 file, func, line, exp);
947 }
948
949 #endif /* TEST_FRAMEWORK */
950
951 int ast_test_init(void)
952 {
953 #ifdef TEST_FRAMEWORK
954         /* Register cli commands */
955         ast_cli_register_multiple(test_cli, ARRAY_LEN(test_cli));
956 #endif
957
958         return 0;
959 }