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.
21 #include "gtestutils.h"
23 #include <sys/types.h>
40 #ifdef HAVE_SYS_SELECT_H
41 #include <sys/select.h>
42 #endif /* HAVE_SYS_SELECT_H */
44 /* Global variable for storing assertion messages; this is the counterpart to
45 * glibc's (private) __abort_msg variable, and allows developers and crash
46 * analysis systems like Apport and ABRT to fish out assertion messages from
47 * core dumps, instead of having to catch them on screen output. */
48 char *__glib_assert_msg = NULL;
50 /* --- structures --- */
55 void (*fixture_setup) (void*, gconstpointer);
56 void (*fixture_test) (void*, gconstpointer);
57 void (*fixture_teardown) (void*, gconstpointer);
66 typedef struct DestroyEntry DestroyEntry;
70 GDestroyNotify destroy_func;
71 gpointer destroy_data;
74 /* --- prototypes --- */
75 static void test_run_seed (const gchar *rseed);
76 static void test_trap_clear (void);
77 static guint8* g_test_log_dump (GTestLogMsg *msg,
79 static void gtest_default_log_handler (const gchar *log_domain,
80 GLogLevelFlags log_level,
82 gpointer unused_data);
85 /* --- variables --- */
86 static int test_log_fd = -1;
87 static gboolean test_mode_fatal = TRUE;
88 static gboolean g_test_run_once = TRUE;
89 static gboolean test_run_list = FALSE;
90 static gchar *test_run_seedstr = NULL;
91 static GRand *test_run_rand = NULL;
92 static gchar *test_run_name = "";
93 static guint test_run_forks = 0;
94 static guint test_run_count = 0;
95 static guint test_skip_count = 0;
96 static GTimer *test_user_timer = NULL;
97 static double test_user_stamp = 0;
98 static GSList *test_paths = NULL;
99 static GTestSuite *test_suite_root = NULL;
100 static int test_trap_last_status = 0;
101 static int test_trap_last_pid = 0;
102 static char *test_trap_last_stdout = NULL;
103 static char *test_trap_last_stderr = NULL;
104 static char *test_uri_base = NULL;
105 static gboolean test_debug_log = FALSE;
106 static DestroyEntry *test_destroy_queue = NULL;
107 static GTestConfig mutable_test_config_vars = {
108 FALSE, /* test_initialized */
109 TRUE, /* test_quick */
110 FALSE, /* test_perf */
111 FALSE, /* test_verbose */
112 FALSE, /* test_quiet */
114 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
116 /* --- functions --- */
118 g_test_log_type_name (GTestLogType log_type)
122 case G_TEST_LOG_NONE: return "none";
123 case G_TEST_LOG_ERROR: return "error";
124 case G_TEST_LOG_START_BINARY: return "binary";
125 case G_TEST_LOG_LIST_CASE: return "list";
126 case G_TEST_LOG_SKIP_CASE: return "skip";
127 case G_TEST_LOG_START_CASE: return "start";
128 case G_TEST_LOG_STOP_CASE: return "stop";
129 case G_TEST_LOG_MIN_RESULT: return "minperf";
130 case G_TEST_LOG_MAX_RESULT: return "maxperf";
131 case G_TEST_LOG_MESSAGE: return "message";
137 g_test_log_send (guint n_bytes,
138 const guint8 *buffer)
140 if (test_log_fd >= 0)
144 r = write (test_log_fd, buffer, n_bytes);
145 while (r < 0 && errno == EINTR);
149 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
152 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
153 msg = g_test_log_buffer_pop (lbuffer);
154 g_warn_if_fail (msg != NULL);
155 g_warn_if_fail (lbuffer->data->len == 0);
156 g_test_log_buffer_free (lbuffer);
158 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
159 for (ui = 0; ui < msg->n_strings; ui++)
160 g_printerr (":{%s}", msg->strings[ui]);
164 for (ui = 0; ui < msg->n_nums; ui++)
165 g_printerr ("%s%.16Lg", ui ? ";" : "", msg->nums[ui]);
168 g_printerr (":LOG*}\n");
169 g_test_log_msg_free (msg);
174 g_test_log (GTestLogType lbit,
175 const gchar *string1,
176 const gchar *string2,
180 gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
182 gchar *astrings[3] = { NULL, NULL, NULL };
188 case G_TEST_LOG_START_BINARY:
189 if (g_test_verbose())
190 g_print ("GTest: random seed: %s\n", string2);
192 case G_TEST_LOG_STOP_CASE:
193 if (g_test_verbose())
194 g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
195 else if (!g_test_quiet())
196 g_print ("%s\n", fail ? "FAIL" : "OK");
197 if (fail && test_mode_fatal)
200 case G_TEST_LOG_MIN_RESULT:
201 if (g_test_verbose())
202 g_print ("(MINPERF:%s)\n", string1);
204 case G_TEST_LOG_MAX_RESULT:
205 if (g_test_verbose())
206 g_print ("(MAXPERF:%s)\n", string1);
208 case G_TEST_LOG_MESSAGE:
209 if (g_test_verbose())
210 g_print ("(MSG: %s)\n", string1);
216 msg.n_strings = (string1 != NULL) + (string1 && string2);
217 msg.strings = astrings;
218 astrings[0] = (gchar*) string1;
219 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
222 dbuffer = g_test_log_dump (&msg, &dbufferlen);
223 g_test_log_send (dbufferlen, dbuffer);
228 case G_TEST_LOG_START_CASE:
229 if (g_test_verbose())
230 g_print ("GTest: run: %s\n", string1);
231 else if (!g_test_quiet())
232 g_print ("%s: ", string1);
238 /* We intentionally parse the command line without GOptionContext
239 * because otherwise you would never be able to test it.
242 parse_args (gint *argc_p,
245 guint argc = *argc_p;
246 gchar **argv = *argv_p;
248 /* parse known args */
249 for (i = 1; i < argc; i++)
251 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
253 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
254 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
255 g_log_set_always_fatal (fatal_mask);
258 else if (strcmp (argv[i], "--keep-going") == 0 ||
259 strcmp (argv[i], "-k") == 0)
261 test_mode_fatal = FALSE;
264 else if (strcmp (argv[i], "--debug-log") == 0)
266 test_debug_log = TRUE;
269 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
271 gchar *equal = argv[i] + 12;
273 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
274 else if (i + 1 < argc)
277 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
281 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
283 gchar *equal = argv[i] + 16;
285 test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
286 else if (i + 1 < argc)
289 test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
293 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
295 gchar *equal = argv[i] + 2;
297 test_paths = g_slist_prepend (test_paths, equal + 1);
298 else if (i + 1 < argc)
301 test_paths = g_slist_prepend (test_paths, argv[i]);
305 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
307 gchar *equal = argv[i] + 2;
308 const gchar *mode = "";
311 else if (i + 1 < argc)
316 if (strcmp (mode, "perf") == 0)
317 mutable_test_config_vars.test_perf = TRUE;
318 else if (strcmp (mode, "slow") == 0)
319 mutable_test_config_vars.test_quick = FALSE;
320 else if (strcmp (mode, "thorough") == 0)
321 mutable_test_config_vars.test_quick = FALSE;
322 else if (strcmp (mode, "quick") == 0)
324 mutable_test_config_vars.test_quick = TRUE;
325 mutable_test_config_vars.test_perf = FALSE;
328 g_error ("unknown test mode: -m %s", mode);
331 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
333 mutable_test_config_vars.test_quiet = TRUE;
334 mutable_test_config_vars.test_verbose = FALSE;
337 else if (strcmp ("--verbose", argv[i]) == 0)
339 mutable_test_config_vars.test_quiet = FALSE;
340 mutable_test_config_vars.test_verbose = TRUE;
343 else if (strcmp ("-l", argv[i]) == 0)
345 test_run_list = TRUE;
348 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
350 gchar *equal = argv[i] + 6;
352 test_run_seedstr = equal + 1;
353 else if (i + 1 < argc)
356 test_run_seedstr = argv[i];
360 else if (strcmp ("-?", argv[i]) == 0 || strcmp ("--help", argv[i]) == 0)
363 " %s [OPTION...]\n\n"
365 " -?, --help Show help options\n"
367 " -l List test cases available in a test executable\n"
368 " -seed=RANDOMSEED Provide a random seed to reproduce test\n"
369 " runs using random numbers\n"
370 " --verbose Run tests verbosely\n"
371 " -q, --quiet Run tests quietly\n"
372 " -p TESTPATH execute all tests matching TESTPATH\n"
373 " -m {perf|slow|thorough|quick} Execute tests according modes\n"
374 " --debug-log debug test logging output\n"
375 " -k, --keep-going gtester-specific argument\n"
376 " --GTestLogFD=N gtester-specific argument\n"
377 " --GTestSkipCount=N gtester-specific argument\n",
384 for (i = 1; i < argc; i++)
396 * @argc: Address of the @argc parameter of the main() function.
397 * Changed if any arguments were handled.
398 * @argv: Address of the @argv parameter of main().
399 * Any parameters understood by g_test_init() stripped before return.
400 * @Varargs: Reserved for future extension. Currently, you must pass %NULL.
402 * Initialize the GLib testing framework, e.g. by seeding the
403 * test random number generator, the name for g_get_prgname()
404 * and parsing test related command line args.
405 * So far, the following arguments are understood:
408 * <term><option>-l</option></term>
410 * list test cases available in a test executable.
414 * <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
416 * provide a random seed to reproduce test runs using random numbers.
420 * <term><option>--verbose</option></term>
421 * <listitem><para>run tests verbosely.</para></listitem>
424 * <term><option>-q</option>, <option>--quiet</option></term>
425 * <listitem><para>run tests quietly.</para></listitem>
428 * <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
430 * execute all tests matching <replaceable>TESTPATH</replaceable>.
434 * <term><option>-m {perf|slow|thorough|quick}</option></term>
436 * execute tests according to these test modes:
441 * performance tests, may take long and report results.
445 * <term>slow, thorough</term>
447 * slow and thorough tests, may take quite long and
454 * quick tests, should run really quickly and give good coverage.
461 * <term><option>--debug-log</option></term>
462 * <listitem><para>debug test logging output.</para></listitem>
465 * <term><option>-k</option>, <option>--keep-going</option></term>
466 * <listitem><para>gtester-specific argument.</para></listitem>
469 * <term><option>--GTestLogFD <replaceable>N</replaceable></option></term>
470 * <listitem><para>gtester-specific argument.</para></listitem>
473 * <term><option>--GTestSkipCount <replaceable>N</replaceable></option></term>
474 * <listitem><para>gtester-specific argument.</para></listitem>
481 g_test_init (int *argc,
485 static char seedstr[4 + 4 * 8 + 1];
488 /* make warnings and criticals fatal for all test programs */
489 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
490 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
491 g_log_set_always_fatal (fatal_mask);
492 /* check caller args */
493 g_return_if_fail (argc != NULL);
494 g_return_if_fail (argv != NULL);
495 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
496 mutable_test_config_vars.test_initialized = TRUE;
498 va_start (args, argv);
499 vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
501 g_return_if_fail (vararg1 == NULL);
503 /* setup random seed string */
504 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
505 test_run_seedstr = seedstr;
507 /* parse args, sets up mode, changes seed, etc. */
508 parse_args (argc, argv);
509 if (!g_get_prgname())
510 g_set_prgname ((*argv)[0]);
512 /* verify GRand reliability, needed for reliable seeds */
515 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
516 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
517 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
518 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
519 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
523 /* check rand seed */
524 test_run_seed (test_run_seedstr);
526 /* report program start */
527 g_log_set_default_handler (gtest_default_log_handler, NULL);
528 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
532 test_run_seed (const gchar *rseed)
534 guint seed_failed = 0;
536 g_rand_free (test_run_rand);
537 test_run_rand = NULL;
538 while (strchr (" \t\v\r\n\f", *rseed))
540 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
542 const char *s = rseed + 4;
543 if (strlen (s) >= 32) /* require 4 * 8 chars */
545 guint32 seedarray[4];
546 gchar *p, hexbuf[9] = { 0, };
547 memcpy (hexbuf, s + 0, 8);
548 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
549 seed_failed += p != NULL && *p != 0;
550 memcpy (hexbuf, s + 8, 8);
551 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
552 seed_failed += p != NULL && *p != 0;
553 memcpy (hexbuf, s + 16, 8);
554 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
555 seed_failed += p != NULL && *p != 0;
556 memcpy (hexbuf, s + 24, 8);
557 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
558 seed_failed += p != NULL && *p != 0;
561 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
566 g_error ("Unknown or invalid random seed: %s", rseed);
572 * Get a reproducible random integer number.
574 * The random numbers generated by the g_test_rand_*() family of functions
575 * change with every new test program start, unless the --seed option is
576 * given when starting test programs.
578 * For individual test cases however, the random number generator is
579 * reseeded, to avoid dependencies between tests and to make --seed
580 * effective for all test cases.
582 * Returns: a random number from the seeded random number generator.
587 g_test_rand_int (void)
589 return g_rand_int (test_run_rand);
593 * g_test_rand_int_range:
594 * @begin: the minimum value returned by this function
595 * @end: the smallest value not to be returned by this function
597 * Get a reproducible random integer number out of a specified range,
598 * see g_test_rand_int() for details on test case random numbers.
600 * Returns: a number with @begin <= number < @end.
605 g_test_rand_int_range (gint32 begin,
608 return g_rand_int_range (test_run_rand, begin, end);
612 * g_test_rand_double:
614 * Get a reproducible random floating point number,
615 * see g_test_rand_int() for details on test case random numbers.
617 * Returns: a random number from the seeded random number generator.
622 g_test_rand_double (void)
624 return g_rand_double (test_run_rand);
628 * g_test_rand_double_range:
629 * @range_start: the minimum value returned by this function
630 * @range_end: the minimum value not returned by this function
632 * Get a reproducible random floating pointer number out of a specified range,
633 * see g_test_rand_int() for details on test case random numbers.
635 * Returns: a number with @range_start <= number < @range_end.
640 g_test_rand_double_range (double range_start,
643 return g_rand_double_range (test_run_rand, range_start, range_end);
647 * g_test_timer_start:
649 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
650 * to be done. Call this function again to restart the timer.
655 g_test_timer_start (void)
657 if (!test_user_timer)
658 test_user_timer = g_timer_new();
660 g_timer_start (test_user_timer);
664 * g_test_timer_elapsed:
666 * Get the time since the last start of the timer with g_test_timer_start().
668 * Returns: the time since the last start of the timer, as a double
673 g_test_timer_elapsed (void)
675 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
676 return test_user_stamp;
682 * Report the last result of g_test_timer_elapsed().
684 * Returns: the last result of g_test_timer_elapsed(), as a double
689 g_test_timer_last (void)
691 return test_user_stamp;
695 * g_test_minimized_result:
696 * @minimized_quantity: the reported value
697 * @format: the format string of the report message
698 * @Varargs: arguments to pass to the printf() function
700 * Report the result of a performance or measurement test.
701 * The test should generally strive to minimize the reported
702 * quantities (smaller values are better than larger ones),
703 * this and @minimized_quantity can determine sorting
704 * order for test result reports.
709 g_test_minimized_result (double minimized_quantity,
713 long double largs = minimized_quantity;
716 va_start (args, format);
717 buffer = g_strdup_vprintf (format, args);
719 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
724 * g_test_maximized_result:
725 * @maximized_quantity: the reported value
726 * @format: the format string of the report message
727 * @Varargs: arguments to pass to the printf() function
729 * Report the result of a performance or measurement test.
730 * The test should generally strive to maximize the reported
731 * quantities (larger values are better than smaller ones),
732 * this and @maximized_quantity can determine sorting
733 * order for test result reports.
738 g_test_maximized_result (double maximized_quantity,
742 long double largs = maximized_quantity;
745 va_start (args, format);
746 buffer = g_strdup_vprintf (format, args);
748 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
754 * @format: the format string
755 * @...: printf-like arguments to @format
757 * Add a message to the test report.
762 g_test_message (const char *format,
767 va_start (args, format);
768 buffer = g_strdup_vprintf (format, args);
770 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
776 * @uri_pattern: the base pattern for bug URIs
778 * Specify the base URI for bug reports.
780 * The base URI is used to construct bug report messages for
781 * g_test_message() when g_test_bug() is called.
782 * Calling this function outside of a test case sets the
783 * default base URI for all test cases. Calling it from within
784 * a test case changes the base URI for the scope of the test
786 * Bug URIs are constructed by appending a bug specific URI
787 * portion to @uri_pattern, or by replacing the special string
788 * '%s' within @uri_pattern if that is present.
793 g_test_bug_base (const char *uri_pattern)
795 g_free (test_uri_base);
796 test_uri_base = g_strdup (uri_pattern);
801 * @bug_uri_snippet: Bug specific bug tracker URI portion.
803 * This function adds a message to test reports that
804 * associates a bug URI with a test case.
805 * Bug URIs are constructed from a base URI set with g_test_bug_base()
806 * and @bug_uri_snippet.
811 g_test_bug (const char *bug_uri_snippet)
814 g_return_if_fail (test_uri_base != NULL);
815 g_return_if_fail (bug_uri_snippet != NULL);
816 c = strstr (test_uri_base, "%s");
819 char *b = g_strndup (test_uri_base, c - test_uri_base);
820 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
822 g_test_message ("Bug Reference: %s", s);
826 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
832 * Get the toplevel test suite for the test path API.
834 * Returns: the toplevel #GTestSuite
839 g_test_get_root (void)
841 if (!test_suite_root)
843 test_suite_root = g_test_create_suite ("root");
844 g_free (test_suite_root->name);
845 test_suite_root->name = g_strdup ("");
847 return test_suite_root;
853 * Runs all tests under the toplevel suite which can be retrieved
854 * with g_test_get_root(). Similar to g_test_run_suite(), the test
855 * cases to be run are filtered according to
856 * test path arguments (-p <replaceable>testpath</replaceable>) as
857 * parsed by g_test_init().
858 * g_test_run_suite() or g_test_run() may only be called once
861 * Returns: 0 on success
868 return g_test_run_suite (g_test_get_root());
872 * g_test_create_case:
873 * @test_name: the name for the test case
874 * @data_size: the size of the fixture data structure
875 * @test_data: test data argument for the test functions
876 * @data_setup: the function to set up the fixture data
877 * @data_test: the actual test function
878 * @data_teardown: the function to teardown the fixture data
880 * Create a new #GTestCase, named @test_name, this API is fairly
881 * low level, calling g_test_add() or g_test_add_func() is preferable.
882 * When this test is executed, a fixture structure of size @data_size
883 * will be allocated and filled with 0s. Then data_setup() is called
884 * to initialize the fixture. After fixture setup, the actual test
885 * function data_test() is called. Once the test run completed, the
886 * fixture structure is torn down by calling data_teardown() and
887 * after that the memory is released.
889 * Splitting up a test run into fixture setup, test function and
890 * fixture teardown is most usful if the same fixture is used for
891 * multiple tests. In this cases, g_test_create_case() will be
892 * called with the same fixture, but varying @test_name and
893 * @data_test arguments.
895 * Returns: a newly allocated #GTestCase.
900 g_test_create_case (const char *test_name,
902 gconstpointer test_data,
903 void (*data_setup) (void),
904 void (*data_test) (void),
905 void (*data_teardown) (void))
908 g_return_val_if_fail (test_name != NULL, NULL);
909 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
910 g_return_val_if_fail (test_name[0] != 0, NULL);
911 g_return_val_if_fail (data_test != NULL, NULL);
912 tc = g_slice_new0 (GTestCase);
913 tc->name = g_strdup (test_name);
914 tc->test_data = (gpointer) test_data;
915 tc->fixture_size = data_size;
916 tc->fixture_setup = (void*) data_setup;
917 tc->fixture_test = (void*) data_test;
918 tc->fixture_teardown = (void*) data_teardown;
923 g_test_add_vtable (const char *testpath,
925 gconstpointer test_data,
926 void (*data_setup) (void),
927 void (*fixture_test_func) (void),
928 void (*data_teardown) (void))
934 g_return_if_fail (testpath != NULL);
935 g_return_if_fail (testpath[0] == '/');
936 g_return_if_fail (fixture_test_func != NULL);
938 suite = g_test_get_root();
939 segments = g_strsplit (testpath, "/", -1);
940 for (ui = 0; segments[ui] != NULL; ui++)
942 const char *seg = segments[ui];
943 gboolean islast = segments[ui + 1] == NULL;
944 if (islast && !seg[0])
945 g_error ("invalid test case path: %s", testpath);
947 continue; /* initial or duplicate slash */
950 GTestSuite *csuite = g_test_create_suite (seg);
951 g_test_suite_add_suite (suite, csuite);
956 GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
957 g_test_suite_add (suite, tc);
960 g_strfreev (segments);
965 * @testpath: Slash-separated test case path name for the test.
966 * @test_func: The test function to invoke for this test.
968 * Create a new test case, similar to g_test_create_case(). However
969 * the test is assumed to use no fixture, and test suites are automatically
970 * created on the fly and added to the root fixture, based on the
971 * slash-separated portions of @testpath.
976 g_test_add_func (const char *testpath,
977 void (*test_func) (void))
979 g_return_if_fail (testpath != NULL);
980 g_return_if_fail (testpath[0] == '/');
981 g_return_if_fail (test_func != NULL);
982 g_test_add_vtable (testpath, 0, NULL, NULL, test_func, NULL);
986 * g_test_add_data_func:
987 * @testpath: Slash-separated test case path name for the test.
988 * @test_data: Test data argument for the test function.
989 * @test_func: The test function to invoke for this test.
991 * Create a new test case, similar to g_test_create_case(). However
992 * the test is assumed to use no fixture, and test suites are automatically
993 * created on the fly and added to the root fixture, based on the
994 * slash-separated portions of @testpath. The @test_data argument
995 * will be passed as first argument to @test_func.
1000 g_test_add_data_func (const char *testpath,
1001 gconstpointer test_data,
1002 void (*test_func) (gconstpointer))
1004 g_return_if_fail (testpath != NULL);
1005 g_return_if_fail (testpath[0] == '/');
1006 g_return_if_fail (test_func != NULL);
1007 g_test_add_vtable (testpath, 0, test_data, NULL, (void(*)(void)) test_func, NULL);
1011 * g_test_create_suite:
1012 * @suite_name: a name for the suite
1014 * Create a new test suite with the name @suite_name.
1016 * Returns: A newly allocated #GTestSuite instance.
1021 g_test_create_suite (const char *suite_name)
1024 g_return_val_if_fail (suite_name != NULL, NULL);
1025 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1026 g_return_val_if_fail (suite_name[0] != 0, NULL);
1027 ts = g_slice_new0 (GTestSuite);
1028 ts->name = g_strdup (suite_name);
1034 * @suite: a #GTestSuite
1035 * @test_case: a #GTestCase
1037 * Adds @test_case to @suite.
1042 g_test_suite_add (GTestSuite *suite,
1043 GTestCase *test_case)
1045 g_return_if_fail (suite != NULL);
1046 g_return_if_fail (test_case != NULL);
1047 suite->cases = g_slist_prepend (suite->cases, test_case);
1051 * g_test_suite_add_suite:
1052 * @suite: a #GTestSuite
1053 * @nestedsuite: another #GTestSuite
1055 * Adds @nestedsuite to @suite.
1060 g_test_suite_add_suite (GTestSuite *suite,
1061 GTestSuite *nestedsuite)
1063 g_return_if_fail (suite != NULL);
1064 g_return_if_fail (nestedsuite != NULL);
1065 suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1069 * g_test_queue_free:
1070 * @gfree_pointer: the pointer to be stored.
1072 * Enqueue a pointer to be released with g_free() during the next
1073 * teardown phase. This is equivalent to calling g_test_queue_destroy()
1074 * with a destroy callback of g_free().
1079 g_test_queue_free (gpointer gfree_pointer)
1082 g_test_queue_destroy (g_free, gfree_pointer);
1086 * g_test_queue_destroy:
1087 * @destroy_func: Destroy callback for teardown phase.
1088 * @destroy_data: Destroy callback data.
1090 * This function enqueus a callback @destroy_func() to be executed
1091 * during the next test case teardown phase. This is most useful
1092 * to auto destruct allocted test resources at the end of a test run.
1093 * Resources are released in reverse queue order, that means enqueueing
1094 * callback A before callback B will cause B() to be called before
1095 * A() during teardown.
1100 g_test_queue_destroy (GDestroyNotify destroy_func,
1101 gpointer destroy_data)
1103 DestroyEntry *dentry;
1104 g_return_if_fail (destroy_func != NULL);
1105 dentry = g_slice_new0 (DestroyEntry);
1106 dentry->destroy_func = destroy_func;
1107 dentry->destroy_data = destroy_data;
1108 dentry->next = test_destroy_queue;
1109 test_destroy_queue = dentry;
1113 test_case_run (GTestCase *tc)
1115 gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1116 test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1117 if (++test_run_count <= test_skip_count)
1118 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1119 else if (test_run_list)
1121 g_print ("%s\n", test_run_name);
1122 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1126 GTimer *test_run_timer = g_timer_new();
1127 long double largs[3];
1129 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1131 g_test_log_set_fatal_handler (NULL, NULL);
1132 g_timer_start (test_run_timer);
1133 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1134 test_run_seed (test_run_seedstr);
1135 if (tc->fixture_setup)
1136 tc->fixture_setup (fixture, tc->test_data);
1137 tc->fixture_test (fixture, tc->test_data);
1139 while (test_destroy_queue)
1141 DestroyEntry *dentry = test_destroy_queue;
1142 test_destroy_queue = dentry->next;
1143 dentry->destroy_func (dentry->destroy_data);
1144 g_slice_free (DestroyEntry, dentry);
1146 if (tc->fixture_teardown)
1147 tc->fixture_teardown (fixture, tc->test_data);
1148 if (tc->fixture_size)
1150 g_timer_stop (test_run_timer);
1151 largs[0] = 0; /* OK */
1152 largs[1] = test_run_forks;
1153 largs[2] = g_timer_elapsed (test_run_timer, NULL);
1154 g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1155 g_timer_destroy (test_run_timer);
1157 g_free (test_run_name);
1158 test_run_name = old_name;
1159 g_free (test_uri_base);
1160 test_uri_base = old_base;
1165 g_test_run_suite_internal (GTestSuite *suite,
1168 guint n_bad = 0, n_good = 0, bad_suite = 0, l;
1169 gchar *rest, *old_name = test_run_name;
1170 GSList *slist, *reversed;
1171 g_return_val_if_fail (suite != NULL, -1);
1172 while (path[0] == '/')
1175 rest = strchr (path, '/');
1176 l = rest ? MIN (l, rest - path) : l;
1177 test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1178 reversed = g_slist_reverse (g_slist_copy (suite->cases));
1179 for (slist = reversed; slist; slist = slist->next)
1181 GTestCase *tc = slist->data;
1182 guint n = l ? strlen (tc->name) : 0;
1183 if (l == n && strncmp (path, tc->name, n) == 0)
1186 n_bad += test_case_run (tc) != 0;
1189 g_slist_free (reversed);
1190 reversed = g_slist_reverse (g_slist_copy (suite->suites));
1191 for (slist = reversed; slist; slist = slist->next)
1193 GTestSuite *ts = slist->data;
1194 guint n = l ? strlen (ts->name) : 0;
1195 if (l == n && strncmp (path, ts->name, n) == 0)
1196 bad_suite += g_test_run_suite_internal (ts, rest ? rest : "") != 0;
1198 g_slist_free (reversed);
1199 g_free (test_run_name);
1200 test_run_name = old_name;
1201 return n_bad || bad_suite;
1206 * @suite: a #GTestSuite
1208 * Execute the tests within @suite and all nested #GTestSuites.
1209 * The test suites to be executed are filtered according to
1210 * test path arguments (-p <replaceable>testpath</replaceable>)
1211 * as parsed by g_test_init().
1212 * g_test_run_suite() or g_test_run() may only be called once
1215 * Returns: 0 on success
1220 g_test_run_suite (GTestSuite *suite)
1223 g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1224 g_return_val_if_fail (g_test_run_once == TRUE, -1);
1225 g_test_run_once = FALSE;
1227 test_paths = g_slist_prepend (test_paths, "");
1230 const char *rest, *path = test_paths->data;
1231 guint l, n = strlen (suite->name);
1232 test_paths = g_slist_delete_link (test_paths, test_paths);
1233 while (path[0] == '/')
1235 if (!n) /* root suite, run unconditionally */
1237 n_bad += 0 != g_test_run_suite_internal (suite, path);
1240 /* regular suite, match path */
1241 rest = strchr (path, '/');
1243 l = rest ? MIN (l, rest - path) : l;
1244 if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1245 n_bad += 0 != g_test_run_suite_internal (suite, rest ? rest : "");
1251 gtest_default_log_handler (const gchar *log_domain,
1252 GLogLevelFlags log_level,
1253 const gchar *message,
1254 gpointer unused_data)
1256 const gchar *strv[16];
1261 strv[i++] = log_domain;
1264 if (log_level & G_LOG_FLAG_FATAL)
1265 strv[i++] = "FATAL-";
1266 if (log_level & G_LOG_FLAG_RECURSION)
1267 strv[i++] = "RECURSIVE-";
1268 if (log_level & G_LOG_LEVEL_ERROR)
1269 strv[i++] = "ERROR";
1270 if (log_level & G_LOG_LEVEL_CRITICAL)
1271 strv[i++] = "CRITICAL";
1272 if (log_level & G_LOG_LEVEL_WARNING)
1273 strv[i++] = "WARNING";
1274 if (log_level & G_LOG_LEVEL_MESSAGE)
1275 strv[i++] = "MESSAGE";
1276 if (log_level & G_LOG_LEVEL_INFO)
1278 if (log_level & G_LOG_LEVEL_DEBUG)
1279 strv[i++] = "DEBUG";
1281 strv[i++] = message;
1283 msg = g_strjoinv ("", (gchar**) strv);
1284 g_test_log (G_TEST_LOG_ERROR, msg, NULL, 0, NULL);
1285 g_log_default_handler (log_domain, log_level, message, unused_data);
1290 g_assertion_message (const char *domain,
1294 const char *message)
1299 message = "code should not be reached";
1300 g_snprintf (lstr, 32, "%d", line);
1301 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1302 "ERROR:", file, ":", lstr, ":",
1303 func, func[0] ? ":" : "",
1304 " ", message, NULL);
1305 g_printerr ("**\n%s\n", s);
1307 /* store assertion message in global variable, so that it can be found in a
1309 if (__glib_assert_msg != NULL)
1310 /* free the old one */
1311 free (__glib_assert_msg);
1312 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
1313 strcpy (__glib_assert_msg, s);
1315 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
1321 g_assertion_message_expr (const char *domain,
1327 char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1328 g_assertion_message (domain, file, line, func, s);
1333 g_assertion_message_cmpnum (const char *domain,
1346 case 'i': s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
1347 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;
1348 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
1349 /* ideally use: floats=%.7g double=%.17g */
1351 g_assertion_message (domain, file, line, func, s);
1356 g_assertion_message_cmpstr (const char *domain,
1365 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1366 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1367 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1370 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1373 g_assertion_message (domain, file, line, func, s);
1378 g_assertion_message_error (const char *domain,
1384 GQuark error_domain,
1389 /* This is used by both g_assert_error() and g_assert_no_error(), so there
1390 * are three cases: expected an error but got the wrong error, expected
1391 * an error but got no error, and expected no error but got an error.
1394 gstring = g_string_new ("assertion failed ");
1396 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
1397 g_quark_to_string (error_domain), error_code);
1399 g_string_append_printf (gstring, "(%s == NULL): ", expr);
1402 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
1403 g_quark_to_string (error->domain), error->code);
1405 g_string_append_printf (gstring, "%s is NULL", expr);
1407 g_assertion_message (domain, file, line, func, gstring->str);
1408 g_string_free (gstring, TRUE);
1413 * @str1: a C string or %NULL
1414 * @str2: another C string or %NULL
1416 * Compares @str1 and @str2 like strcmp(). Handles %NULL
1417 * gracefully by sorting it before non-%NULL strings.
1419 * Returns: -1, 0 or 1, if @str1 is <, == or > than @str2.
1424 g_strcmp0 (const char *str1,
1428 return -(str1 != str2);
1430 return str1 != str2;
1431 return strcmp (str1, str2);
1435 static int /* 0 on success */
1436 kill_child (int pid,
1441 if (patience >= 3) /* try graceful reap */
1443 if (waitpid (pid, status, WNOHANG) > 0)
1446 if (patience >= 2) /* try SIGHUP */
1449 if (waitpid (pid, status, WNOHANG) > 0)
1451 g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1452 if (waitpid (pid, status, WNOHANG) > 0)
1454 g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
1455 if (waitpid (pid, status, WNOHANG) > 0)
1457 g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
1458 if (waitpid (pid, status, WNOHANG) > 0)
1461 if (patience >= 1) /* try SIGTERM */
1463 kill (pid, SIGTERM);
1464 if (waitpid (pid, status, WNOHANG) > 0)
1466 g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
1467 if (waitpid (pid, status, WNOHANG) > 0)
1469 g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
1470 if (waitpid (pid, status, WNOHANG) > 0)
1474 kill (pid, SIGKILL);
1476 wr = waitpid (pid, status, 0);
1477 while (wr < 0 && errno == EINTR);
1483 g_string_must_read (GString *gstring,
1486 #define STRING_BUFFER_SIZE 4096
1487 char buf[STRING_BUFFER_SIZE];
1490 bytes = read (fd, buf, sizeof (buf));
1492 return 0; /* EOF, calling this function assumes data is available */
1495 g_string_append_len (gstring, buf, bytes);
1498 else if (bytes < 0 && errno == EINTR)
1500 else /* bytes < 0 */
1502 g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1503 return 1; /* ignore error after warning */
1508 g_string_write_out (GString *gstring,
1512 if (*stringpos < gstring->len)
1516 r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
1517 while (r < 0 && errno == EINTR);
1518 *stringpos += MAX (r, 0);
1523 test_trap_clear (void)
1525 test_trap_last_status = 0;
1526 test_trap_last_pid = 0;
1527 g_free (test_trap_last_stdout);
1528 test_trap_last_stdout = NULL;
1529 g_free (test_trap_last_stderr);
1530 test_trap_last_stderr = NULL;
1541 ret = dup2 (fd1, fd2);
1542 while (ret < 0 && errno == EINTR);
1547 test_time_stamp (void)
1551 g_get_current_time (&tv);
1553 stamp = stamp * 1000000 + tv.tv_usec;
1561 * @usec_timeout: Timeout for the forked test in micro seconds.
1562 * @test_trap_flags: Flags to modify forking behaviour.
1564 * Fork the current test program to execute a test case that might
1565 * not return or that might abort. The forked test case is aborted
1566 * and considered failing if its run time exceeds @usec_timeout.
1568 * The forking behavior can be configured with the #GTestTrapFlags flags.
1570 * In the following example, the test code forks, the forked child
1571 * process produces some sample output and exits successfully.
1572 * The forking parent process then asserts successful child program
1573 * termination and validates child program outputs.
1577 * test_fork_patterns (void)
1579 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
1581 * g_print ("some stdout text: somagic17\n");
1582 * g_printerr ("some stderr text: semagic43\n");
1583 * exit (0); /* successful test run */
1585 * g_test_trap_assert_passed();
1586 * g_test_trap_assert_stdout ("*somagic17*");
1587 * g_test_trap_assert_stderr ("*semagic43*");
1591 * This function is implemented only on Unix platforms.
1593 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
1598 g_test_trap_fork (guint64 usec_timeout,
1599 GTestTrapFlags test_trap_flags)
1602 gboolean pass_on_forked_log = FALSE;
1603 int stdout_pipe[2] = { -1, -1 };
1604 int stderr_pipe[2] = { -1, -1 };
1605 int stdtst_pipe[2] = { -1, -1 };
1607 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
1608 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
1609 signal (SIGCHLD, SIG_DFL);
1610 test_trap_last_pid = fork ();
1611 if (test_trap_last_pid < 0)
1612 g_error ("failed to fork test program: %s", g_strerror (errno));
1613 if (test_trap_last_pid == 0) /* child */
1616 close (stdout_pipe[0]);
1617 close (stderr_pipe[0]);
1618 close (stdtst_pipe[0]);
1619 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
1620 fd0 = open ("/dev/null", O_RDONLY);
1621 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
1622 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
1625 if (stdout_pipe[1] >= 3)
1626 close (stdout_pipe[1]);
1627 if (stderr_pipe[1] >= 3)
1628 close (stderr_pipe[1]);
1629 test_log_fd = stdtst_pipe[1];
1634 GString *sout = g_string_new (NULL);
1635 GString *serr = g_string_new (NULL);
1637 int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
1639 close (stdout_pipe[1]);
1640 close (stderr_pipe[1]);
1641 close (stdtst_pipe[1]);
1642 sstamp = test_time_stamp();
1643 /* read data until we get EOF on all pipes */
1644 while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
1650 if (stdout_pipe[0] >= 0)
1651 FD_SET (stdout_pipe[0], &fds);
1652 if (stderr_pipe[0] >= 0)
1653 FD_SET (stderr_pipe[0], &fds);
1654 if (stdtst_pipe[0] >= 0)
1655 FD_SET (stdtst_pipe[0], &fds);
1657 tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
1658 ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
1659 if (ret < 0 && errno != EINTR)
1661 g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1664 if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
1665 g_string_must_read (sout, stdout_pipe[0]) == 0)
1667 close (stdout_pipe[0]);
1668 stdout_pipe[0] = -1;
1670 if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
1671 g_string_must_read (serr, stderr_pipe[0]) == 0)
1673 close (stderr_pipe[0]);
1674 stderr_pipe[0] = -1;
1676 if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
1678 guint8 buffer[4096];
1679 gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
1680 if (r > 0 && test_log_fd > 0)
1682 l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
1683 while (l < 0 && errno == EINTR);
1684 if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
1686 close (stdtst_pipe[0]);
1687 stdtst_pipe[0] = -1;
1690 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
1691 g_string_write_out (sout, 1, &soutpos);
1692 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
1693 g_string_write_out (serr, 2, &serrpos);
1696 guint64 nstamp = test_time_stamp();
1698 sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
1699 if (usec_timeout < nstamp - sstamp)
1701 /* timeout reached, need to abort the child now */
1702 kill_child (test_trap_last_pid, &status, 3);
1703 test_trap_last_status = 1024; /* timeout */
1704 if (0 && WIFSIGNALED (status))
1705 g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
1711 close (stdout_pipe[0]);
1712 close (stderr_pipe[0]);
1713 close (stdtst_pipe[0]);
1718 wr = waitpid (test_trap_last_pid, &status, 0);
1719 while (wr < 0 && errno == EINTR);
1720 if (WIFEXITED (status)) /* normal exit */
1721 test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
1722 else if (WIFSIGNALED (status))
1723 test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
1724 else /* WCOREDUMP (status) */
1725 test_trap_last_status = 512; /* coredump */
1727 test_trap_last_stdout = g_string_free (sout, FALSE);
1728 test_trap_last_stderr = g_string_free (serr, FALSE);
1732 g_message ("Not implemented: g_test_trap_fork");
1739 * g_test_trap_has_passed:
1741 * Check the result of the last g_test_trap_fork() call.
1743 * Returns: %TRUE if the last forked child terminated successfully.
1748 g_test_trap_has_passed (void)
1750 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
1754 * g_test_trap_reached_timeout:
1756 * Check the result of the last g_test_trap_fork() call.
1758 * Returns: %TRUE if the last forked child got killed due to a fork timeout.
1763 g_test_trap_reached_timeout (void)
1765 return 0 != (test_trap_last_status & 1024); /* timeout flag */
1769 g_test_trap_assertions (const char *domain,
1773 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
1774 const char *pattern)
1777 gboolean must_pass = assertion_flags == 0;
1778 gboolean must_fail = assertion_flags == 1;
1779 gboolean match_result = 0 == (assertion_flags & 1);
1780 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
1781 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
1782 const char *match_error = match_result ? "failed to match" : "contains invalid match";
1783 if (test_trap_last_pid == 0)
1784 g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
1785 if (must_pass && !g_test_trap_has_passed())
1787 char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
1788 g_assertion_message (domain, file, line, func, msg);
1791 if (must_fail && g_test_trap_has_passed())
1793 char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
1794 g_assertion_message (domain, file, line, func, msg);
1797 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
1799 char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
1800 g_assertion_message (domain, file, line, func, msg);
1803 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
1805 char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
1806 g_assertion_message (domain, file, line, func, msg);
1813 gstring_overwrite_int (GString *gstring,
1817 vuint = g_htonl (vuint);
1818 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
1822 gstring_append_int (GString *gstring,
1825 vuint = g_htonl (vuint);
1826 g_string_append_len (gstring, (const gchar*) &vuint, 4);
1830 gstring_append_double (GString *gstring,
1833 union { double vdouble; guint64 vuint64; } u;
1834 u.vdouble = vdouble;
1835 u.vuint64 = GUINT64_TO_BE (u.vuint64);
1836 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
1840 g_test_log_dump (GTestLogMsg *msg,
1843 GString *gstring = g_string_sized_new (1024);
1845 gstring_append_int (gstring, 0); /* message length */
1846 gstring_append_int (gstring, msg->log_type);
1847 gstring_append_int (gstring, msg->n_strings);
1848 gstring_append_int (gstring, msg->n_nums);
1849 gstring_append_int (gstring, 0); /* reserved */
1850 for (ui = 0; ui < msg->n_strings; ui++)
1852 guint l = strlen (msg->strings[ui]);
1853 gstring_append_int (gstring, l);
1854 g_string_append_len (gstring, msg->strings[ui], l);
1856 for (ui = 0; ui < msg->n_nums; ui++)
1857 gstring_append_double (gstring, msg->nums[ui]);
1858 *len = gstring->len;
1859 gstring_overwrite_int (gstring, 0, *len); /* message length */
1860 return (guint8*) g_string_free (gstring, FALSE);
1863 static inline long double
1864 net_double (const gchar **ipointer)
1866 union { guint64 vuint64; double vdouble; } u;
1867 guint64 aligned_int64;
1868 memcpy (&aligned_int64, *ipointer, 8);
1870 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
1874 static inline guint32
1875 net_int (const gchar **ipointer)
1877 guint32 aligned_int;
1878 memcpy (&aligned_int, *ipointer, 4);
1880 return g_ntohl (aligned_int);
1884 g_test_log_extract (GTestLogBuffer *tbuffer)
1886 const gchar *p = tbuffer->data->str;
1889 if (tbuffer->data->len < 4 * 5)
1891 mlength = net_int (&p);
1892 if (tbuffer->data->len < mlength)
1894 msg.log_type = net_int (&p);
1895 msg.n_strings = net_int (&p);
1896 msg.n_nums = net_int (&p);
1897 if (net_int (&p) == 0)
1900 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
1901 msg.nums = g_new0 (long double, msg.n_nums);
1902 for (ui = 0; ui < msg.n_strings; ui++)
1904 guint sl = net_int (&p);
1905 msg.strings[ui] = g_strndup (p, sl);
1908 for (ui = 0; ui < msg.n_nums; ui++)
1909 msg.nums[ui] = net_double (&p);
1910 if (p <= tbuffer->data->str + mlength)
1912 g_string_erase (tbuffer->data, 0, mlength);
1913 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
1918 g_strfreev (msg.strings);
1919 g_error ("corrupt log stream from test program");
1924 * g_test_log_buffer_new:
1926 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1929 g_test_log_buffer_new (void)
1931 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
1932 tb->data = g_string_sized_new (1024);
1937 * g_test_log_buffer_free
1939 * Internal function for gtester to free test log messages, no ABI guarantees provided.
1942 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
1944 g_return_if_fail (tbuffer != NULL);
1945 while (tbuffer->msgs)
1946 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
1947 g_string_free (tbuffer->data, TRUE);
1952 * g_test_log_buffer_push
1954 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1957 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
1959 const guint8 *bytes)
1961 g_return_if_fail (tbuffer != NULL);
1964 gboolean more_messages;
1965 g_return_if_fail (bytes != NULL);
1966 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
1968 more_messages = g_test_log_extract (tbuffer);
1969 while (more_messages);
1974 * g_test_log_buffer_pop:
1976 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
1979 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
1981 GTestLogMsg *msg = NULL;
1982 g_return_val_if_fail (tbuffer != NULL, NULL);
1985 GSList *slist = g_slist_last (tbuffer->msgs);
1987 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
1993 * g_test_log_msg_free:
1995 * Internal function for gtester to free test log messages, no ABI guarantees provided.
1998 g_test_log_msg_free (GTestLogMsg *tmsg)
2000 g_return_if_fail (tmsg != NULL);
2001 g_strfreev (tmsg->strings);
2002 g_free (tmsg->nums);
2006 /* --- macros docs START --- */
2009 * @testpath: The test path for a new test case.
2010 * @Fixture: The type of a fixture data structure.
2011 * @tdata: Data argument for the test functions.
2012 * @fsetup: The function to set up the fixture data.
2013 * @ftest: The actual test function.
2014 * @fteardown: The function to tear down the fixture data.
2016 * Hook up a new test case at @testpath, similar to g_test_add_func().
2017 * A fixture data structure with setup and teardown function may be provided
2018 * though, similar to g_test_create_case().
2019 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2020 * fteardown() callbacks can expect a @Fixture pointer as first argument in
2021 * a type safe manner.
2025 /* --- macros docs END --- */
2027 #define __G_TEST_UTILS_C__
2028 #include "galiasdef.c"