1 /* GLib testing utilities
2 * Copyright (C) 2007 Imendio AB
3 * Authors: Tim Janik, Sven Herzberg
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
23 #include "gtestutils.h"
25 #include <sys/types.h>
42 #ifdef HAVE_SYS_SELECT_H
43 #include <sys/select.h>
44 #endif /* HAVE_SYS_SELECT_H */
49 #include "gstrfuncs.h"
53 /* Global variable for storing assertion messages; this is the counterpart to
54 * glibc's (private) __abort_msg variable, and allows developers and crash
55 * analysis systems like Apport and ABRT to fish out assertion messages from
56 * core dumps, instead of having to catch them on screen output. */
57 char *__glib_assert_msg = NULL;
59 /* --- structures --- */
64 void (*fixture_setup) (void*, gconstpointer);
65 void (*fixture_test) (void*, gconstpointer);
66 void (*fixture_teardown) (void*, gconstpointer);
75 typedef struct DestroyEntry DestroyEntry;
79 GDestroyNotify destroy_func;
80 gpointer destroy_data;
83 /* --- prototypes --- */
84 static void test_run_seed (const gchar *rseed);
85 static void test_trap_clear (void);
86 static guint8* g_test_log_dump (GTestLogMsg *msg,
88 static void gtest_default_log_handler (const gchar *log_domain,
89 GLogLevelFlags log_level,
91 gpointer unused_data);
94 /* --- variables --- */
95 static int test_log_fd = -1;
96 static gboolean test_mode_fatal = TRUE;
97 static gboolean g_test_run_once = TRUE;
98 static gboolean test_run_list = FALSE;
99 static gchar *test_run_seedstr = NULL;
100 static GRand *test_run_rand = NULL;
101 static gchar *test_run_name = "";
102 static guint test_run_forks = 0;
103 static guint test_run_count = 0;
104 static guint test_skip_count = 0;
105 static GTimer *test_user_timer = NULL;
106 static double test_user_stamp = 0;
107 static GSList *test_paths = NULL;
108 static GTestSuite *test_suite_root = NULL;
109 static int test_trap_last_status = 0;
110 static int test_trap_last_pid = 0;
111 static char *test_trap_last_stdout = NULL;
112 static char *test_trap_last_stderr = NULL;
113 static char *test_uri_base = NULL;
114 static gboolean test_debug_log = FALSE;
115 static DestroyEntry *test_destroy_queue = NULL;
116 static GTestConfig mutable_test_config_vars = {
117 FALSE, /* test_initialized */
118 TRUE, /* test_quick */
119 FALSE, /* test_perf */
120 FALSE, /* test_verbose */
121 FALSE, /* test_quiet */
123 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
125 /* --- functions --- */
127 g_test_log_type_name (GTestLogType log_type)
131 case G_TEST_LOG_NONE: return "none";
132 case G_TEST_LOG_ERROR: return "error";
133 case G_TEST_LOG_START_BINARY: return "binary";
134 case G_TEST_LOG_LIST_CASE: return "list";
135 case G_TEST_LOG_SKIP_CASE: return "skip";
136 case G_TEST_LOG_START_CASE: return "start";
137 case G_TEST_LOG_STOP_CASE: return "stop";
138 case G_TEST_LOG_MIN_RESULT: return "minperf";
139 case G_TEST_LOG_MAX_RESULT: return "maxperf";
140 case G_TEST_LOG_MESSAGE: return "message";
146 g_test_log_send (guint n_bytes,
147 const guint8 *buffer)
149 if (test_log_fd >= 0)
153 r = write (test_log_fd, buffer, n_bytes);
154 while (r < 0 && errno == EINTR);
158 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
161 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
162 msg = g_test_log_buffer_pop (lbuffer);
163 g_warn_if_fail (msg != NULL);
164 g_warn_if_fail (lbuffer->data->len == 0);
165 g_test_log_buffer_free (lbuffer);
167 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
168 for (ui = 0; ui < msg->n_strings; ui++)
169 g_printerr (":{%s}", msg->strings[ui]);
173 for (ui = 0; ui < msg->n_nums; ui++)
174 g_printerr ("%s%.16Lg", ui ? ";" : "", msg->nums[ui]);
177 g_printerr (":LOG*}\n");
178 g_test_log_msg_free (msg);
183 g_test_log (GTestLogType lbit,
184 const gchar *string1,
185 const gchar *string2,
189 gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
191 gchar *astrings[3] = { NULL, NULL, NULL };
197 case G_TEST_LOG_START_BINARY:
198 if (g_test_verbose())
199 g_print ("GTest: random seed: %s\n", string2);
201 case G_TEST_LOG_STOP_CASE:
202 if (g_test_verbose())
203 g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
204 else if (!g_test_quiet())
205 g_print ("%s\n", fail ? "FAIL" : "OK");
206 if (fail && test_mode_fatal)
209 case G_TEST_LOG_MIN_RESULT:
210 if (g_test_verbose())
211 g_print ("(MINPERF:%s)\n", string1);
213 case G_TEST_LOG_MAX_RESULT:
214 if (g_test_verbose())
215 g_print ("(MAXPERF:%s)\n", string1);
217 case G_TEST_LOG_MESSAGE:
218 if (g_test_verbose())
219 g_print ("(MSG: %s)\n", string1);
225 msg.n_strings = (string1 != NULL) + (string1 && string2);
226 msg.strings = astrings;
227 astrings[0] = (gchar*) string1;
228 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
231 dbuffer = g_test_log_dump (&msg, &dbufferlen);
232 g_test_log_send (dbufferlen, dbuffer);
237 case G_TEST_LOG_START_CASE:
238 if (g_test_verbose())
239 g_print ("GTest: run: %s\n", string1);
240 else if (!g_test_quiet())
241 g_print ("%s: ", string1);
247 /* We intentionally parse the command line without GOptionContext
248 * because otherwise you would never be able to test it.
251 parse_args (gint *argc_p,
254 guint argc = *argc_p;
255 gchar **argv = *argv_p;
257 /* parse known args */
258 for (i = 1; i < argc; i++)
260 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
262 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
263 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
264 g_log_set_always_fatal (fatal_mask);
267 else if (strcmp (argv[i], "--keep-going") == 0 ||
268 strcmp (argv[i], "-k") == 0)
270 test_mode_fatal = FALSE;
273 else if (strcmp (argv[i], "--debug-log") == 0)
275 test_debug_log = TRUE;
278 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
280 gchar *equal = argv[i] + 12;
282 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
283 else if (i + 1 < argc)
286 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
290 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
292 gchar *equal = argv[i] + 16;
294 test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
295 else if (i + 1 < argc)
298 test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
302 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
304 gchar *equal = argv[i] + 2;
306 test_paths = g_slist_prepend (test_paths, equal + 1);
307 else if (i + 1 < argc)
310 test_paths = g_slist_prepend (test_paths, argv[i]);
314 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
316 gchar *equal = argv[i] + 2;
317 const gchar *mode = "";
320 else if (i + 1 < argc)
325 if (strcmp (mode, "perf") == 0)
326 mutable_test_config_vars.test_perf = TRUE;
327 else if (strcmp (mode, "slow") == 0)
328 mutable_test_config_vars.test_quick = FALSE;
329 else if (strcmp (mode, "thorough") == 0)
330 mutable_test_config_vars.test_quick = FALSE;
331 else if (strcmp (mode, "quick") == 0)
333 mutable_test_config_vars.test_quick = TRUE;
334 mutable_test_config_vars.test_perf = FALSE;
337 g_error ("unknown test mode: -m %s", mode);
340 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
342 mutable_test_config_vars.test_quiet = TRUE;
343 mutable_test_config_vars.test_verbose = FALSE;
346 else if (strcmp ("--verbose", argv[i]) == 0)
348 mutable_test_config_vars.test_quiet = FALSE;
349 mutable_test_config_vars.test_verbose = TRUE;
352 else if (strcmp ("-l", argv[i]) == 0)
354 test_run_list = TRUE;
357 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
359 gchar *equal = argv[i] + 6;
361 test_run_seedstr = equal + 1;
362 else if (i + 1 < argc)
365 test_run_seedstr = argv[i];
369 else if (strcmp ("-?", argv[i]) == 0 || strcmp ("--help", argv[i]) == 0)
372 " %s [OPTION...]\n\n"
374 " -?, --help Show help options\n"
376 " -l List test cases available in a test executable\n"
377 " -seed=RANDOMSEED Provide a random seed to reproduce test\n"
378 " runs using random numbers\n"
379 " --verbose Run tests verbosely\n"
380 " -q, --quiet Run tests quietly\n"
381 " -p TESTPATH execute all tests matching TESTPATH\n"
382 " -m {perf|slow|thorough|quick} Execute tests according modes\n"
383 " --debug-log debug test logging output\n"
384 " -k, --keep-going gtester-specific argument\n"
385 " --GTestLogFD=N gtester-specific argument\n"
386 " --GTestSkipCount=N gtester-specific argument\n",
393 for (i = 1; i < argc; i++)
405 * @argc: Address of the @argc parameter of the main() function.
406 * Changed if any arguments were handled.
407 * @argv: Address of the @argv parameter of main().
408 * Any parameters understood by g_test_init() stripped before return.
409 * @Varargs: Reserved for future extension. Currently, you must pass %NULL.
411 * Initialize the GLib testing framework, e.g. by seeding the
412 * test random number generator, the name for g_get_prgname()
413 * and parsing test related command line args.
414 * So far, the following arguments are understood:
417 * <term><option>-l</option></term>
419 * list test cases available in a test executable.
423 * <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
425 * provide a random seed to reproduce test runs using random numbers.
429 * <term><option>--verbose</option></term>
430 * <listitem><para>run tests verbosely.</para></listitem>
433 * <term><option>-q</option>, <option>--quiet</option></term>
434 * <listitem><para>run tests quietly.</para></listitem>
437 * <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
439 * execute all tests matching <replaceable>TESTPATH</replaceable>.
443 * <term><option>-m {perf|slow|thorough|quick}</option></term>
445 * execute tests according to these test modes:
450 * performance tests, may take long and report results.
454 * <term>slow, thorough</term>
456 * slow and thorough tests, may take quite long and
463 * quick tests, should run really quickly and give good coverage.
470 * <term><option>--debug-log</option></term>
471 * <listitem><para>debug test logging output.</para></listitem>
474 * <term><option>-k</option>, <option>--keep-going</option></term>
475 * <listitem><para>gtester-specific argument.</para></listitem>
478 * <term><option>--GTestLogFD <replaceable>N</replaceable></option></term>
479 * <listitem><para>gtester-specific argument.</para></listitem>
482 * <term><option>--GTestSkipCount <replaceable>N</replaceable></option></term>
483 * <listitem><para>gtester-specific argument.</para></listitem>
490 g_test_init (int *argc,
494 static char seedstr[4 + 4 * 8 + 1];
497 /* make warnings and criticals fatal for all test programs */
498 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
499 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
500 g_log_set_always_fatal (fatal_mask);
501 /* check caller args */
502 g_return_if_fail (argc != NULL);
503 g_return_if_fail (argv != NULL);
504 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
505 mutable_test_config_vars.test_initialized = TRUE;
507 va_start (args, argv);
508 vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
510 g_return_if_fail (vararg1 == NULL);
512 /* setup random seed string */
513 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
514 test_run_seedstr = seedstr;
516 /* parse args, sets up mode, changes seed, etc. */
517 parse_args (argc, argv);
518 if (!g_get_prgname())
519 g_set_prgname ((*argv)[0]);
521 /* verify GRand reliability, needed for reliable seeds */
524 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
525 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
526 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
527 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
528 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
532 /* check rand seed */
533 test_run_seed (test_run_seedstr);
535 /* report program start */
536 g_log_set_default_handler (gtest_default_log_handler, NULL);
537 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
541 test_run_seed (const gchar *rseed)
543 guint seed_failed = 0;
545 g_rand_free (test_run_rand);
546 test_run_rand = NULL;
547 while (strchr (" \t\v\r\n\f", *rseed))
549 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
551 const char *s = rseed + 4;
552 if (strlen (s) >= 32) /* require 4 * 8 chars */
554 guint32 seedarray[4];
555 gchar *p, hexbuf[9] = { 0, };
556 memcpy (hexbuf, s + 0, 8);
557 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
558 seed_failed += p != NULL && *p != 0;
559 memcpy (hexbuf, s + 8, 8);
560 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
561 seed_failed += p != NULL && *p != 0;
562 memcpy (hexbuf, s + 16, 8);
563 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
564 seed_failed += p != NULL && *p != 0;
565 memcpy (hexbuf, s + 24, 8);
566 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
567 seed_failed += p != NULL && *p != 0;
570 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
575 g_error ("Unknown or invalid random seed: %s", rseed);
581 * Get a reproducible random integer number.
583 * The random numbers generated by the g_test_rand_*() family of functions
584 * change with every new test program start, unless the --seed option is
585 * given when starting test programs.
587 * For individual test cases however, the random number generator is
588 * reseeded, to avoid dependencies between tests and to make --seed
589 * effective for all test cases.
591 * Returns: a random number from the seeded random number generator.
596 g_test_rand_int (void)
598 return g_rand_int (test_run_rand);
602 * g_test_rand_int_range:
603 * @begin: the minimum value returned by this function
604 * @end: the smallest value not to be returned by this function
606 * Get a reproducible random integer number out of a specified range,
607 * see g_test_rand_int() for details on test case random numbers.
609 * Returns: a number with @begin <= number < @end.
614 g_test_rand_int_range (gint32 begin,
617 return g_rand_int_range (test_run_rand, begin, end);
621 * g_test_rand_double:
623 * Get a reproducible random floating point number,
624 * see g_test_rand_int() for details on test case random numbers.
626 * Returns: a random number from the seeded random number generator.
631 g_test_rand_double (void)
633 return g_rand_double (test_run_rand);
637 * g_test_rand_double_range:
638 * @range_start: the minimum value returned by this function
639 * @range_end: the minimum value not returned by this function
641 * Get a reproducible random floating pointer number out of a specified range,
642 * see g_test_rand_int() for details on test case random numbers.
644 * Returns: a number with @range_start <= number < @range_end.
649 g_test_rand_double_range (double range_start,
652 return g_rand_double_range (test_run_rand, range_start, range_end);
656 * g_test_timer_start:
658 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
659 * to be done. Call this function again to restart the timer.
664 g_test_timer_start (void)
666 if (!test_user_timer)
667 test_user_timer = g_timer_new();
669 g_timer_start (test_user_timer);
673 * g_test_timer_elapsed:
675 * Get the time since the last start of the timer with g_test_timer_start().
677 * Returns: the time since the last start of the timer, as a double
682 g_test_timer_elapsed (void)
684 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
685 return test_user_stamp;
691 * Report the last result of g_test_timer_elapsed().
693 * Returns: the last result of g_test_timer_elapsed(), as a double
698 g_test_timer_last (void)
700 return test_user_stamp;
704 * g_test_minimized_result:
705 * @minimized_quantity: the reported value
706 * @format: the format string of the report message
707 * @Varargs: arguments to pass to the printf() function
709 * Report the result of a performance or measurement test.
710 * The test should generally strive to minimize the reported
711 * quantities (smaller values are better than larger ones),
712 * this and @minimized_quantity can determine sorting
713 * order for test result reports.
718 g_test_minimized_result (double minimized_quantity,
722 long double largs = minimized_quantity;
725 va_start (args, format);
726 buffer = g_strdup_vprintf (format, args);
728 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
733 * g_test_maximized_result:
734 * @maximized_quantity: the reported value
735 * @format: the format string of the report message
736 * @Varargs: arguments to pass to the printf() function
738 * Report the result of a performance or measurement test.
739 * The test should generally strive to maximize the reported
740 * quantities (larger values are better than smaller ones),
741 * this and @maximized_quantity can determine sorting
742 * order for test result reports.
747 g_test_maximized_result (double maximized_quantity,
751 long double largs = maximized_quantity;
754 va_start (args, format);
755 buffer = g_strdup_vprintf (format, args);
757 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
763 * @format: the format string
764 * @...: printf-like arguments to @format
766 * Add a message to the test report.
771 g_test_message (const char *format,
776 va_start (args, format);
777 buffer = g_strdup_vprintf (format, args);
779 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
785 * @uri_pattern: the base pattern for bug URIs
787 * Specify the base URI for bug reports.
789 * The base URI is used to construct bug report messages for
790 * g_test_message() when g_test_bug() is called.
791 * Calling this function outside of a test case sets the
792 * default base URI for all test cases. Calling it from within
793 * a test case changes the base URI for the scope of the test
795 * Bug URIs are constructed by appending a bug specific URI
796 * portion to @uri_pattern, or by replacing the special string
797 * '%s' within @uri_pattern if that is present.
802 g_test_bug_base (const char *uri_pattern)
804 g_free (test_uri_base);
805 test_uri_base = g_strdup (uri_pattern);
810 * @bug_uri_snippet: Bug specific bug tracker URI portion.
812 * This function adds a message to test reports that
813 * associates a bug URI with a test case.
814 * Bug URIs are constructed from a base URI set with g_test_bug_base()
815 * and @bug_uri_snippet.
820 g_test_bug (const char *bug_uri_snippet)
823 g_return_if_fail (test_uri_base != NULL);
824 g_return_if_fail (bug_uri_snippet != NULL);
825 c = strstr (test_uri_base, "%s");
828 char *b = g_strndup (test_uri_base, c - test_uri_base);
829 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
831 g_test_message ("Bug Reference: %s", s);
835 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
841 * Get the toplevel test suite for the test path API.
843 * Returns: the toplevel #GTestSuite
848 g_test_get_root (void)
850 if (!test_suite_root)
852 test_suite_root = g_test_create_suite ("root");
853 g_free (test_suite_root->name);
854 test_suite_root->name = g_strdup ("");
856 return test_suite_root;
862 * Runs all tests under the toplevel suite which can be retrieved
863 * with g_test_get_root(). Similar to g_test_run_suite(), the test
864 * cases to be run are filtered according to
865 * test path arguments (-p <replaceable>testpath</replaceable>) as
866 * parsed by g_test_init().
867 * g_test_run_suite() or g_test_run() may only be called once
870 * Returns: 0 on success
877 return g_test_run_suite (g_test_get_root());
881 * g_test_create_case:
882 * @test_name: the name for the test case
883 * @data_size: the size of the fixture data structure
884 * @test_data: test data argument for the test functions
885 * @data_setup: the function to set up the fixture data
886 * @data_test: the actual test function
887 * @data_teardown: the function to teardown the fixture data
889 * Create a new #GTestCase, named @test_name, this API is fairly
890 * low level, calling g_test_add() or g_test_add_func() is preferable.
891 * When this test is executed, a fixture structure of size @data_size
892 * will be allocated and filled with 0s. Then data_setup() is called
893 * to initialize the fixture. After fixture setup, the actual test
894 * function data_test() is called. Once the test run completed, the
895 * fixture structure is torn down by calling data_teardown() and
896 * after that the memory is released.
898 * Splitting up a test run into fixture setup, test function and
899 * fixture teardown is most usful if the same fixture is used for
900 * multiple tests. In this cases, g_test_create_case() will be
901 * called with the same fixture, but varying @test_name and
902 * @data_test arguments.
904 * Returns: a newly allocated #GTestCase.
909 g_test_create_case (const char *test_name,
911 gconstpointer test_data,
912 GTestFixtureFunc data_setup,
913 GTestFixtureFunc data_test,
914 GTestFixtureFunc data_teardown)
917 g_return_val_if_fail (test_name != NULL, NULL);
918 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
919 g_return_val_if_fail (test_name[0] != 0, NULL);
920 g_return_val_if_fail (data_test != NULL, NULL);
921 tc = g_slice_new0 (GTestCase);
922 tc->name = g_strdup (test_name);
923 tc->test_data = (gpointer) test_data;
924 tc->fixture_size = data_size;
925 tc->fixture_setup = (void*) data_setup;
926 tc->fixture_test = (void*) data_test;
927 tc->fixture_teardown = (void*) data_teardown;
933 * @fixture: the test fixture
934 * @user_data: the data provided when registering the test
936 * The type used for functions that operate on test fixtures. This is
937 * used for the fixture setup and teardown functions as well as for the
938 * testcases themselves.
940 * @user_data is a pointer to the data that was given when registering
943 * @fixture will be a pointer to the area of memory allocated by the
944 * test framework, of the size requested. If the requested size was
945 * zero then @fixture will be equal to @user_data.
948 g_test_add_vtable (const char *testpath,
950 gconstpointer test_data,
951 GTestFixtureFunc data_setup,
952 GTestFixtureFunc fixture_test_func,
953 GTestFixtureFunc data_teardown)
959 g_return_if_fail (testpath != NULL);
960 g_return_if_fail (testpath[0] == '/');
961 g_return_if_fail (fixture_test_func != NULL);
963 suite = g_test_get_root();
964 segments = g_strsplit (testpath, "/", -1);
965 for (ui = 0; segments[ui] != NULL; ui++)
967 const char *seg = segments[ui];
968 gboolean islast = segments[ui + 1] == NULL;
969 if (islast && !seg[0])
970 g_error ("invalid test case path: %s", testpath);
972 continue; /* initial or duplicate slash */
975 GTestSuite *csuite = g_test_create_suite (seg);
976 g_test_suite_add_suite (suite, csuite);
981 GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
982 g_test_suite_add (suite, tc);
985 g_strfreev (segments);
991 * The type used for test case functions.
995 * @testpath: Slash-separated test case path name for the test.
996 * @test_func: The test function to invoke for this test.
998 * Create a new test case, similar to g_test_create_case(). However
999 * the test is assumed to use no fixture, and test suites are automatically
1000 * created on the fly and added to the root fixture, based on the
1001 * slash-separated portions of @testpath.
1006 g_test_add_func (const char *testpath,
1007 GTestFunc test_func)
1009 g_return_if_fail (testpath != NULL);
1010 g_return_if_fail (testpath[0] == '/');
1011 g_return_if_fail (test_func != NULL);
1012 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1017 * @user_data: the data provided when registering the test
1019 * The type used for test case functions that take an extra pointer
1023 * g_test_add_data_func:
1024 * @testpath: Slash-separated test case path name for the test.
1025 * @test_data: Test data argument for the test function.
1026 * @test_func: The test function to invoke for this test.
1028 * Create a new test case, similar to g_test_create_case(). However
1029 * the test is assumed to use no fixture, and test suites are automatically
1030 * created on the fly and added to the root fixture, based on the
1031 * slash-separated portions of @testpath. The @test_data argument
1032 * will be passed as first argument to @test_func.
1037 g_test_add_data_func (const char *testpath,
1038 gconstpointer test_data,
1039 GTestDataFunc test_func)
1041 g_return_if_fail (testpath != NULL);
1042 g_return_if_fail (testpath[0] == '/');
1043 g_return_if_fail (test_func != NULL);
1044 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1048 * g_test_create_suite:
1049 * @suite_name: a name for the suite
1051 * Create a new test suite with the name @suite_name.
1053 * Returns: A newly allocated #GTestSuite instance.
1058 g_test_create_suite (const char *suite_name)
1061 g_return_val_if_fail (suite_name != NULL, NULL);
1062 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1063 g_return_val_if_fail (suite_name[0] != 0, NULL);
1064 ts = g_slice_new0 (GTestSuite);
1065 ts->name = g_strdup (suite_name);
1071 * @suite: a #GTestSuite
1072 * @test_case: a #GTestCase
1074 * Adds @test_case to @suite.
1079 g_test_suite_add (GTestSuite *suite,
1080 GTestCase *test_case)
1082 g_return_if_fail (suite != NULL);
1083 g_return_if_fail (test_case != NULL);
1084 suite->cases = g_slist_prepend (suite->cases, test_case);
1088 * g_test_suite_add_suite:
1089 * @suite: a #GTestSuite
1090 * @nestedsuite: another #GTestSuite
1092 * Adds @nestedsuite to @suite.
1097 g_test_suite_add_suite (GTestSuite *suite,
1098 GTestSuite *nestedsuite)
1100 g_return_if_fail (suite != NULL);
1101 g_return_if_fail (nestedsuite != NULL);
1102 suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1106 * g_test_queue_free:
1107 * @gfree_pointer: the pointer to be stored.
1109 * Enqueue a pointer to be released with g_free() during the next
1110 * teardown phase. This is equivalent to calling g_test_queue_destroy()
1111 * with a destroy callback of g_free().
1116 g_test_queue_free (gpointer gfree_pointer)
1119 g_test_queue_destroy (g_free, gfree_pointer);
1123 * g_test_queue_destroy:
1124 * @destroy_func: Destroy callback for teardown phase.
1125 * @destroy_data: Destroy callback data.
1127 * This function enqueus a callback @destroy_func() to be executed
1128 * during the next test case teardown phase. This is most useful
1129 * to auto destruct allocted test resources at the end of a test run.
1130 * Resources are released in reverse queue order, that means enqueueing
1131 * callback A before callback B will cause B() to be called before
1132 * A() during teardown.
1137 g_test_queue_destroy (GDestroyNotify destroy_func,
1138 gpointer destroy_data)
1140 DestroyEntry *dentry;
1141 g_return_if_fail (destroy_func != NULL);
1142 dentry = g_slice_new0 (DestroyEntry);
1143 dentry->destroy_func = destroy_func;
1144 dentry->destroy_data = destroy_data;
1145 dentry->next = test_destroy_queue;
1146 test_destroy_queue = dentry;
1150 test_case_run (GTestCase *tc)
1152 gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1153 test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1154 if (++test_run_count <= test_skip_count)
1155 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1156 else if (test_run_list)
1158 g_print ("%s\n", test_run_name);
1159 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1163 GTimer *test_run_timer = g_timer_new();
1164 long double largs[3];
1166 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1168 g_test_log_set_fatal_handler (NULL, NULL);
1169 g_timer_start (test_run_timer);
1170 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1171 test_run_seed (test_run_seedstr);
1172 if (tc->fixture_setup)
1173 tc->fixture_setup (fixture, tc->test_data);
1174 tc->fixture_test (fixture, tc->test_data);
1176 while (test_destroy_queue)
1178 DestroyEntry *dentry = test_destroy_queue;
1179 test_destroy_queue = dentry->next;
1180 dentry->destroy_func (dentry->destroy_data);
1181 g_slice_free (DestroyEntry, dentry);
1183 if (tc->fixture_teardown)
1184 tc->fixture_teardown (fixture, tc->test_data);
1185 if (tc->fixture_size)
1187 g_timer_stop (test_run_timer);
1188 largs[0] = 0; /* OK */
1189 largs[1] = test_run_forks;
1190 largs[2] = g_timer_elapsed (test_run_timer, NULL);
1191 g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1192 g_timer_destroy (test_run_timer);
1194 g_free (test_run_name);
1195 test_run_name = old_name;
1196 g_free (test_uri_base);
1197 test_uri_base = old_base;
1202 g_test_run_suite_internal (GTestSuite *suite,
1206 gchar *rest, *old_name = test_run_name;
1207 GSList *slist, *reversed;
1208 g_return_val_if_fail (suite != NULL, -1);
1209 while (path[0] == '/')
1212 rest = strchr (path, '/');
1213 l = rest ? MIN (l, rest - path) : l;
1214 test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1215 reversed = g_slist_reverse (g_slist_copy (suite->cases));
1216 for (slist = reversed; slist; slist = slist->next)
1218 GTestCase *tc = slist->data;
1219 guint n = l ? strlen (tc->name) : 0;
1220 if (l == n && strncmp (path, tc->name, n) == 0)
1222 if (!test_case_run (tc))
1226 g_slist_free (reversed);
1227 reversed = g_slist_reverse (g_slist_copy (suite->suites));
1228 for (slist = reversed; slist; slist = slist->next)
1230 GTestSuite *ts = slist->data;
1231 guint n = l ? strlen (ts->name) : 0;
1232 if (l == n && strncmp (path, ts->name, n) == 0)
1233 n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
1235 g_slist_free (reversed);
1236 g_free (test_run_name);
1237 test_run_name = old_name;
1243 * @suite: a #GTestSuite
1245 * Execute the tests within @suite and all nested #GTestSuites.
1246 * The test suites to be executed are filtered according to
1247 * test path arguments (-p <replaceable>testpath</replaceable>)
1248 * as parsed by g_test_init().
1249 * g_test_run_suite() or g_test_run() may only be called once
1252 * Returns: 0 on success
1257 g_test_run_suite (GTestSuite *suite)
1260 g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1261 g_return_val_if_fail (g_test_run_once == TRUE, -1);
1262 g_test_run_once = FALSE;
1264 test_paths = g_slist_prepend (test_paths, "");
1267 const char *rest, *path = test_paths->data;
1268 guint l, n = strlen (suite->name);
1269 test_paths = g_slist_delete_link (test_paths, test_paths);
1270 while (path[0] == '/')
1272 if (!n) /* root suite, run unconditionally */
1274 n_bad += g_test_run_suite_internal (suite, path);
1277 /* regular suite, match path */
1278 rest = strchr (path, '/');
1280 l = rest ? MIN (l, rest - path) : l;
1281 if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1282 n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
1288 gtest_default_log_handler (const gchar *log_domain,
1289 GLogLevelFlags log_level,
1290 const gchar *message,
1291 gpointer unused_data)
1293 const gchar *strv[16];
1294 gboolean fatal = FALSE;
1299 strv[i++] = log_domain;
1302 if (log_level & G_LOG_FLAG_FATAL)
1304 strv[i++] = "FATAL-";
1307 if (log_level & G_LOG_FLAG_RECURSION)
1308 strv[i++] = "RECURSIVE-";
1309 if (log_level & G_LOG_LEVEL_ERROR)
1310 strv[i++] = "ERROR";
1311 if (log_level & G_LOG_LEVEL_CRITICAL)
1312 strv[i++] = "CRITICAL";
1313 if (log_level & G_LOG_LEVEL_WARNING)
1314 strv[i++] = "WARNING";
1315 if (log_level & G_LOG_LEVEL_MESSAGE)
1316 strv[i++] = "MESSAGE";
1317 if (log_level & G_LOG_LEVEL_INFO)
1319 if (log_level & G_LOG_LEVEL_DEBUG)
1320 strv[i++] = "DEBUG";
1322 strv[i++] = message;
1324 msg = g_strjoinv ("", (gchar**) strv);
1325 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
1326 g_log_default_handler (log_domain, log_level, message, unused_data);
1331 g_assertion_message (const char *domain,
1335 const char *message)
1340 message = "code should not be reached";
1341 g_snprintf (lstr, 32, "%d", line);
1342 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1343 "ERROR:", file, ":", lstr, ":",
1344 func, func[0] ? ":" : "",
1345 " ", message, NULL);
1346 g_printerr ("**\n%s\n", s);
1348 /* store assertion message in global variable, so that it can be found in a
1350 if (__glib_assert_msg != NULL)
1351 /* free the old one */
1352 free (__glib_assert_msg);
1353 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
1354 strcpy (__glib_assert_msg, s);
1356 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
1362 g_assertion_message_expr (const char *domain,
1368 char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1369 g_assertion_message (domain, file, line, func, s);
1374 g_assertion_message_cmpnum (const char *domain,
1387 case 'i': s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
1388 case 'x': s = g_strdup_printf ("assertion failed (%s): (0x%08" G_GINT64_MODIFIER "x %s 0x%08" G_GINT64_MODIFIER "x)", expr, (guint64) arg1, cmp, (guint64) arg2); break;
1389 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
1390 /* ideally use: floats=%.7g double=%.17g */
1392 g_assertion_message (domain, file, line, func, s);
1397 g_assertion_message_cmpstr (const char *domain,
1406 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1407 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1408 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1411 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1414 g_assertion_message (domain, file, line, func, s);
1419 g_assertion_message_error (const char *domain,
1424 const GError *error,
1425 GQuark error_domain,
1430 /* This is used by both g_assert_error() and g_assert_no_error(), so there
1431 * are three cases: expected an error but got the wrong error, expected
1432 * an error but got no error, and expected no error but got an error.
1435 gstring = g_string_new ("assertion failed ");
1437 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
1438 g_quark_to_string (error_domain), error_code);
1440 g_string_append_printf (gstring, "(%s == NULL): ", expr);
1443 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
1444 g_quark_to_string (error->domain), error->code);
1446 g_string_append_printf (gstring, "%s is NULL", expr);
1448 g_assertion_message (domain, file, line, func, gstring->str);
1449 g_string_free (gstring, TRUE);
1454 * @str1: a C string or %NULL
1455 * @str2: another C string or %NULL
1457 * Compares @str1 and @str2 like strcmp(). Handles %NULL
1458 * gracefully by sorting it before non-%NULL strings.
1459 * Comparing two %NULL pointers returns 0.
1461 * Returns: -1, 0 or 1, if @str1 is <, == or > than @str2.
1466 g_strcmp0 (const char *str1,
1470 return -(str1 != str2);
1472 return str1 != str2;
1473 return strcmp (str1, str2);
1477 static int /* 0 on success */
1478 kill_child (int pid,
1483 if (patience >= 3) /* try graceful reap */
1485 if (waitpid (pid, status, WNOHANG) > 0)
1488 if (patience >= 2) /* try SIGHUP */
1491 if (waitpid (pid, status, WNOHANG) > 0)
1493 g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1494 if (waitpid (pid, status, WNOHANG) > 0)
1496 g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
1497 if (waitpid (pid, status, WNOHANG) > 0)
1499 g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
1500 if (waitpid (pid, status, WNOHANG) > 0)
1503 if (patience >= 1) /* try SIGTERM */
1505 kill (pid, SIGTERM);
1506 if (waitpid (pid, status, WNOHANG) > 0)
1508 g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
1509 if (waitpid (pid, status, WNOHANG) > 0)
1511 g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
1512 if (waitpid (pid, status, WNOHANG) > 0)
1516 kill (pid, SIGKILL);
1518 wr = waitpid (pid, status, 0);
1519 while (wr < 0 && errno == EINTR);
1525 g_string_must_read (GString *gstring,
1528 #define STRING_BUFFER_SIZE 4096
1529 char buf[STRING_BUFFER_SIZE];
1532 bytes = read (fd, buf, sizeof (buf));
1534 return 0; /* EOF, calling this function assumes data is available */
1537 g_string_append_len (gstring, buf, bytes);
1540 else if (bytes < 0 && errno == EINTR)
1542 else /* bytes < 0 */
1544 g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1545 return 1; /* ignore error after warning */
1550 g_string_write_out (GString *gstring,
1554 if (*stringpos < gstring->len)
1558 r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
1559 while (r < 0 && errno == EINTR);
1560 *stringpos += MAX (r, 0);
1565 test_trap_clear (void)
1567 test_trap_last_status = 0;
1568 test_trap_last_pid = 0;
1569 g_free (test_trap_last_stdout);
1570 test_trap_last_stdout = NULL;
1571 g_free (test_trap_last_stderr);
1572 test_trap_last_stderr = NULL;
1583 ret = dup2 (fd1, fd2);
1584 while (ret < 0 && errno == EINTR);
1589 test_time_stamp (void)
1593 g_get_current_time (&tv);
1595 stamp = stamp * 1000000 + tv.tv_usec;
1603 * @usec_timeout: Timeout for the forked test in micro seconds.
1604 * @test_trap_flags: Flags to modify forking behaviour.
1606 * Fork the current test program to execute a test case that might
1607 * not return or that might abort. The forked test case is aborted
1608 * and considered failing if its run time exceeds @usec_timeout.
1610 * The forking behavior can be configured with the #GTestTrapFlags flags.
1612 * In the following example, the test code forks, the forked child
1613 * process produces some sample output and exits successfully.
1614 * The forking parent process then asserts successful child program
1615 * termination and validates child program outputs.
1619 * test_fork_patterns (void)
1621 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
1623 * g_print ("some stdout text: somagic17\n");
1624 * g_printerr ("some stderr text: semagic43\n");
1625 * exit (0); /* successful test run */
1627 * g_test_trap_assert_passed();
1628 * g_test_trap_assert_stdout ("*somagic17*");
1629 * g_test_trap_assert_stderr ("*semagic43*");
1633 * This function is implemented only on Unix platforms.
1635 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
1640 g_test_trap_fork (guint64 usec_timeout,
1641 GTestTrapFlags test_trap_flags)
1644 gboolean pass_on_forked_log = FALSE;
1645 int stdout_pipe[2] = { -1, -1 };
1646 int stderr_pipe[2] = { -1, -1 };
1647 int stdtst_pipe[2] = { -1, -1 };
1649 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
1650 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
1651 signal (SIGCHLD, SIG_DFL);
1652 test_trap_last_pid = fork ();
1653 if (test_trap_last_pid < 0)
1654 g_error ("failed to fork test program: %s", g_strerror (errno));
1655 if (test_trap_last_pid == 0) /* child */
1658 close (stdout_pipe[0]);
1659 close (stderr_pipe[0]);
1660 close (stdtst_pipe[0]);
1661 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
1662 fd0 = open ("/dev/null", O_RDONLY);
1663 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
1664 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
1667 if (stdout_pipe[1] >= 3)
1668 close (stdout_pipe[1]);
1669 if (stderr_pipe[1] >= 3)
1670 close (stderr_pipe[1]);
1671 test_log_fd = stdtst_pipe[1];
1676 GString *sout = g_string_new (NULL);
1677 GString *serr = g_string_new (NULL);
1679 int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
1681 close (stdout_pipe[1]);
1682 close (stderr_pipe[1]);
1683 close (stdtst_pipe[1]);
1684 sstamp = test_time_stamp();
1685 /* read data until we get EOF on all pipes */
1686 while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
1692 if (stdout_pipe[0] >= 0)
1693 FD_SET (stdout_pipe[0], &fds);
1694 if (stderr_pipe[0] >= 0)
1695 FD_SET (stderr_pipe[0], &fds);
1696 if (stdtst_pipe[0] >= 0)
1697 FD_SET (stdtst_pipe[0], &fds);
1699 tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
1700 ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
1701 if (ret < 0 && errno != EINTR)
1703 g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1706 if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
1707 g_string_must_read (sout, stdout_pipe[0]) == 0)
1709 close (stdout_pipe[0]);
1710 stdout_pipe[0] = -1;
1712 if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
1713 g_string_must_read (serr, stderr_pipe[0]) == 0)
1715 close (stderr_pipe[0]);
1716 stderr_pipe[0] = -1;
1718 if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
1720 guint8 buffer[4096];
1721 gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
1722 if (r > 0 && test_log_fd > 0)
1724 l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
1725 while (l < 0 && errno == EINTR);
1726 if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
1728 close (stdtst_pipe[0]);
1729 stdtst_pipe[0] = -1;
1732 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
1733 g_string_write_out (sout, 1, &soutpos);
1734 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
1735 g_string_write_out (serr, 2, &serrpos);
1738 guint64 nstamp = test_time_stamp();
1740 sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
1741 if (usec_timeout < nstamp - sstamp)
1743 /* timeout reached, need to abort the child now */
1744 kill_child (test_trap_last_pid, &status, 3);
1745 test_trap_last_status = 1024; /* timeout */
1746 if (0 && WIFSIGNALED (status))
1747 g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
1753 close (stdout_pipe[0]);
1754 close (stderr_pipe[0]);
1755 close (stdtst_pipe[0]);
1760 wr = waitpid (test_trap_last_pid, &status, 0);
1761 while (wr < 0 && errno == EINTR);
1762 if (WIFEXITED (status)) /* normal exit */
1763 test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
1764 else if (WIFSIGNALED (status))
1765 test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
1766 else /* WCOREDUMP (status) */
1767 test_trap_last_status = 512; /* coredump */
1769 test_trap_last_stdout = g_string_free (sout, FALSE);
1770 test_trap_last_stderr = g_string_free (serr, FALSE);
1774 g_message ("Not implemented: g_test_trap_fork");
1781 * g_test_trap_has_passed:
1783 * Check the result of the last g_test_trap_fork() call.
1785 * Returns: %TRUE if the last forked child terminated successfully.
1790 g_test_trap_has_passed (void)
1792 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
1796 * g_test_trap_reached_timeout:
1798 * Check the result of the last g_test_trap_fork() call.
1800 * Returns: %TRUE if the last forked child got killed due to a fork timeout.
1805 g_test_trap_reached_timeout (void)
1807 return 0 != (test_trap_last_status & 1024); /* timeout flag */
1811 g_test_trap_assertions (const char *domain,
1815 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
1816 const char *pattern)
1819 gboolean must_pass = assertion_flags == 0;
1820 gboolean must_fail = assertion_flags == 1;
1821 gboolean match_result = 0 == (assertion_flags & 1);
1822 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
1823 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
1824 const char *match_error = match_result ? "failed to match" : "contains invalid match";
1825 if (test_trap_last_pid == 0)
1826 g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
1827 if (must_pass && !g_test_trap_has_passed())
1829 char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
1830 g_assertion_message (domain, file, line, func, msg);
1833 if (must_fail && g_test_trap_has_passed())
1835 char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
1836 g_assertion_message (domain, file, line, func, msg);
1839 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
1841 char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
1842 g_assertion_message (domain, file, line, func, msg);
1845 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
1847 char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
1848 g_assertion_message (domain, file, line, func, msg);
1855 gstring_overwrite_int (GString *gstring,
1859 vuint = g_htonl (vuint);
1860 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
1864 gstring_append_int (GString *gstring,
1867 vuint = g_htonl (vuint);
1868 g_string_append_len (gstring, (const gchar*) &vuint, 4);
1872 gstring_append_double (GString *gstring,
1875 union { double vdouble; guint64 vuint64; } u;
1876 u.vdouble = vdouble;
1877 u.vuint64 = GUINT64_TO_BE (u.vuint64);
1878 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
1882 g_test_log_dump (GTestLogMsg *msg,
1885 GString *gstring = g_string_sized_new (1024);
1887 gstring_append_int (gstring, 0); /* message length */
1888 gstring_append_int (gstring, msg->log_type);
1889 gstring_append_int (gstring, msg->n_strings);
1890 gstring_append_int (gstring, msg->n_nums);
1891 gstring_append_int (gstring, 0); /* reserved */
1892 for (ui = 0; ui < msg->n_strings; ui++)
1894 guint l = strlen (msg->strings[ui]);
1895 gstring_append_int (gstring, l);
1896 g_string_append_len (gstring, msg->strings[ui], l);
1898 for (ui = 0; ui < msg->n_nums; ui++)
1899 gstring_append_double (gstring, msg->nums[ui]);
1900 *len = gstring->len;
1901 gstring_overwrite_int (gstring, 0, *len); /* message length */
1902 return (guint8*) g_string_free (gstring, FALSE);
1905 static inline long double
1906 net_double (const gchar **ipointer)
1908 union { guint64 vuint64; double vdouble; } u;
1909 guint64 aligned_int64;
1910 memcpy (&aligned_int64, *ipointer, 8);
1912 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
1916 static inline guint32
1917 net_int (const gchar **ipointer)
1919 guint32 aligned_int;
1920 memcpy (&aligned_int, *ipointer, 4);
1922 return g_ntohl (aligned_int);
1926 g_test_log_extract (GTestLogBuffer *tbuffer)
1928 const gchar *p = tbuffer->data->str;
1931 if (tbuffer->data->len < 4 * 5)
1933 mlength = net_int (&p);
1934 if (tbuffer->data->len < mlength)
1936 msg.log_type = net_int (&p);
1937 msg.n_strings = net_int (&p);
1938 msg.n_nums = net_int (&p);
1939 if (net_int (&p) == 0)
1942 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
1943 msg.nums = g_new0 (long double, msg.n_nums);
1944 for (ui = 0; ui < msg.n_strings; ui++)
1946 guint sl = net_int (&p);
1947 msg.strings[ui] = g_strndup (p, sl);
1950 for (ui = 0; ui < msg.n_nums; ui++)
1951 msg.nums[ui] = net_double (&p);
1952 if (p <= tbuffer->data->str + mlength)
1954 g_string_erase (tbuffer->data, 0, mlength);
1955 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
1960 g_strfreev (msg.strings);
1961 g_error ("corrupt log stream from test program");
1966 * g_test_log_buffer_new:
1968 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1971 g_test_log_buffer_new (void)
1973 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
1974 tb->data = g_string_sized_new (1024);
1979 * g_test_log_buffer_free
1981 * Internal function for gtester to free test log messages, no ABI guarantees provided.
1984 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
1986 g_return_if_fail (tbuffer != NULL);
1987 while (tbuffer->msgs)
1988 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
1989 g_string_free (tbuffer->data, TRUE);
1994 * g_test_log_buffer_push
1996 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1999 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
2001 const guint8 *bytes)
2003 g_return_if_fail (tbuffer != NULL);
2006 gboolean more_messages;
2007 g_return_if_fail (bytes != NULL);
2008 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
2010 more_messages = g_test_log_extract (tbuffer);
2011 while (more_messages);
2016 * g_test_log_buffer_pop:
2018 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
2021 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
2023 GTestLogMsg *msg = NULL;
2024 g_return_val_if_fail (tbuffer != NULL, NULL);
2027 GSList *slist = g_slist_last (tbuffer->msgs);
2029 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
2035 * g_test_log_msg_free:
2037 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2040 g_test_log_msg_free (GTestLogMsg *tmsg)
2042 g_return_if_fail (tmsg != NULL);
2043 g_strfreev (tmsg->strings);
2044 g_free (tmsg->nums);
2048 /* --- macros docs START --- */
2051 * @testpath: The test path for a new test case.
2052 * @Fixture: The type of a fixture data structure.
2053 * @tdata: Data argument for the test functions.
2054 * @fsetup: The function to set up the fixture data.
2055 * @ftest: The actual test function.
2056 * @fteardown: The function to tear down the fixture data.
2058 * Hook up a new test case at @testpath, similar to g_test_add_func().
2059 * A fixture data structure with setup and teardown function may be provided
2060 * though, similar to g_test_create_case().
2061 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2062 * fteardown() callbacks can expect a @Fixture pointer as first argument in
2063 * a type safe manner.
2067 /* --- macros docs END --- */