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"
54 /* Global variable for storing assertion messages; this is the counterpart to
55 * glibc's (private) __abort_msg variable, and allows developers and crash
56 * analysis systems like Apport and ABRT to fish out assertion messages from
57 * core dumps, instead of having to catch them on screen output. */
58 char *__glib_assert_msg = NULL;
60 /* --- structures --- */
65 void (*fixture_setup) (void*, gconstpointer);
66 void (*fixture_test) (void*, gconstpointer);
67 void (*fixture_teardown) (void*, gconstpointer);
76 typedef struct DestroyEntry DestroyEntry;
80 GDestroyNotify destroy_func;
81 gpointer destroy_data;
84 /* --- prototypes --- */
85 static void test_run_seed (const gchar *rseed);
86 static void test_trap_clear (void);
87 static guint8* g_test_log_dump (GTestLogMsg *msg,
89 static void gtest_default_log_handler (const gchar *log_domain,
90 GLogLevelFlags log_level,
92 gpointer unused_data);
95 /* --- variables --- */
96 static int test_log_fd = -1;
97 static gboolean test_mode_fatal = TRUE;
98 static gboolean g_test_run_once = TRUE;
99 static gboolean test_run_list = FALSE;
100 static gchar *test_run_seedstr = NULL;
101 static GRand *test_run_rand = NULL;
102 static gchar *test_run_name = "";
103 static guint test_run_forks = 0;
104 static guint test_run_count = 0;
105 static guint test_run_success = FALSE;
106 static guint test_skip_count = 0;
107 static GTimer *test_user_timer = NULL;
108 static double test_user_stamp = 0;
109 static GSList *test_paths = NULL;
110 static GTestSuite *test_suite_root = NULL;
111 static int test_trap_last_status = 0;
112 static int test_trap_last_pid = 0;
113 static char *test_trap_last_stdout = NULL;
114 static char *test_trap_last_stderr = NULL;
115 static char *test_uri_base = NULL;
116 static gboolean test_debug_log = FALSE;
117 static DestroyEntry *test_destroy_queue = NULL;
118 static GTestConfig mutable_test_config_vars = {
119 FALSE, /* test_initialized */
120 TRUE, /* test_quick */
121 FALSE, /* test_perf */
122 FALSE, /* test_verbose */
123 FALSE, /* test_quiet */
125 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
127 /* --- functions --- */
129 g_test_log_type_name (GTestLogType log_type)
133 case G_TEST_LOG_NONE: return "none";
134 case G_TEST_LOG_ERROR: return "error";
135 case G_TEST_LOG_START_BINARY: return "binary";
136 case G_TEST_LOG_LIST_CASE: return "list";
137 case G_TEST_LOG_SKIP_CASE: return "skip";
138 case G_TEST_LOG_START_CASE: return "start";
139 case G_TEST_LOG_STOP_CASE: return "stop";
140 case G_TEST_LOG_MIN_RESULT: return "minperf";
141 case G_TEST_LOG_MAX_RESULT: return "maxperf";
142 case G_TEST_LOG_MESSAGE: return "message";
148 g_test_log_send (guint n_bytes,
149 const guint8 *buffer)
151 if (test_log_fd >= 0)
155 r = write (test_log_fd, buffer, n_bytes);
156 while (r < 0 && errno == EINTR);
160 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
163 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
164 msg = g_test_log_buffer_pop (lbuffer);
165 g_warn_if_fail (msg != NULL);
166 g_warn_if_fail (lbuffer->data->len == 0);
167 g_test_log_buffer_free (lbuffer);
169 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
170 for (ui = 0; ui < msg->n_strings; ui++)
171 g_printerr (":{%s}", msg->strings[ui]);
175 for (ui = 0; ui < msg->n_nums; ui++)
176 g_printerr ("%s%.16Lg", ui ? ";" : "", msg->nums[ui]);
179 g_printerr (":LOG*}\n");
180 g_test_log_msg_free (msg);
185 g_test_log (GTestLogType lbit,
186 const gchar *string1,
187 const gchar *string2,
191 gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
193 gchar *astrings[3] = { NULL, NULL, NULL };
199 case G_TEST_LOG_START_BINARY:
200 if (g_test_verbose())
201 g_print ("GTest: random seed: %s\n", string2);
203 case G_TEST_LOG_STOP_CASE:
204 if (g_test_verbose())
205 g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
206 else if (!g_test_quiet())
207 g_print ("%s\n", fail ? "FAIL" : "OK");
208 if (fail && test_mode_fatal)
211 case G_TEST_LOG_MIN_RESULT:
212 if (g_test_verbose())
213 g_print ("(MINPERF:%s)\n", string1);
215 case G_TEST_LOG_MAX_RESULT:
216 if (g_test_verbose())
217 g_print ("(MAXPERF:%s)\n", string1);
219 case G_TEST_LOG_MESSAGE:
220 if (g_test_verbose())
221 g_print ("(MSG: %s)\n", string1);
227 msg.n_strings = (string1 != NULL) + (string1 && string2);
228 msg.strings = astrings;
229 astrings[0] = (gchar*) string1;
230 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
233 dbuffer = g_test_log_dump (&msg, &dbufferlen);
234 g_test_log_send (dbufferlen, dbuffer);
239 case G_TEST_LOG_START_CASE:
240 if (g_test_verbose())
241 g_print ("GTest: run: %s\n", string1);
242 else if (!g_test_quiet())
243 g_print ("%s: ", string1);
249 /* We intentionally parse the command line without GOptionContext
250 * because otherwise you would never be able to test it.
253 parse_args (gint *argc_p,
256 guint argc = *argc_p;
257 gchar **argv = *argv_p;
259 /* parse known args */
260 for (i = 1; i < argc; i++)
262 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
264 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
265 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
266 g_log_set_always_fatal (fatal_mask);
269 else if (strcmp (argv[i], "--keep-going") == 0 ||
270 strcmp (argv[i], "-k") == 0)
272 test_mode_fatal = FALSE;
275 else if (strcmp (argv[i], "--debug-log") == 0)
277 test_debug_log = TRUE;
280 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
282 gchar *equal = argv[i] + 12;
284 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
285 else if (i + 1 < argc)
288 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
292 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
294 gchar *equal = argv[i] + 16;
296 test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
297 else if (i + 1 < argc)
300 test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
304 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
306 gchar *equal = argv[i] + 2;
308 test_paths = g_slist_prepend (test_paths, equal + 1);
309 else if (i + 1 < argc)
312 test_paths = g_slist_prepend (test_paths, argv[i]);
316 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
318 gchar *equal = argv[i] + 2;
319 const gchar *mode = "";
322 else if (i + 1 < argc)
327 if (strcmp (mode, "perf") == 0)
328 mutable_test_config_vars.test_perf = TRUE;
329 else if (strcmp (mode, "slow") == 0)
330 mutable_test_config_vars.test_quick = FALSE;
331 else if (strcmp (mode, "thorough") == 0)
332 mutable_test_config_vars.test_quick = FALSE;
333 else if (strcmp (mode, "quick") == 0)
335 mutable_test_config_vars.test_quick = TRUE;
336 mutable_test_config_vars.test_perf = FALSE;
339 g_error ("unknown test mode: -m %s", mode);
342 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
344 mutable_test_config_vars.test_quiet = TRUE;
345 mutable_test_config_vars.test_verbose = FALSE;
348 else if (strcmp ("--verbose", argv[i]) == 0)
350 mutable_test_config_vars.test_quiet = FALSE;
351 mutable_test_config_vars.test_verbose = TRUE;
354 else if (strcmp ("-l", argv[i]) == 0)
356 test_run_list = TRUE;
359 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
361 gchar *equal = argv[i] + 6;
363 test_run_seedstr = equal + 1;
364 else if (i + 1 < argc)
367 test_run_seedstr = argv[i];
371 else if (strcmp ("-?", argv[i]) == 0 || strcmp ("--help", argv[i]) == 0)
374 " %s [OPTION...]\n\n"
376 " -?, --help Show help options\n"
378 " -l List test cases available in a test executable\n"
379 " -seed=RANDOMSEED Provide a random seed to reproduce test\n"
380 " runs using random numbers\n"
381 " --verbose Run tests verbosely\n"
382 " -q, --quiet Run tests quietly\n"
383 " -p TESTPATH execute all tests matching TESTPATH\n"
384 " -m {perf|slow|thorough|quick} Execute tests according modes\n"
385 " --debug-log debug test logging output\n"
386 " -k, --keep-going gtester-specific argument\n"
387 " --GTestLogFD=N gtester-specific argument\n"
388 " --GTestSkipCount=N gtester-specific argument\n",
395 for (i = 1; i < argc; i++)
407 * @argc: Address of the @argc parameter of the main() function.
408 * Changed if any arguments were handled.
409 * @argv: Address of the @argv parameter of main().
410 * Any parameters understood by g_test_init() stripped before return.
411 * @...: Reserved for future extension. Currently, you must pass %NULL.
413 * Initialize the GLib testing framework, e.g. by seeding the
414 * test random number generator, the name for g_get_prgname()
415 * and parsing test related command line args.
416 * So far, the following arguments are understood:
419 * <term><option>-l</option></term>
421 * list test cases available in a test executable.
425 * <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
427 * provide a random seed to reproduce test runs using random numbers.
431 * <term><option>--verbose</option></term>
432 * <listitem><para>run tests verbosely.</para></listitem>
435 * <term><option>-q</option>, <option>--quiet</option></term>
436 * <listitem><para>run tests quietly.</para></listitem>
439 * <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
441 * execute all tests matching <replaceable>TESTPATH</replaceable>.
445 * <term><option>-m {perf|slow|thorough|quick}</option></term>
447 * execute tests according to these test modes:
452 * performance tests, may take long and report results.
456 * <term>slow, thorough</term>
458 * slow and thorough tests, may take quite long and
465 * quick tests, should run really quickly and give good coverage.
472 * <term><option>--debug-log</option></term>
473 * <listitem><para>debug test logging output.</para></listitem>
476 * <term><option>-k</option>, <option>--keep-going</option></term>
477 * <listitem><para>gtester-specific argument.</para></listitem>
480 * <term><option>--GTestLogFD <replaceable>N</replaceable></option></term>
481 * <listitem><para>gtester-specific argument.</para></listitem>
484 * <term><option>--GTestSkipCount <replaceable>N</replaceable></option></term>
485 * <listitem><para>gtester-specific argument.</para></listitem>
492 g_test_init (int *argc,
496 static char seedstr[4 + 4 * 8 + 1];
499 /* make warnings and criticals fatal for all test programs */
500 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
501 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
502 g_log_set_always_fatal (fatal_mask);
503 /* check caller args */
504 g_return_if_fail (argc != NULL);
505 g_return_if_fail (argv != NULL);
506 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
507 mutable_test_config_vars.test_initialized = TRUE;
509 va_start (args, argv);
510 vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
512 g_return_if_fail (vararg1 == NULL);
514 /* setup random seed string */
515 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
516 test_run_seedstr = seedstr;
518 /* parse args, sets up mode, changes seed, etc. */
519 parse_args (argc, argv);
520 if (!g_get_prgname())
521 g_set_prgname ((*argv)[0]);
523 /* verify GRand reliability, needed for reliable seeds */
526 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
527 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
528 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
529 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
530 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
534 /* check rand seed */
535 test_run_seed (test_run_seedstr);
537 /* report program start */
538 g_log_set_default_handler (gtest_default_log_handler, NULL);
539 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
543 test_run_seed (const gchar *rseed)
545 guint seed_failed = 0;
547 g_rand_free (test_run_rand);
548 test_run_rand = NULL;
549 while (strchr (" \t\v\r\n\f", *rseed))
551 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
553 const char *s = rseed + 4;
554 if (strlen (s) >= 32) /* require 4 * 8 chars */
556 guint32 seedarray[4];
557 gchar *p, hexbuf[9] = { 0, };
558 memcpy (hexbuf, s + 0, 8);
559 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
560 seed_failed += p != NULL && *p != 0;
561 memcpy (hexbuf, s + 8, 8);
562 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
563 seed_failed += p != NULL && *p != 0;
564 memcpy (hexbuf, s + 16, 8);
565 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
566 seed_failed += p != NULL && *p != 0;
567 memcpy (hexbuf, s + 24, 8);
568 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
569 seed_failed += p != NULL && *p != 0;
572 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
577 g_error ("Unknown or invalid random seed: %s", rseed);
583 * Get a reproducible random integer number.
585 * The random numbers generated by the g_test_rand_*() family of functions
586 * change with every new test program start, unless the --seed option is
587 * given when starting test programs.
589 * For individual test cases however, the random number generator is
590 * reseeded, to avoid dependencies between tests and to make --seed
591 * effective for all test cases.
593 * Returns: a random number from the seeded random number generator.
598 g_test_rand_int (void)
600 return g_rand_int (test_run_rand);
604 * g_test_rand_int_range:
605 * @begin: the minimum value returned by this function
606 * @end: the smallest value not to be returned by this function
608 * Get a reproducible random integer number out of a specified range,
609 * see g_test_rand_int() for details on test case random numbers.
611 * Returns: a number with @begin <= number < @end.
616 g_test_rand_int_range (gint32 begin,
619 return g_rand_int_range (test_run_rand, begin, end);
623 * g_test_rand_double:
625 * Get a reproducible random floating point number,
626 * see g_test_rand_int() for details on test case random numbers.
628 * Returns: a random number from the seeded random number generator.
633 g_test_rand_double (void)
635 return g_rand_double (test_run_rand);
639 * g_test_rand_double_range:
640 * @range_start: the minimum value returned by this function
641 * @range_end: the minimum value not returned by this function
643 * Get a reproducible random floating pointer number out of a specified range,
644 * see g_test_rand_int() for details on test case random numbers.
646 * Returns: a number with @range_start <= number < @range_end.
651 g_test_rand_double_range (double range_start,
654 return g_rand_double_range (test_run_rand, range_start, range_end);
658 * g_test_timer_start:
660 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
661 * to be done. Call this function again to restart the timer.
666 g_test_timer_start (void)
668 if (!test_user_timer)
669 test_user_timer = g_timer_new();
671 g_timer_start (test_user_timer);
675 * g_test_timer_elapsed:
677 * Get the time since the last start of the timer with g_test_timer_start().
679 * Returns: the time since the last start of the timer, as a double
684 g_test_timer_elapsed (void)
686 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
687 return test_user_stamp;
693 * Report the last result of g_test_timer_elapsed().
695 * Returns: the last result of g_test_timer_elapsed(), as a double
700 g_test_timer_last (void)
702 return test_user_stamp;
706 * g_test_minimized_result:
707 * @minimized_quantity: the reported value
708 * @format: the format string of the report message
709 * @...: arguments to pass to the printf() function
711 * Report the result of a performance or measurement test.
712 * The test should generally strive to minimize the reported
713 * quantities (smaller values are better than larger ones),
714 * this and @minimized_quantity can determine sorting
715 * order for test result reports.
720 g_test_minimized_result (double minimized_quantity,
724 long double largs = minimized_quantity;
728 va_start (args, format);
729 buffer = g_strdup_vprintf (format, args);
732 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
737 * g_test_maximized_result:
738 * @maximized_quantity: the reported value
739 * @format: the format string of the report message
740 * @...: arguments to pass to the printf() function
742 * Report the result of a performance or measurement test.
743 * The test should generally strive to maximize the reported
744 * quantities (larger values are better than smaller ones),
745 * this and @maximized_quantity can determine sorting
746 * order for test result reports.
751 g_test_maximized_result (double maximized_quantity,
755 long double largs = maximized_quantity;
759 va_start (args, format);
760 buffer = g_strdup_vprintf (format, args);
763 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
769 * @format: the format string
770 * @...: printf-like arguments to @format
772 * Add a message to the test report.
777 g_test_message (const char *format,
783 va_start (args, format);
784 buffer = g_strdup_vprintf (format, args);
787 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
793 * @uri_pattern: the base pattern for bug URIs
795 * Specify the base URI for bug reports.
797 * The base URI is used to construct bug report messages for
798 * g_test_message() when g_test_bug() is called.
799 * Calling this function outside of a test case sets the
800 * default base URI for all test cases. Calling it from within
801 * a test case changes the base URI for the scope of the test
803 * Bug URIs are constructed by appending a bug specific URI
804 * portion to @uri_pattern, or by replacing the special string
805 * '\%s' within @uri_pattern if that is present.
810 g_test_bug_base (const char *uri_pattern)
812 g_free (test_uri_base);
813 test_uri_base = g_strdup (uri_pattern);
818 * @bug_uri_snippet: Bug specific bug tracker URI portion.
820 * This function adds a message to test reports that
821 * associates a bug URI with a test case.
822 * Bug URIs are constructed from a base URI set with g_test_bug_base()
823 * and @bug_uri_snippet.
828 g_test_bug (const char *bug_uri_snippet)
832 g_return_if_fail (test_uri_base != NULL);
833 g_return_if_fail (bug_uri_snippet != NULL);
835 c = strstr (test_uri_base, "%s");
838 char *b = g_strndup (test_uri_base, c - test_uri_base);
839 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
841 g_test_message ("Bug Reference: %s", s);
845 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
851 * Get the toplevel test suite for the test path API.
853 * Returns: the toplevel #GTestSuite
858 g_test_get_root (void)
860 if (!test_suite_root)
862 test_suite_root = g_test_create_suite ("root");
863 g_free (test_suite_root->name);
864 test_suite_root->name = g_strdup ("");
867 return test_suite_root;
873 * Runs all tests under the toplevel suite which can be retrieved
874 * with g_test_get_root(). Similar to g_test_run_suite(), the test
875 * cases to be run are filtered according to
876 * test path arguments (-p <replaceable>testpath</replaceable>) as
877 * parsed by g_test_init().
878 * g_test_run_suite() or g_test_run() may only be called once
881 * Returns: 0 on success
888 return g_test_run_suite (g_test_get_root());
892 * g_test_create_case:
893 * @test_name: the name for the test case
894 * @data_size: the size of the fixture data structure
895 * @test_data: test data argument for the test functions
896 * @data_setup: the function to set up the fixture data
897 * @data_test: the actual test function
898 * @data_teardown: the function to teardown the fixture data
900 * Create a new #GTestCase, named @test_name, this API is fairly
901 * low level, calling g_test_add() or g_test_add_func() is preferable.
902 * When this test is executed, a fixture structure of size @data_size
903 * will be allocated and filled with 0s. Then data_setup() is called
904 * to initialize the fixture. After fixture setup, the actual test
905 * function data_test() is called. Once the test run completed, the
906 * fixture structure is torn down by calling data_teardown() and
907 * after that the memory is released.
909 * Splitting up a test run into fixture setup, test function and
910 * fixture teardown is most usful if the same fixture is used for
911 * multiple tests. In this cases, g_test_create_case() will be
912 * called with the same fixture, but varying @test_name and
913 * @data_test arguments.
915 * Returns: a newly allocated #GTestCase.
920 g_test_create_case (const char *test_name,
922 gconstpointer test_data,
923 GTestFixtureFunc data_setup,
924 GTestFixtureFunc data_test,
925 GTestFixtureFunc data_teardown)
929 g_return_val_if_fail (test_name != NULL, NULL);
930 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
931 g_return_val_if_fail (test_name[0] != 0, NULL);
932 g_return_val_if_fail (data_test != NULL, NULL);
934 tc = g_slice_new0 (GTestCase);
935 tc->name = g_strdup (test_name);
936 tc->test_data = (gpointer) test_data;
937 tc->fixture_size = data_size;
938 tc->fixture_setup = (void*) data_setup;
939 tc->fixture_test = (void*) data_test;
940 tc->fixture_teardown = (void*) data_teardown;
947 * @fixture: the test fixture
948 * @user_data: the data provided when registering the test
950 * The type used for functions that operate on test fixtures. This is
951 * used for the fixture setup and teardown functions as well as for the
952 * testcases themselves.
954 * @user_data is a pointer to the data that was given when registering
957 * @fixture will be a pointer to the area of memory allocated by the
958 * test framework, of the size requested. If the requested size was
959 * zero then @fixture will be equal to @user_data.
964 g_test_add_vtable (const char *testpath,
966 gconstpointer test_data,
967 GTestFixtureFunc data_setup,
968 GTestFixtureFunc fixture_test_func,
969 GTestFixtureFunc data_teardown)
975 g_return_if_fail (testpath != NULL);
976 g_return_if_fail (testpath[0] == '/');
977 g_return_if_fail (fixture_test_func != NULL);
979 suite = g_test_get_root();
980 segments = g_strsplit (testpath, "/", -1);
981 for (ui = 0; segments[ui] != NULL; ui++)
983 const char *seg = segments[ui];
984 gboolean islast = segments[ui + 1] == NULL;
985 if (islast && !seg[0])
986 g_error ("invalid test case path: %s", testpath);
988 continue; /* initial or duplicate slash */
991 GTestSuite *csuite = g_test_create_suite (seg);
992 g_test_suite_add_suite (suite, csuite);
997 GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
998 g_test_suite_add (suite, tc);
1001 g_strfreev (segments);
1007 * Indicates that a test failed. This function can be called
1008 * multiple times from the same test. You can use this function
1009 * if your test failed in a recoverable way.
1011 * Do not use this function if the failure of a test could cause
1012 * other tests to malfunction.
1014 * Calling this function will not stop the test from running, you
1015 * need to return from the test function yourself. So you can
1016 * produce additional diagnostic messages or even continue running
1019 * If not called from inside a test, this function does nothing.
1026 test_run_success = FALSE;
1032 * The type used for test case functions.
1039 * @testpath: Slash-separated test case path name for the test.
1040 * @test_func: The test function to invoke for this test.
1042 * Create a new test case, similar to g_test_create_case(). However
1043 * the test is assumed to use no fixture, and test suites are automatically
1044 * created on the fly and added to the root fixture, based on the
1045 * slash-separated portions of @testpath.
1050 g_test_add_func (const char *testpath,
1051 GTestFunc test_func)
1053 g_return_if_fail (testpath != NULL);
1054 g_return_if_fail (testpath[0] == '/');
1055 g_return_if_fail (test_func != NULL);
1056 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1061 * @user_data: the data provided when registering the test
1063 * The type used for test case functions that take an extra pointer
1070 * g_test_add_data_func:
1071 * @testpath: Slash-separated test case path name for the test.
1072 * @test_data: Test data argument for the test function.
1073 * @test_func: The test function to invoke for this test.
1075 * Create a new test case, similar to g_test_create_case(). However
1076 * the test is assumed to use no fixture, and test suites are automatically
1077 * created on the fly and added to the root fixture, based on the
1078 * slash-separated portions of @testpath. The @test_data argument
1079 * will be passed as first argument to @test_func.
1084 g_test_add_data_func (const char *testpath,
1085 gconstpointer test_data,
1086 GTestDataFunc test_func)
1088 g_return_if_fail (testpath != NULL);
1089 g_return_if_fail (testpath[0] == '/');
1090 g_return_if_fail (test_func != NULL);
1091 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1095 * g_test_create_suite:
1096 * @suite_name: a name for the suite
1098 * Create a new test suite with the name @suite_name.
1100 * Returns: A newly allocated #GTestSuite instance.
1105 g_test_create_suite (const char *suite_name)
1108 g_return_val_if_fail (suite_name != NULL, NULL);
1109 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1110 g_return_val_if_fail (suite_name[0] != 0, NULL);
1111 ts = g_slice_new0 (GTestSuite);
1112 ts->name = g_strdup (suite_name);
1118 * @suite: a #GTestSuite
1119 * @test_case: a #GTestCase
1121 * Adds @test_case to @suite.
1126 g_test_suite_add (GTestSuite *suite,
1127 GTestCase *test_case)
1129 g_return_if_fail (suite != NULL);
1130 g_return_if_fail (test_case != NULL);
1132 suite->cases = g_slist_prepend (suite->cases, test_case);
1136 * g_test_suite_add_suite:
1137 * @suite: a #GTestSuite
1138 * @nestedsuite: another #GTestSuite
1140 * Adds @nestedsuite to @suite.
1145 g_test_suite_add_suite (GTestSuite *suite,
1146 GTestSuite *nestedsuite)
1148 g_return_if_fail (suite != NULL);
1149 g_return_if_fail (nestedsuite != NULL);
1151 suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1155 * g_test_queue_free:
1156 * @gfree_pointer: the pointer to be stored.
1158 * Enqueue a pointer to be released with g_free() during the next
1159 * teardown phase. This is equivalent to calling g_test_queue_destroy()
1160 * with a destroy callback of g_free().
1165 g_test_queue_free (gpointer gfree_pointer)
1168 g_test_queue_destroy (g_free, gfree_pointer);
1172 * g_test_queue_destroy:
1173 * @destroy_func: Destroy callback for teardown phase.
1174 * @destroy_data: Destroy callback data.
1176 * This function enqueus a callback @destroy_func() to be executed
1177 * during the next test case teardown phase. This is most useful
1178 * to auto destruct allocted test resources at the end of a test run.
1179 * Resources are released in reverse queue order, that means enqueueing
1180 * callback A before callback B will cause B() to be called before
1181 * A() during teardown.
1186 g_test_queue_destroy (GDestroyNotify destroy_func,
1187 gpointer destroy_data)
1189 DestroyEntry *dentry;
1191 g_return_if_fail (destroy_func != NULL);
1193 dentry = g_slice_new0 (DestroyEntry);
1194 dentry->destroy_func = destroy_func;
1195 dentry->destroy_data = destroy_data;
1196 dentry->next = test_destroy_queue;
1197 test_destroy_queue = dentry;
1201 test_case_run (GTestCase *tc)
1203 gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1204 gboolean success = TRUE;
1206 test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1207 if (++test_run_count <= test_skip_count)
1208 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1209 else if (test_run_list)
1211 g_print ("%s\n", test_run_name);
1212 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1216 GTimer *test_run_timer = g_timer_new();
1217 long double largs[3];
1219 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1221 test_run_success = TRUE;
1222 g_test_log_set_fatal_handler (NULL, NULL);
1223 g_timer_start (test_run_timer);
1224 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1225 test_run_seed (test_run_seedstr);
1226 if (tc->fixture_setup)
1227 tc->fixture_setup (fixture, tc->test_data);
1228 tc->fixture_test (fixture, tc->test_data);
1230 while (test_destroy_queue)
1232 DestroyEntry *dentry = test_destroy_queue;
1233 test_destroy_queue = dentry->next;
1234 dentry->destroy_func (dentry->destroy_data);
1235 g_slice_free (DestroyEntry, dentry);
1237 if (tc->fixture_teardown)
1238 tc->fixture_teardown (fixture, tc->test_data);
1239 if (tc->fixture_size)
1241 g_timer_stop (test_run_timer);
1242 success = test_run_success;
1243 test_run_success = FALSE;
1244 largs[0] = success ? 0 : 1; /* OK */
1245 largs[1] = test_run_forks;
1246 largs[2] = g_timer_elapsed (test_run_timer, NULL);
1247 g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1248 g_timer_destroy (test_run_timer);
1250 g_free (test_run_name);
1251 test_run_name = old_name;
1252 g_free (test_uri_base);
1253 test_uri_base = old_base;
1259 g_test_run_suite_internal (GTestSuite *suite,
1263 gchar *rest, *old_name = test_run_name;
1264 GSList *slist, *reversed;
1266 g_return_val_if_fail (suite != NULL, -1);
1268 while (path[0] == '/')
1271 rest = strchr (path, '/');
1272 l = rest ? MIN (l, rest - path) : l;
1273 test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1274 reversed = g_slist_reverse (g_slist_copy (suite->cases));
1275 for (slist = reversed; slist; slist = slist->next)
1277 GTestCase *tc = slist->data;
1278 guint n = l ? strlen (tc->name) : 0;
1279 if (l == n && strncmp (path, tc->name, n) == 0)
1281 if (!test_case_run (tc))
1285 g_slist_free (reversed);
1286 reversed = g_slist_reverse (g_slist_copy (suite->suites));
1287 for (slist = reversed; slist; slist = slist->next)
1289 GTestSuite *ts = slist->data;
1290 guint n = l ? strlen (ts->name) : 0;
1291 if (l == n && strncmp (path, ts->name, n) == 0)
1292 n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
1294 g_slist_free (reversed);
1295 g_free (test_run_name);
1296 test_run_name = old_name;
1303 * @suite: a #GTestSuite
1305 * Execute the tests within @suite and all nested #GTestSuites.
1306 * The test suites to be executed are filtered according to
1307 * test path arguments (-p <replaceable>testpath</replaceable>)
1308 * as parsed by g_test_init().
1309 * g_test_run_suite() or g_test_run() may only be called once
1312 * Returns: 0 on success
1317 g_test_run_suite (GTestSuite *suite)
1321 g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1322 g_return_val_if_fail (g_test_run_once == TRUE, -1);
1324 g_test_run_once = FALSE;
1327 test_paths = g_slist_prepend (test_paths, "");
1330 const char *rest, *path = test_paths->data;
1331 guint l, n = strlen (suite->name);
1332 test_paths = g_slist_delete_link (test_paths, test_paths);
1333 while (path[0] == '/')
1335 if (!n) /* root suite, run unconditionally */
1337 n_bad += g_test_run_suite_internal (suite, path);
1340 /* regular suite, match path */
1341 rest = strchr (path, '/');
1343 l = rest ? MIN (l, rest - path) : l;
1344 if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1345 n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
1352 gtest_default_log_handler (const gchar *log_domain,
1353 GLogLevelFlags log_level,
1354 const gchar *message,
1355 gpointer unused_data)
1357 const gchar *strv[16];
1358 gboolean fatal = FALSE;
1364 strv[i++] = log_domain;
1367 if (log_level & G_LOG_FLAG_FATAL)
1369 strv[i++] = "FATAL-";
1372 if (log_level & G_LOG_FLAG_RECURSION)
1373 strv[i++] = "RECURSIVE-";
1374 if (log_level & G_LOG_LEVEL_ERROR)
1375 strv[i++] = "ERROR";
1376 if (log_level & G_LOG_LEVEL_CRITICAL)
1377 strv[i++] = "CRITICAL";
1378 if (log_level & G_LOG_LEVEL_WARNING)
1379 strv[i++] = "WARNING";
1380 if (log_level & G_LOG_LEVEL_MESSAGE)
1381 strv[i++] = "MESSAGE";
1382 if (log_level & G_LOG_LEVEL_INFO)
1384 if (log_level & G_LOG_LEVEL_DEBUG)
1385 strv[i++] = "DEBUG";
1387 strv[i++] = message;
1390 msg = g_strjoinv ("", (gchar**) strv);
1391 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
1392 g_log_default_handler (log_domain, log_level, message, unused_data);
1398 g_assertion_message (const char *domain,
1402 const char *message)
1408 message = "code should not be reached";
1409 g_snprintf (lstr, 32, "%d", line);
1410 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1411 "ERROR:", file, ":", lstr, ":",
1412 func, func[0] ? ":" : "",
1413 " ", message, NULL);
1414 g_printerr ("**\n%s\n", s);
1416 /* store assertion message in global variable, so that it can be found in a
1418 if (__glib_assert_msg != NULL)
1419 /* free the old one */
1420 free (__glib_assert_msg);
1421 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
1422 strcpy (__glib_assert_msg, s);
1424 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
1430 g_assertion_message_expr (const char *domain,
1436 char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1437 g_assertion_message (domain, file, line, func, s);
1442 g_assertion_message_cmpnum (const char *domain,
1455 case 'i': s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
1456 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;
1457 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
1458 /* ideally use: floats=%.7g double=%.17g */
1460 g_assertion_message (domain, file, line, func, s);
1465 g_assertion_message_cmpstr (const char *domain,
1474 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1475 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1476 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1479 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1482 g_assertion_message (domain, file, line, func, s);
1487 g_assertion_message_error (const char *domain,
1492 const GError *error,
1493 GQuark error_domain,
1498 /* This is used by both g_assert_error() and g_assert_no_error(), so there
1499 * are three cases: expected an error but got the wrong error, expected
1500 * an error but got no error, and expected no error but got an error.
1503 gstring = g_string_new ("assertion failed ");
1505 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
1506 g_quark_to_string (error_domain), error_code);
1508 g_string_append_printf (gstring, "(%s == NULL): ", expr);
1511 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
1512 g_quark_to_string (error->domain), error->code);
1514 g_string_append_printf (gstring, "%s is NULL", expr);
1516 g_assertion_message (domain, file, line, func, gstring->str);
1517 g_string_free (gstring, TRUE);
1522 * @str1: a C string or %NULL
1523 * @str2: another C string or %NULL
1525 * Compares @str1 and @str2 like strcmp(). Handles %NULL
1526 * gracefully by sorting it before non-%NULL strings.
1527 * Comparing two %NULL pointers returns 0.
1529 * Returns: -1, 0 or 1, if @str1 is <, == or > than @str2.
1534 g_strcmp0 (const char *str1,
1538 return -(str1 != str2);
1540 return str1 != str2;
1541 return strcmp (str1, str2);
1545 static int /* 0 on success */
1546 kill_child (int pid,
1551 if (patience >= 3) /* try graceful reap */
1553 if (waitpid (pid, status, WNOHANG) > 0)
1556 if (patience >= 2) /* try SIGHUP */
1559 if (waitpid (pid, status, WNOHANG) > 0)
1561 g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1562 if (waitpid (pid, status, WNOHANG) > 0)
1564 g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
1565 if (waitpid (pid, status, WNOHANG) > 0)
1567 g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
1568 if (waitpid (pid, status, WNOHANG) > 0)
1571 if (patience >= 1) /* try SIGTERM */
1573 kill (pid, SIGTERM);
1574 if (waitpid (pid, status, WNOHANG) > 0)
1576 g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
1577 if (waitpid (pid, status, WNOHANG) > 0)
1579 g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
1580 if (waitpid (pid, status, WNOHANG) > 0)
1584 kill (pid, SIGKILL);
1586 wr = waitpid (pid, status, 0);
1587 while (wr < 0 && errno == EINTR);
1593 g_string_must_read (GString *gstring,
1596 #define STRING_BUFFER_SIZE 4096
1597 char buf[STRING_BUFFER_SIZE];
1600 bytes = read (fd, buf, sizeof (buf));
1602 return 0; /* EOF, calling this function assumes data is available */
1605 g_string_append_len (gstring, buf, bytes);
1608 else if (bytes < 0 && errno == EINTR)
1610 else /* bytes < 0 */
1612 g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1613 return 1; /* ignore error after warning */
1618 g_string_write_out (GString *gstring,
1622 if (*stringpos < gstring->len)
1626 r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
1627 while (r < 0 && errno == EINTR);
1628 *stringpos += MAX (r, 0);
1633 test_trap_clear (void)
1635 test_trap_last_status = 0;
1636 test_trap_last_pid = 0;
1637 g_free (test_trap_last_stdout);
1638 test_trap_last_stdout = NULL;
1639 g_free (test_trap_last_stderr);
1640 test_trap_last_stderr = NULL;
1651 ret = dup2 (fd1, fd2);
1652 while (ret < 0 && errno == EINTR);
1657 test_time_stamp (void)
1661 g_get_current_time (&tv);
1663 stamp = stamp * 1000000 + tv.tv_usec;
1671 * @usec_timeout: Timeout for the forked test in micro seconds.
1672 * @test_trap_flags: Flags to modify forking behaviour.
1674 * Fork the current test program to execute a test case that might
1675 * not return or that might abort. The forked test case is aborted
1676 * and considered failing if its run time exceeds @usec_timeout.
1678 * The forking behavior can be configured with the #GTestTrapFlags flags.
1680 * In the following example, the test code forks, the forked child
1681 * process produces some sample output and exits successfully.
1682 * The forking parent process then asserts successful child program
1683 * termination and validates child program outputs.
1687 * test_fork_patterns (void)
1689 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
1691 * g_print ("some stdout text: somagic17\n");
1692 * g_printerr ("some stderr text: semagic43\n");
1693 * exit (0); /* successful test run */
1695 * g_test_trap_assert_passed();
1696 * g_test_trap_assert_stdout ("*somagic17*");
1697 * g_test_trap_assert_stderr ("*semagic43*");
1701 * This function is implemented only on Unix platforms.
1703 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
1708 g_test_trap_fork (guint64 usec_timeout,
1709 GTestTrapFlags test_trap_flags)
1712 gboolean pass_on_forked_log = FALSE;
1713 int stdout_pipe[2] = { -1, -1 };
1714 int stderr_pipe[2] = { -1, -1 };
1715 int stdtst_pipe[2] = { -1, -1 };
1717 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
1718 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
1719 signal (SIGCHLD, SIG_DFL);
1720 test_trap_last_pid = fork ();
1721 if (test_trap_last_pid < 0)
1722 g_error ("failed to fork test program: %s", g_strerror (errno));
1723 if (test_trap_last_pid == 0) /* child */
1726 close (stdout_pipe[0]);
1727 close (stderr_pipe[0]);
1728 close (stdtst_pipe[0]);
1729 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
1730 fd0 = open ("/dev/null", O_RDONLY);
1731 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
1732 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
1735 if (stdout_pipe[1] >= 3)
1736 close (stdout_pipe[1]);
1737 if (stderr_pipe[1] >= 3)
1738 close (stderr_pipe[1]);
1739 test_log_fd = stdtst_pipe[1];
1744 GString *sout = g_string_new (NULL);
1745 GString *serr = g_string_new (NULL);
1747 int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
1749 close (stdout_pipe[1]);
1750 close (stderr_pipe[1]);
1751 close (stdtst_pipe[1]);
1752 sstamp = test_time_stamp();
1753 /* read data until we get EOF on all pipes */
1754 while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
1760 if (stdout_pipe[0] >= 0)
1761 FD_SET (stdout_pipe[0], &fds);
1762 if (stderr_pipe[0] >= 0)
1763 FD_SET (stderr_pipe[0], &fds);
1764 if (stdtst_pipe[0] >= 0)
1765 FD_SET (stdtst_pipe[0], &fds);
1767 tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
1768 ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
1769 if (ret < 0 && errno != EINTR)
1771 g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1774 if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
1775 g_string_must_read (sout, stdout_pipe[0]) == 0)
1777 close (stdout_pipe[0]);
1778 stdout_pipe[0] = -1;
1780 if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
1781 g_string_must_read (serr, stderr_pipe[0]) == 0)
1783 close (stderr_pipe[0]);
1784 stderr_pipe[0] = -1;
1786 if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
1788 guint8 buffer[4096];
1789 gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
1790 if (r > 0 && test_log_fd > 0)
1792 l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
1793 while (l < 0 && errno == EINTR);
1794 if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
1796 close (stdtst_pipe[0]);
1797 stdtst_pipe[0] = -1;
1800 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
1801 g_string_write_out (sout, 1, &soutpos);
1802 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
1803 g_string_write_out (serr, 2, &serrpos);
1806 guint64 nstamp = test_time_stamp();
1808 sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
1809 if (usec_timeout < nstamp - sstamp)
1811 /* timeout reached, need to abort the child now */
1812 kill_child (test_trap_last_pid, &status, 3);
1813 test_trap_last_status = 1024; /* timeout */
1814 if (0 && WIFSIGNALED (status))
1815 g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
1821 if (stdout_pipe[0] != -1)
1822 close (stdout_pipe[0]);
1823 if (stderr_pipe[0] != -1)
1824 close (stderr_pipe[0]);
1825 if (stdtst_pipe[0] != -1)
1826 close (stdtst_pipe[0]);
1831 wr = waitpid (test_trap_last_pid, &status, 0);
1832 while (wr < 0 && errno == EINTR);
1833 if (WIFEXITED (status)) /* normal exit */
1834 test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
1835 else if (WIFSIGNALED (status))
1836 test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
1837 else /* WCOREDUMP (status) */
1838 test_trap_last_status = 512; /* coredump */
1840 test_trap_last_stdout = g_string_free (sout, FALSE);
1841 test_trap_last_stderr = g_string_free (serr, FALSE);
1845 g_message ("Not implemented: g_test_trap_fork");
1852 * g_test_trap_has_passed:
1854 * Check the result of the last g_test_trap_fork() call.
1856 * Returns: %TRUE if the last forked child terminated successfully.
1861 g_test_trap_has_passed (void)
1863 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
1867 * g_test_trap_reached_timeout:
1869 * Check the result of the last g_test_trap_fork() call.
1871 * Returns: %TRUE if the last forked child got killed due to a fork timeout.
1876 g_test_trap_reached_timeout (void)
1878 return 0 != (test_trap_last_status & 1024); /* timeout flag */
1882 g_test_trap_assertions (const char *domain,
1886 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
1887 const char *pattern)
1890 gboolean must_pass = assertion_flags == 0;
1891 gboolean must_fail = assertion_flags == 1;
1892 gboolean match_result = 0 == (assertion_flags & 1);
1893 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
1894 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
1895 const char *match_error = match_result ? "failed to match" : "contains invalid match";
1896 if (test_trap_last_pid == 0)
1897 g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
1898 if (must_pass && !g_test_trap_has_passed())
1900 char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
1901 g_assertion_message (domain, file, line, func, msg);
1904 if (must_fail && g_test_trap_has_passed())
1906 char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
1907 g_assertion_message (domain, file, line, func, msg);
1910 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
1912 char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
1913 g_assertion_message (domain, file, line, func, msg);
1916 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
1918 char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
1919 g_assertion_message (domain, file, line, func, msg);
1926 gstring_overwrite_int (GString *gstring,
1930 vuint = g_htonl (vuint);
1931 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
1935 gstring_append_int (GString *gstring,
1938 vuint = g_htonl (vuint);
1939 g_string_append_len (gstring, (const gchar*) &vuint, 4);
1943 gstring_append_double (GString *gstring,
1946 union { double vdouble; guint64 vuint64; } u;
1947 u.vdouble = vdouble;
1948 u.vuint64 = GUINT64_TO_BE (u.vuint64);
1949 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
1953 g_test_log_dump (GTestLogMsg *msg,
1956 GString *gstring = g_string_sized_new (1024);
1958 gstring_append_int (gstring, 0); /* message length */
1959 gstring_append_int (gstring, msg->log_type);
1960 gstring_append_int (gstring, msg->n_strings);
1961 gstring_append_int (gstring, msg->n_nums);
1962 gstring_append_int (gstring, 0); /* reserved */
1963 for (ui = 0; ui < msg->n_strings; ui++)
1965 guint l = strlen (msg->strings[ui]);
1966 gstring_append_int (gstring, l);
1967 g_string_append_len (gstring, msg->strings[ui], l);
1969 for (ui = 0; ui < msg->n_nums; ui++)
1970 gstring_append_double (gstring, msg->nums[ui]);
1971 *len = gstring->len;
1972 gstring_overwrite_int (gstring, 0, *len); /* message length */
1973 return (guint8*) g_string_free (gstring, FALSE);
1976 static inline long double
1977 net_double (const gchar **ipointer)
1979 union { guint64 vuint64; double vdouble; } u;
1980 guint64 aligned_int64;
1981 memcpy (&aligned_int64, *ipointer, 8);
1983 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
1987 static inline guint32
1988 net_int (const gchar **ipointer)
1990 guint32 aligned_int;
1991 memcpy (&aligned_int, *ipointer, 4);
1993 return g_ntohl (aligned_int);
1997 g_test_log_extract (GTestLogBuffer *tbuffer)
1999 const gchar *p = tbuffer->data->str;
2002 if (tbuffer->data->len < 4 * 5)
2004 mlength = net_int (&p);
2005 if (tbuffer->data->len < mlength)
2007 msg.log_type = net_int (&p);
2008 msg.n_strings = net_int (&p);
2009 msg.n_nums = net_int (&p);
2010 if (net_int (&p) == 0)
2013 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
2014 msg.nums = g_new0 (long double, msg.n_nums);
2015 for (ui = 0; ui < msg.n_strings; ui++)
2017 guint sl = net_int (&p);
2018 msg.strings[ui] = g_strndup (p, sl);
2021 for (ui = 0; ui < msg.n_nums; ui++)
2022 msg.nums[ui] = net_double (&p);
2023 if (p <= tbuffer->data->str + mlength)
2025 g_string_erase (tbuffer->data, 0, mlength);
2026 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
2031 g_strfreev (msg.strings);
2032 g_error ("corrupt log stream from test program");
2037 * g_test_log_buffer_new:
2039 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2042 g_test_log_buffer_new (void)
2044 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
2045 tb->data = g_string_sized_new (1024);
2050 * g_test_log_buffer_free
2052 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2055 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
2057 g_return_if_fail (tbuffer != NULL);
2058 while (tbuffer->msgs)
2059 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
2060 g_string_free (tbuffer->data, TRUE);
2065 * g_test_log_buffer_push
2067 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2070 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
2072 const guint8 *bytes)
2074 g_return_if_fail (tbuffer != NULL);
2077 gboolean more_messages;
2078 g_return_if_fail (bytes != NULL);
2079 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
2081 more_messages = g_test_log_extract (tbuffer);
2082 while (more_messages);
2087 * g_test_log_buffer_pop:
2089 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
2092 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
2094 GTestLogMsg *msg = NULL;
2095 g_return_val_if_fail (tbuffer != NULL, NULL);
2098 GSList *slist = g_slist_last (tbuffer->msgs);
2100 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
2106 * g_test_log_msg_free:
2108 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2111 g_test_log_msg_free (GTestLogMsg *tmsg)
2113 g_return_if_fail (tmsg != NULL);
2114 g_strfreev (tmsg->strings);
2115 g_free (tmsg->nums);
2119 /* --- macros docs START --- */
2122 * @testpath: The test path for a new test case.
2123 * @Fixture: The type of a fixture data structure.
2124 * @tdata: Data argument for the test functions.
2125 * @fsetup: The function to set up the fixture data.
2126 * @ftest: The actual test function.
2127 * @fteardown: The function to tear down the fixture data.
2129 * Hook up a new test case at @testpath, similar to g_test_add_func().
2130 * A fixture data structure with setup and teardown function may be provided
2131 * though, similar to g_test_create_case().
2132 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2133 * fteardown() callbacks can expect a @Fixture pointer as first argument in
2134 * a type safe manner.
2138 /* --- macros docs END --- */