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"
24 #include <sys/types.h>
41 #ifdef HAVE_SYS_SELECT_H
42 #include <sys/select.h>
43 #endif /* HAVE_SYS_SELECT_H */
45 /* Global variable for storing assertion messages; this is the counterpart to
46 * glibc's (private) __abort_msg variable, and allows developers and crash
47 * analysis systems like Apport and ABRT to fish out assertion messages from
48 * core dumps, instead of having to catch them on screen output. */
49 char *__glib_assert_msg = NULL;
51 /* --- structures --- */
56 void (*fixture_setup) (void*, gconstpointer);
57 void (*fixture_test) (void*, gconstpointer);
58 void (*fixture_teardown) (void*, gconstpointer);
67 typedef struct DestroyEntry DestroyEntry;
71 GDestroyNotify destroy_func;
72 gpointer destroy_data;
75 /* --- prototypes --- */
76 static void test_run_seed (const gchar *rseed);
77 static void test_trap_clear (void);
78 static guint8* g_test_log_dump (GTestLogMsg *msg,
80 static void gtest_default_log_handler (const gchar *log_domain,
81 GLogLevelFlags log_level,
83 gpointer unused_data);
86 /* --- variables --- */
87 static int test_log_fd = -1;
88 static gboolean test_mode_fatal = TRUE;
89 static gboolean g_test_run_once = TRUE;
90 static gboolean test_run_list = FALSE;
91 static gchar *test_run_seedstr = NULL;
92 static GRand *test_run_rand = NULL;
93 static gchar *test_run_name = "";
94 static guint test_run_forks = 0;
95 static guint test_run_count = 0;
96 static guint test_skip_count = 0;
97 static GTimer *test_user_timer = NULL;
98 static double test_user_stamp = 0;
99 static GSList *test_paths = NULL;
100 static GTestSuite *test_suite_root = NULL;
101 static int test_trap_last_status = 0;
102 static int test_trap_last_pid = 0;
103 static char *test_trap_last_stdout = NULL;
104 static char *test_trap_last_stderr = NULL;
105 static char *test_uri_base = NULL;
106 static gboolean test_debug_log = FALSE;
107 static DestroyEntry *test_destroy_queue = NULL;
108 static GTestConfig mutable_test_config_vars = {
109 FALSE, /* test_initialized */
110 TRUE, /* test_quick */
111 FALSE, /* test_perf */
112 FALSE, /* test_verbose */
113 FALSE, /* test_quiet */
115 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
117 /* --- functions --- */
119 g_test_log_type_name (GTestLogType log_type)
123 case G_TEST_LOG_NONE: return "none";
124 case G_TEST_LOG_ERROR: return "error";
125 case G_TEST_LOG_START_BINARY: return "binary";
126 case G_TEST_LOG_LIST_CASE: return "list";
127 case G_TEST_LOG_SKIP_CASE: return "skip";
128 case G_TEST_LOG_START_CASE: return "start";
129 case G_TEST_LOG_STOP_CASE: return "stop";
130 case G_TEST_LOG_MIN_RESULT: return "minperf";
131 case G_TEST_LOG_MAX_RESULT: return "maxperf";
132 case G_TEST_LOG_MESSAGE: return "message";
138 g_test_log_send (guint n_bytes,
139 const guint8 *buffer)
141 if (test_log_fd >= 0)
145 r = write (test_log_fd, buffer, n_bytes);
146 while (r < 0 && errno == EINTR);
150 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
153 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
154 msg = g_test_log_buffer_pop (lbuffer);
155 g_warn_if_fail (msg != NULL);
156 g_warn_if_fail (lbuffer->data->len == 0);
157 g_test_log_buffer_free (lbuffer);
159 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
160 for (ui = 0; ui < msg->n_strings; ui++)
161 g_printerr (":{%s}", msg->strings[ui]);
165 for (ui = 0; ui < msg->n_nums; ui++)
166 g_printerr ("%s%.16Lg", ui ? ";" : "", msg->nums[ui]);
169 g_printerr (":LOG*}\n");
170 g_test_log_msg_free (msg);
175 g_test_log (GTestLogType lbit,
176 const gchar *string1,
177 const gchar *string2,
181 gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
183 gchar *astrings[3] = { NULL, NULL, NULL };
189 case G_TEST_LOG_START_BINARY:
190 if (g_test_verbose())
191 g_print ("GTest: random seed: %s\n", string2);
193 case G_TEST_LOG_STOP_CASE:
194 if (g_test_verbose())
195 g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
196 else if (!g_test_quiet())
197 g_print ("%s\n", fail ? "FAIL" : "OK");
198 if (fail && test_mode_fatal)
201 case G_TEST_LOG_MIN_RESULT:
202 if (g_test_verbose())
203 g_print ("(MINPERF:%s)\n", string1);
205 case G_TEST_LOG_MAX_RESULT:
206 if (g_test_verbose())
207 g_print ("(MAXPERF:%s)\n", string1);
209 case G_TEST_LOG_MESSAGE:
210 if (g_test_verbose())
211 g_print ("(MSG: %s)\n", string1);
217 msg.n_strings = (string1 != NULL) + (string1 && string2);
218 msg.strings = astrings;
219 astrings[0] = (gchar*) string1;
220 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
223 dbuffer = g_test_log_dump (&msg, &dbufferlen);
224 g_test_log_send (dbufferlen, dbuffer);
229 case G_TEST_LOG_START_CASE:
230 if (g_test_verbose())
231 g_print ("GTest: run: %s\n", string1);
232 else if (!g_test_quiet())
233 g_print ("%s: ", string1);
239 /* We intentionally parse the command line without GOptionContext
240 * because otherwise you would never be able to test it.
243 parse_args (gint *argc_p,
246 guint argc = *argc_p;
247 gchar **argv = *argv_p;
249 /* parse known args */
250 for (i = 1; i < argc; i++)
252 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
254 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
255 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
256 g_log_set_always_fatal (fatal_mask);
259 else if (strcmp (argv[i], "--keep-going") == 0 ||
260 strcmp (argv[i], "-k") == 0)
262 test_mode_fatal = FALSE;
265 else if (strcmp (argv[i], "--debug-log") == 0)
267 test_debug_log = TRUE;
270 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
272 gchar *equal = argv[i] + 12;
274 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
275 else if (i + 1 < argc)
278 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
282 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
284 gchar *equal = argv[i] + 16;
286 test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
287 else if (i + 1 < argc)
290 test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
294 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
296 gchar *equal = argv[i] + 2;
298 test_paths = g_slist_prepend (test_paths, equal + 1);
299 else if (i + 1 < argc)
302 test_paths = g_slist_prepend (test_paths, argv[i]);
306 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
308 gchar *equal = argv[i] + 2;
309 const gchar *mode = "";
312 else if (i + 1 < argc)
317 if (strcmp (mode, "perf") == 0)
318 mutable_test_config_vars.test_perf = TRUE;
319 else if (strcmp (mode, "slow") == 0)
320 mutable_test_config_vars.test_quick = FALSE;
321 else if (strcmp (mode, "thorough") == 0)
322 mutable_test_config_vars.test_quick = FALSE;
323 else if (strcmp (mode, "quick") == 0)
325 mutable_test_config_vars.test_quick = TRUE;
326 mutable_test_config_vars.test_perf = FALSE;
329 g_error ("unknown test mode: -m %s", mode);
332 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
334 mutable_test_config_vars.test_quiet = TRUE;
335 mutable_test_config_vars.test_verbose = FALSE;
338 else if (strcmp ("--verbose", argv[i]) == 0)
340 mutable_test_config_vars.test_quiet = FALSE;
341 mutable_test_config_vars.test_verbose = TRUE;
344 else if (strcmp ("-l", argv[i]) == 0)
346 test_run_list = TRUE;
349 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
351 gchar *equal = argv[i] + 6;
353 test_run_seedstr = equal + 1;
354 else if (i + 1 < argc)
357 test_run_seedstr = argv[i];
361 else if (strcmp ("-?", argv[i]) == 0 || strcmp ("--help", argv[i]) == 0)
364 " %s [OPTION...]\n\n"
366 " -?, --help Show help options\n"
368 " -l List test cases available in a test executable\n"
369 " -seed=RANDOMSEED Provide a random seed to reproduce test\n"
370 " runs using random numbers\n"
371 " --verbose Run tests verbosely\n"
372 " -q, --quiet Run tests quietly\n"
373 " -p TESTPATH execute all tests matching TESTPATH\n"
374 " -m {perf|slow|thorough|quick} Execute tests according modes\n"
375 " --debug-log debug test logging output\n"
376 " -k, --keep-going gtester-specific argument\n"
377 " --GTestLogFD=N gtester-specific argument\n"
378 " --GTestSkipCount=N gtester-specific argument\n",
385 for (i = 1; i < argc; i++)
397 * @argc: Address of the @argc parameter of the main() function.
398 * Changed if any arguments were handled.
399 * @argv: Address of the @argv parameter of main().
400 * Any parameters understood by g_test_init() stripped before return.
401 * @Varargs: Reserved for future extension. Currently, you must pass %NULL.
403 * Initialize the GLib testing framework, e.g. by seeding the
404 * test random number generator, the name for g_get_prgname()
405 * and parsing test related command line args.
406 * So far, the following arguments are understood:
409 * <term><option>-l</option></term>
411 * list test cases available in a test executable.
415 * <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
417 * provide a random seed to reproduce test runs using random numbers.
421 * <term><option>--verbose</option></term>
422 * <listitem><para>run tests verbosely.</para></listitem>
425 * <term><option>-q</option>, <option>--quiet</option></term>
426 * <listitem><para>run tests quietly.</para></listitem>
429 * <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
431 * execute all tests matching <replaceable>TESTPATH</replaceable>.
435 * <term><option>-m {perf|slow|thorough|quick}</option></term>
437 * execute tests according to these test modes:
442 * performance tests, may take long and report results.
446 * <term>slow, thorough</term>
448 * slow and thorough tests, may take quite long and
455 * quick tests, should run really quickly and give good coverage.
462 * <term><option>--debug-log</option></term>
463 * <listitem><para>debug test logging output.</para></listitem>
466 * <term><option>-k</option>, <option>--keep-going</option></term>
467 * <listitem><para>gtester-specific argument.</para></listitem>
470 * <term><option>--GTestLogFD <replaceable>N</replaceable></option></term>
471 * <listitem><para>gtester-specific argument.</para></listitem>
474 * <term><option>--GTestSkipCount <replaceable>N</replaceable></option></term>
475 * <listitem><para>gtester-specific argument.</para></listitem>
482 g_test_init (int *argc,
486 static char seedstr[4 + 4 * 8 + 1];
489 /* make warnings and criticals fatal for all test programs */
490 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
491 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
492 g_log_set_always_fatal (fatal_mask);
493 /* check caller args */
494 g_return_if_fail (argc != NULL);
495 g_return_if_fail (argv != NULL);
496 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
497 mutable_test_config_vars.test_initialized = TRUE;
499 va_start (args, argv);
500 vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
502 g_return_if_fail (vararg1 == NULL);
504 /* setup random seed string */
505 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
506 test_run_seedstr = seedstr;
508 /* parse args, sets up mode, changes seed, etc. */
509 parse_args (argc, argv);
510 if (!g_get_prgname())
511 g_set_prgname ((*argv)[0]);
513 /* verify GRand reliability, needed for reliable seeds */
516 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
517 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
518 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
519 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
520 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
524 /* check rand seed */
525 test_run_seed (test_run_seedstr);
527 /* report program start */
528 g_log_set_default_handler (gtest_default_log_handler, NULL);
529 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
533 test_run_seed (const gchar *rseed)
535 guint seed_failed = 0;
537 g_rand_free (test_run_rand);
538 test_run_rand = NULL;
539 while (strchr (" \t\v\r\n\f", *rseed))
541 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
543 const char *s = rseed + 4;
544 if (strlen (s) >= 32) /* require 4 * 8 chars */
546 guint32 seedarray[4];
547 gchar *p, hexbuf[9] = { 0, };
548 memcpy (hexbuf, s + 0, 8);
549 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
550 seed_failed += p != NULL && *p != 0;
551 memcpy (hexbuf, s + 8, 8);
552 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
553 seed_failed += p != NULL && *p != 0;
554 memcpy (hexbuf, s + 16, 8);
555 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
556 seed_failed += p != NULL && *p != 0;
557 memcpy (hexbuf, s + 24, 8);
558 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
559 seed_failed += p != NULL && *p != 0;
562 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
567 g_error ("Unknown or invalid random seed: %s", rseed);
573 * Get a reproducible random integer number.
575 * The random numbers generated by the g_test_rand_*() family of functions
576 * change with every new test program start, unless the --seed option is
577 * given when starting test programs.
579 * For individual test cases however, the random number generator is
580 * reseeded, to avoid dependencies between tests and to make --seed
581 * effective for all test cases.
583 * Returns: a random number from the seeded random number generator.
588 g_test_rand_int (void)
590 return g_rand_int (test_run_rand);
594 * g_test_rand_int_range:
595 * @begin: the minimum value returned by this function
596 * @end: the smallest value not to be returned by this function
598 * Get a reproducible random integer number out of a specified range,
599 * see g_test_rand_int() for details on test case random numbers.
601 * Returns: a number with @begin <= number < @end.
606 g_test_rand_int_range (gint32 begin,
609 return g_rand_int_range (test_run_rand, begin, end);
613 * g_test_rand_double:
615 * Get a reproducible random floating point number,
616 * see g_test_rand_int() for details on test case random numbers.
618 * Returns: a random number from the seeded random number generator.
623 g_test_rand_double (void)
625 return g_rand_double (test_run_rand);
629 * g_test_rand_double_range:
630 * @range_start: the minimum value returned by this function
631 * @range_end: the minimum value not returned by this function
633 * Get a reproducible random floating pointer number out of a specified range,
634 * see g_test_rand_int() for details on test case random numbers.
636 * Returns: a number with @range_start <= number < @range_end.
641 g_test_rand_double_range (double range_start,
644 return g_rand_double_range (test_run_rand, range_start, range_end);
648 * g_test_timer_start:
650 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
651 * to be done. Call this function again to restart the timer.
656 g_test_timer_start (void)
658 if (!test_user_timer)
659 test_user_timer = g_timer_new();
661 g_timer_start (test_user_timer);
665 * g_test_timer_elapsed:
667 * Get the time since the last start of the timer with g_test_timer_start().
669 * Returns: the time since the last start of the timer, as a double
674 g_test_timer_elapsed (void)
676 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
677 return test_user_stamp;
683 * Report the last result of g_test_timer_elapsed().
685 * Returns: the last result of g_test_timer_elapsed(), as a double
690 g_test_timer_last (void)
692 return test_user_stamp;
696 * g_test_minimized_result:
697 * @minimized_quantity: the reported value
698 * @format: the format string of the report message
699 * @Varargs: arguments to pass to the printf() function
701 * Report the result of a performance or measurement test.
702 * The test should generally strive to minimize the reported
703 * quantities (smaller values are better than larger ones),
704 * this and @minimized_quantity can determine sorting
705 * order for test result reports.
710 g_test_minimized_result (double minimized_quantity,
714 long double largs = minimized_quantity;
717 va_start (args, format);
718 buffer = g_strdup_vprintf (format, args);
720 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
725 * g_test_maximized_result:
726 * @maximized_quantity: the reported value
727 * @format: the format string of the report message
728 * @Varargs: arguments to pass to the printf() function
730 * Report the result of a performance or measurement test.
731 * The test should generally strive to maximize the reported
732 * quantities (larger values are better than smaller ones),
733 * this and @maximized_quantity can determine sorting
734 * order for test result reports.
739 g_test_maximized_result (double maximized_quantity,
743 long double largs = maximized_quantity;
746 va_start (args, format);
747 buffer = g_strdup_vprintf (format, args);
749 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
755 * @format: the format string
756 * @...: printf-like arguments to @format
758 * Add a message to the test report.
763 g_test_message (const char *format,
768 va_start (args, format);
769 buffer = g_strdup_vprintf (format, args);
771 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
777 * @uri_pattern: the base pattern for bug URIs
779 * Specify the base URI for bug reports.
781 * The base URI is used to construct bug report messages for
782 * g_test_message() when g_test_bug() is called.
783 * Calling this function outside of a test case sets the
784 * default base URI for all test cases. Calling it from within
785 * a test case changes the base URI for the scope of the test
787 * Bug URIs are constructed by appending a bug specific URI
788 * portion to @uri_pattern, or by replacing the special string
789 * '%s' within @uri_pattern if that is present.
794 g_test_bug_base (const char *uri_pattern)
796 g_free (test_uri_base);
797 test_uri_base = g_strdup (uri_pattern);
802 * @bug_uri_snippet: Bug specific bug tracker URI portion.
804 * This function adds a message to test reports that
805 * associates a bug URI with a test case.
806 * Bug URIs are constructed from a base URI set with g_test_bug_base()
807 * and @bug_uri_snippet.
812 g_test_bug (const char *bug_uri_snippet)
815 g_return_if_fail (test_uri_base != NULL);
816 g_return_if_fail (bug_uri_snippet != NULL);
817 c = strstr (test_uri_base, "%s");
820 char *b = g_strndup (test_uri_base, c - test_uri_base);
821 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
823 g_test_message ("Bug Reference: %s", s);
827 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
833 * Get the toplevel test suite for the test path API.
835 * Returns: the toplevel #GTestSuite
840 g_test_get_root (void)
842 if (!test_suite_root)
844 test_suite_root = g_test_create_suite ("root");
845 g_free (test_suite_root->name);
846 test_suite_root->name = g_strdup ("");
848 return test_suite_root;
854 * Runs all tests under the toplevel suite which can be retrieved
855 * with g_test_get_root(). Similar to g_test_run_suite(), the test
856 * cases to be run are filtered according to
857 * test path arguments (-p <replaceable>testpath</replaceable>) as
858 * parsed by g_test_init().
859 * g_test_run_suite() or g_test_run() may only be called once
862 * Returns: 0 on success
869 return g_test_run_suite (g_test_get_root());
873 * g_test_create_case:
874 * @test_name: the name for the test case
875 * @data_size: the size of the fixture data structure
876 * @test_data: test data argument for the test functions
877 * @data_setup: the function to set up the fixture data
878 * @data_test: the actual test function
879 * @data_teardown: the function to teardown the fixture data
881 * Create a new #GTestCase, named @test_name, this API is fairly
882 * low level, calling g_test_add() or g_test_add_func() is preferable.
883 * When this test is executed, a fixture structure of size @data_size
884 * will be allocated and filled with 0s. Then data_setup() is called
885 * to initialize the fixture. After fixture setup, the actual test
886 * function data_test() is called. Once the test run completed, the
887 * fixture structure is torn down by calling data_teardown() and
888 * after that the memory is released.
890 * Splitting up a test run into fixture setup, test function and
891 * fixture teardown is most usful if the same fixture is used for
892 * multiple tests. In this cases, g_test_create_case() will be
893 * called with the same fixture, but varying @test_name and
894 * @data_test arguments.
896 * Returns: a newly allocated #GTestCase.
901 g_test_create_case (const char *test_name,
903 gconstpointer test_data,
904 void (*data_setup) (void),
905 void (*data_test) (void),
906 void (*data_teardown) (void))
909 g_return_val_if_fail (test_name != NULL, NULL);
910 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
911 g_return_val_if_fail (test_name[0] != 0, NULL);
912 g_return_val_if_fail (data_test != NULL, NULL);
913 tc = g_slice_new0 (GTestCase);
914 tc->name = g_strdup (test_name);
915 tc->test_data = (gpointer) test_data;
916 tc->fixture_size = data_size;
917 tc->fixture_setup = (void*) data_setup;
918 tc->fixture_test = (void*) data_test;
919 tc->fixture_teardown = (void*) data_teardown;
924 g_test_add_vtable (const char *testpath,
926 gconstpointer test_data,
927 void (*data_setup) (void),
928 void (*fixture_test_func) (void),
929 void (*data_teardown) (void))
935 g_return_if_fail (testpath != NULL);
936 g_return_if_fail (testpath[0] == '/');
937 g_return_if_fail (fixture_test_func != NULL);
939 suite = g_test_get_root();
940 segments = g_strsplit (testpath, "/", -1);
941 for (ui = 0; segments[ui] != NULL; ui++)
943 const char *seg = segments[ui];
944 gboolean islast = segments[ui + 1] == NULL;
945 if (islast && !seg[0])
946 g_error ("invalid test case path: %s", testpath);
948 continue; /* initial or duplicate slash */
951 GTestSuite *csuite = g_test_create_suite (seg);
952 g_test_suite_add_suite (suite, csuite);
957 GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
958 g_test_suite_add (suite, tc);
961 g_strfreev (segments);
966 * @testpath: Slash-separated test case path name for the test.
967 * @test_func: The test function to invoke for this test.
969 * Create a new test case, similar to g_test_create_case(). However
970 * the test is assumed to use no fixture, and test suites are automatically
971 * created on the fly and added to the root fixture, based on the
972 * slash-separated portions of @testpath.
977 g_test_add_func (const char *testpath,
978 void (*test_func) (void))
980 g_return_if_fail (testpath != NULL);
981 g_return_if_fail (testpath[0] == '/');
982 g_return_if_fail (test_func != NULL);
983 g_test_add_vtable (testpath, 0, NULL, NULL, test_func, NULL);
987 * g_test_add_data_func:
988 * @testpath: Slash-separated test case path name for the test.
989 * @test_data: Test data argument for the test function.
990 * @test_func: The test function to invoke for this test.
992 * Create a new test case, similar to g_test_create_case(). However
993 * the test is assumed to use no fixture, and test suites are automatically
994 * created on the fly and added to the root fixture, based on the
995 * slash-separated portions of @testpath. The @test_data argument
996 * will be passed as first argument to @test_func.
1001 g_test_add_data_func (const char *testpath,
1002 gconstpointer test_data,
1003 void (*test_func) (gconstpointer))
1005 g_return_if_fail (testpath != NULL);
1006 g_return_if_fail (testpath[0] == '/');
1007 g_return_if_fail (test_func != NULL);
1008 g_test_add_vtable (testpath, 0, test_data, NULL, (void(*)(void)) test_func, NULL);
1012 * g_test_create_suite:
1013 * @suite_name: a name for the suite
1015 * Create a new test suite with the name @suite_name.
1017 * Returns: A newly allocated #GTestSuite instance.
1022 g_test_create_suite (const char *suite_name)
1025 g_return_val_if_fail (suite_name != NULL, NULL);
1026 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1027 g_return_val_if_fail (suite_name[0] != 0, NULL);
1028 ts = g_slice_new0 (GTestSuite);
1029 ts->name = g_strdup (suite_name);
1035 * @suite: a #GTestSuite
1036 * @test_case: a #GTestCase
1038 * Adds @test_case to @suite.
1043 g_test_suite_add (GTestSuite *suite,
1044 GTestCase *test_case)
1046 g_return_if_fail (suite != NULL);
1047 g_return_if_fail (test_case != NULL);
1048 suite->cases = g_slist_prepend (suite->cases, test_case);
1052 * g_test_suite_add_suite:
1053 * @suite: a #GTestSuite
1054 * @nestedsuite: another #GTestSuite
1056 * Adds @nestedsuite to @suite.
1061 g_test_suite_add_suite (GTestSuite *suite,
1062 GTestSuite *nestedsuite)
1064 g_return_if_fail (suite != NULL);
1065 g_return_if_fail (nestedsuite != NULL);
1066 suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1070 * g_test_queue_free:
1071 * @gfree_pointer: the pointer to be stored.
1073 * Enqueue a pointer to be released with g_free() during the next
1074 * teardown phase. This is equivalent to calling g_test_queue_destroy()
1075 * with a destroy callback of g_free().
1080 g_test_queue_free (gpointer gfree_pointer)
1083 g_test_queue_destroy (g_free, gfree_pointer);
1087 * g_test_queue_destroy:
1088 * @destroy_func: Destroy callback for teardown phase.
1089 * @destroy_data: Destroy callback data.
1091 * This function enqueus a callback @destroy_func() to be executed
1092 * during the next test case teardown phase. This is most useful
1093 * to auto destruct allocted test resources at the end of a test run.
1094 * Resources are released in reverse queue order, that means enqueueing
1095 * callback A before callback B will cause B() to be called before
1096 * A() during teardown.
1101 g_test_queue_destroy (GDestroyNotify destroy_func,
1102 gpointer destroy_data)
1104 DestroyEntry *dentry;
1105 g_return_if_fail (destroy_func != NULL);
1106 dentry = g_slice_new0 (DestroyEntry);
1107 dentry->destroy_func = destroy_func;
1108 dentry->destroy_data = destroy_data;
1109 dentry->next = test_destroy_queue;
1110 test_destroy_queue = dentry;
1114 test_case_run (GTestCase *tc)
1116 gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1117 test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1118 if (++test_run_count <= test_skip_count)
1119 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1120 else if (test_run_list)
1122 g_print ("%s\n", test_run_name);
1123 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1127 GTimer *test_run_timer = g_timer_new();
1128 long double largs[3];
1130 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1132 g_test_log_set_fatal_handler (NULL, NULL);
1133 g_timer_start (test_run_timer);
1134 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1135 test_run_seed (test_run_seedstr);
1136 if (tc->fixture_setup)
1137 tc->fixture_setup (fixture, tc->test_data);
1138 tc->fixture_test (fixture, tc->test_data);
1140 while (test_destroy_queue)
1142 DestroyEntry *dentry = test_destroy_queue;
1143 test_destroy_queue = dentry->next;
1144 dentry->destroy_func (dentry->destroy_data);
1145 g_slice_free (DestroyEntry, dentry);
1147 if (tc->fixture_teardown)
1148 tc->fixture_teardown (fixture, tc->test_data);
1149 if (tc->fixture_size)
1151 g_timer_stop (test_run_timer);
1152 largs[0] = 0; /* OK */
1153 largs[1] = test_run_forks;
1154 largs[2] = g_timer_elapsed (test_run_timer, NULL);
1155 g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1156 g_timer_destroy (test_run_timer);
1158 g_free (test_run_name);
1159 test_run_name = old_name;
1160 g_free (test_uri_base);
1161 test_uri_base = old_base;
1166 g_test_run_suite_internal (GTestSuite *suite,
1169 guint n_bad = 0, n_good = 0, bad_suite = 0, l;
1170 gchar *rest, *old_name = test_run_name;
1171 GSList *slist, *reversed;
1172 g_return_val_if_fail (suite != NULL, -1);
1173 while (path[0] == '/')
1176 rest = strchr (path, '/');
1177 l = rest ? MIN (l, rest - path) : l;
1178 test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1179 reversed = g_slist_reverse (g_slist_copy (suite->cases));
1180 for (slist = reversed; slist; slist = slist->next)
1182 GTestCase *tc = slist->data;
1183 guint n = l ? strlen (tc->name) : 0;
1184 if (l == n && strncmp (path, tc->name, n) == 0)
1187 n_bad += test_case_run (tc) != 0;
1190 g_slist_free (reversed);
1191 reversed = g_slist_reverse (g_slist_copy (suite->suites));
1192 for (slist = reversed; slist; slist = slist->next)
1194 GTestSuite *ts = slist->data;
1195 guint n = l ? strlen (ts->name) : 0;
1196 if (l == n && strncmp (path, ts->name, n) == 0)
1197 bad_suite += g_test_run_suite_internal (ts, rest ? rest : "") != 0;
1199 g_slist_free (reversed);
1200 g_free (test_run_name);
1201 test_run_name = old_name;
1202 return n_bad || bad_suite;
1207 * @suite: a #GTestSuite
1209 * Execute the tests within @suite and all nested #GTestSuites.
1210 * The test suites to be executed are filtered according to
1211 * test path arguments (-p <replaceable>testpath</replaceable>)
1212 * as parsed by g_test_init().
1213 * g_test_run_suite() or g_test_run() may only be called once
1216 * Returns: 0 on success
1221 g_test_run_suite (GTestSuite *suite)
1224 g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1225 g_return_val_if_fail (g_test_run_once == TRUE, -1);
1226 g_test_run_once = FALSE;
1228 test_paths = g_slist_prepend (test_paths, "");
1231 const char *rest, *path = test_paths->data;
1232 guint l, n = strlen (suite->name);
1233 test_paths = g_slist_delete_link (test_paths, test_paths);
1234 while (path[0] == '/')
1236 if (!n) /* root suite, run unconditionally */
1238 n_bad += 0 != g_test_run_suite_internal (suite, path);
1241 /* regular suite, match path */
1242 rest = strchr (path, '/');
1244 l = rest ? MIN (l, rest - path) : l;
1245 if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1246 n_bad += 0 != g_test_run_suite_internal (suite, rest ? rest : "");
1252 gtest_default_log_handler (const gchar *log_domain,
1253 GLogLevelFlags log_level,
1254 const gchar *message,
1255 gpointer unused_data)
1257 const gchar *strv[16];
1262 strv[i++] = log_domain;
1265 if (log_level & G_LOG_FLAG_FATAL)
1266 strv[i++] = "FATAL-";
1267 if (log_level & G_LOG_FLAG_RECURSION)
1268 strv[i++] = "RECURSIVE-";
1269 if (log_level & G_LOG_LEVEL_ERROR)
1270 strv[i++] = "ERROR";
1271 if (log_level & G_LOG_LEVEL_CRITICAL)
1272 strv[i++] = "CRITICAL";
1273 if (log_level & G_LOG_LEVEL_WARNING)
1274 strv[i++] = "WARNING";
1275 if (log_level & G_LOG_LEVEL_MESSAGE)
1276 strv[i++] = "MESSAGE";
1277 if (log_level & G_LOG_LEVEL_INFO)
1279 if (log_level & G_LOG_LEVEL_DEBUG)
1280 strv[i++] = "DEBUG";
1282 strv[i++] = message;
1284 msg = g_strjoinv ("", (gchar**) strv);
1285 g_test_log (G_TEST_LOG_ERROR, msg, NULL, 0, NULL);
1286 g_log_default_handler (log_domain, log_level, message, unused_data);
1291 g_assertion_message (const char *domain,
1295 const char *message)
1300 message = "code should not be reached";
1301 g_snprintf (lstr, 32, "%d", line);
1302 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1303 "ERROR:", file, ":", lstr, ":",
1304 func, func[0] ? ":" : "",
1305 " ", message, NULL);
1306 g_printerr ("**\n%s\n", s);
1308 /* store assertion message in global variable, so that it can be found in a
1310 if (__glib_assert_msg != NULL)
1311 /* free the old one */
1312 free (__glib_assert_msg);
1313 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
1314 strcpy (__glib_assert_msg, s);
1316 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
1322 g_assertion_message_expr (const char *domain,
1328 char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1329 g_assertion_message (domain, file, line, func, s);
1334 g_assertion_message_cmpnum (const char *domain,
1347 case 'i': s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
1348 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;
1349 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
1350 /* ideally use: floats=%.7g double=%.17g */
1352 g_assertion_message (domain, file, line, func, s);
1357 g_assertion_message_cmpstr (const char *domain,
1366 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1367 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1368 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1371 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1374 g_assertion_message (domain, file, line, func, s);
1379 g_assertion_message_error (const char *domain,
1385 GQuark error_domain,
1390 /* This is used by both g_assert_error() and g_assert_no_error(), so there
1391 * are three cases: expected an error but got the wrong error, expected
1392 * an error but got no error, and expected no error but got an error.
1395 gstring = g_string_new ("assertion failed ");
1397 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
1398 g_quark_to_string (error_domain), error_code);
1400 g_string_append_printf (gstring, "(%s == NULL): ", expr);
1403 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
1404 g_quark_to_string (error->domain), error->code);
1406 g_string_append_printf (gstring, "%s is NULL", expr);
1408 g_assertion_message (domain, file, line, func, gstring->str);
1409 g_string_free (gstring, TRUE);
1414 * @str1: a C string or %NULL
1415 * @str2: another C string or %NULL
1417 * Compares @str1 and @str2 like strcmp(). Handles %NULL
1418 * gracefully by sorting it before non-%NULL strings.
1420 * Returns: -1, 0 or 1, if @str1 is <, == or > than @str2.
1425 g_strcmp0 (const char *str1,
1429 return -(str1 != str2);
1431 return str1 != str2;
1432 return strcmp (str1, str2);
1436 static int /* 0 on success */
1437 kill_child (int pid,
1442 if (patience >= 3) /* try graceful reap */
1444 if (waitpid (pid, status, WNOHANG) > 0)
1447 if (patience >= 2) /* try SIGHUP */
1450 if (waitpid (pid, status, WNOHANG) > 0)
1452 g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1453 if (waitpid (pid, status, WNOHANG) > 0)
1455 g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
1456 if (waitpid (pid, status, WNOHANG) > 0)
1458 g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
1459 if (waitpid (pid, status, WNOHANG) > 0)
1462 if (patience >= 1) /* try SIGTERM */
1464 kill (pid, SIGTERM);
1465 if (waitpid (pid, status, WNOHANG) > 0)
1467 g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
1468 if (waitpid (pid, status, WNOHANG) > 0)
1470 g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
1471 if (waitpid (pid, status, WNOHANG) > 0)
1475 kill (pid, SIGKILL);
1477 wr = waitpid (pid, status, 0);
1478 while (wr < 0 && errno == EINTR);
1484 g_string_must_read (GString *gstring,
1487 #define STRING_BUFFER_SIZE 4096
1488 char buf[STRING_BUFFER_SIZE];
1491 bytes = read (fd, buf, sizeof (buf));
1493 return 0; /* EOF, calling this function assumes data is available */
1496 g_string_append_len (gstring, buf, bytes);
1499 else if (bytes < 0 && errno == EINTR)
1501 else /* bytes < 0 */
1503 g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1504 return 1; /* ignore error after warning */
1509 g_string_write_out (GString *gstring,
1513 if (*stringpos < gstring->len)
1517 r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
1518 while (r < 0 && errno == EINTR);
1519 *stringpos += MAX (r, 0);
1524 test_trap_clear (void)
1526 test_trap_last_status = 0;
1527 test_trap_last_pid = 0;
1528 g_free (test_trap_last_stdout);
1529 test_trap_last_stdout = NULL;
1530 g_free (test_trap_last_stderr);
1531 test_trap_last_stderr = NULL;
1542 ret = dup2 (fd1, fd2);
1543 while (ret < 0 && errno == EINTR);
1548 test_time_stamp (void)
1552 g_get_current_time (&tv);
1554 stamp = stamp * 1000000 + tv.tv_usec;
1562 * @usec_timeout: Timeout for the forked test in micro seconds.
1563 * @test_trap_flags: Flags to modify forking behaviour.
1565 * Fork the current test program to execute a test case that might
1566 * not return or that might abort. The forked test case is aborted
1567 * and considered failing if its run time exceeds @usec_timeout.
1569 * The forking behavior can be configured with the #GTestTrapFlags flags.
1571 * In the following example, the test code forks, the forked child
1572 * process produces some sample output and exits successfully.
1573 * The forking parent process then asserts successful child program
1574 * termination and validates child program outputs.
1578 * test_fork_patterns (void)
1580 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
1582 * g_print ("some stdout text: somagic17\n");
1583 * g_printerr ("some stderr text: semagic43\n");
1584 * exit (0); /* successful test run */
1586 * g_test_trap_assert_passed();
1587 * g_test_trap_assert_stdout ("*somagic17*");
1588 * g_test_trap_assert_stderr ("*semagic43*");
1592 * This function is implemented only on Unix platforms.
1594 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
1599 g_test_trap_fork (guint64 usec_timeout,
1600 GTestTrapFlags test_trap_flags)
1603 gboolean pass_on_forked_log = FALSE;
1604 int stdout_pipe[2] = { -1, -1 };
1605 int stderr_pipe[2] = { -1, -1 };
1606 int stdtst_pipe[2] = { -1, -1 };
1608 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
1609 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
1610 signal (SIGCHLD, SIG_DFL);
1611 test_trap_last_pid = fork ();
1612 if (test_trap_last_pid < 0)
1613 g_error ("failed to fork test program: %s", g_strerror (errno));
1614 if (test_trap_last_pid == 0) /* child */
1617 close (stdout_pipe[0]);
1618 close (stderr_pipe[0]);
1619 close (stdtst_pipe[0]);
1620 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
1621 fd0 = open ("/dev/null", O_RDONLY);
1622 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
1623 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
1626 if (stdout_pipe[1] >= 3)
1627 close (stdout_pipe[1]);
1628 if (stderr_pipe[1] >= 3)
1629 close (stderr_pipe[1]);
1630 test_log_fd = stdtst_pipe[1];
1635 GString *sout = g_string_new (NULL);
1636 GString *serr = g_string_new (NULL);
1638 int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
1640 close (stdout_pipe[1]);
1641 close (stderr_pipe[1]);
1642 close (stdtst_pipe[1]);
1643 sstamp = test_time_stamp();
1644 /* read data until we get EOF on all pipes */
1645 while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
1651 if (stdout_pipe[0] >= 0)
1652 FD_SET (stdout_pipe[0], &fds);
1653 if (stderr_pipe[0] >= 0)
1654 FD_SET (stderr_pipe[0], &fds);
1655 if (stdtst_pipe[0] >= 0)
1656 FD_SET (stdtst_pipe[0], &fds);
1658 tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
1659 ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
1660 if (ret < 0 && errno != EINTR)
1662 g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1665 if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
1666 g_string_must_read (sout, stdout_pipe[0]) == 0)
1668 close (stdout_pipe[0]);
1669 stdout_pipe[0] = -1;
1671 if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
1672 g_string_must_read (serr, stderr_pipe[0]) == 0)
1674 close (stderr_pipe[0]);
1675 stderr_pipe[0] = -1;
1677 if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
1679 guint8 buffer[4096];
1680 gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
1681 if (r > 0 && test_log_fd > 0)
1683 l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
1684 while (l < 0 && errno == EINTR);
1685 if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
1687 close (stdtst_pipe[0]);
1688 stdtst_pipe[0] = -1;
1691 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
1692 g_string_write_out (sout, 1, &soutpos);
1693 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
1694 g_string_write_out (serr, 2, &serrpos);
1697 guint64 nstamp = test_time_stamp();
1699 sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
1700 if (usec_timeout < nstamp - sstamp)
1702 /* timeout reached, need to abort the child now */
1703 kill_child (test_trap_last_pid, &status, 3);
1704 test_trap_last_status = 1024; /* timeout */
1705 if (0 && WIFSIGNALED (status))
1706 g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
1712 close (stdout_pipe[0]);
1713 close (stderr_pipe[0]);
1714 close (stdtst_pipe[0]);
1719 wr = waitpid (test_trap_last_pid, &status, 0);
1720 while (wr < 0 && errno == EINTR);
1721 if (WIFEXITED (status)) /* normal exit */
1722 test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
1723 else if (WIFSIGNALED (status))
1724 test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
1725 else /* WCOREDUMP (status) */
1726 test_trap_last_status = 512; /* coredump */
1728 test_trap_last_stdout = g_string_free (sout, FALSE);
1729 test_trap_last_stderr = g_string_free (serr, FALSE);
1733 g_message ("Not implemented: g_test_trap_fork");
1740 * g_test_trap_has_passed:
1742 * Check the result of the last g_test_trap_fork() call.
1744 * Returns: %TRUE if the last forked child terminated successfully.
1749 g_test_trap_has_passed (void)
1751 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
1755 * g_test_trap_reached_timeout:
1757 * Check the result of the last g_test_trap_fork() call.
1759 * Returns: %TRUE if the last forked child got killed due to a fork timeout.
1764 g_test_trap_reached_timeout (void)
1766 return 0 != (test_trap_last_status & 1024); /* timeout flag */
1770 g_test_trap_assertions (const char *domain,
1774 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
1775 const char *pattern)
1778 gboolean must_pass = assertion_flags == 0;
1779 gboolean must_fail = assertion_flags == 1;
1780 gboolean match_result = 0 == (assertion_flags & 1);
1781 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
1782 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
1783 const char *match_error = match_result ? "failed to match" : "contains invalid match";
1784 if (test_trap_last_pid == 0)
1785 g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
1786 if (must_pass && !g_test_trap_has_passed())
1788 char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
1789 g_assertion_message (domain, file, line, func, msg);
1792 if (must_fail && g_test_trap_has_passed())
1794 char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
1795 g_assertion_message (domain, file, line, func, msg);
1798 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
1800 char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
1801 g_assertion_message (domain, file, line, func, msg);
1804 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
1806 char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
1807 g_assertion_message (domain, file, line, func, msg);
1814 gstring_overwrite_int (GString *gstring,
1818 vuint = g_htonl (vuint);
1819 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
1823 gstring_append_int (GString *gstring,
1826 vuint = g_htonl (vuint);
1827 g_string_append_len (gstring, (const gchar*) &vuint, 4);
1831 gstring_append_double (GString *gstring,
1834 union { double vdouble; guint64 vuint64; } u;
1835 u.vdouble = vdouble;
1836 u.vuint64 = GUINT64_TO_BE (u.vuint64);
1837 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
1841 g_test_log_dump (GTestLogMsg *msg,
1844 GString *gstring = g_string_sized_new (1024);
1846 gstring_append_int (gstring, 0); /* message length */
1847 gstring_append_int (gstring, msg->log_type);
1848 gstring_append_int (gstring, msg->n_strings);
1849 gstring_append_int (gstring, msg->n_nums);
1850 gstring_append_int (gstring, 0); /* reserved */
1851 for (ui = 0; ui < msg->n_strings; ui++)
1853 guint l = strlen (msg->strings[ui]);
1854 gstring_append_int (gstring, l);
1855 g_string_append_len (gstring, msg->strings[ui], l);
1857 for (ui = 0; ui < msg->n_nums; ui++)
1858 gstring_append_double (gstring, msg->nums[ui]);
1859 *len = gstring->len;
1860 gstring_overwrite_int (gstring, 0, *len); /* message length */
1861 return (guint8*) g_string_free (gstring, FALSE);
1864 static inline long double
1865 net_double (const gchar **ipointer)
1867 union { guint64 vuint64; double vdouble; } u;
1868 guint64 aligned_int64;
1869 memcpy (&aligned_int64, *ipointer, 8);
1871 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
1875 static inline guint32
1876 net_int (const gchar **ipointer)
1878 guint32 aligned_int;
1879 memcpy (&aligned_int, *ipointer, 4);
1881 return g_ntohl (aligned_int);
1885 g_test_log_extract (GTestLogBuffer *tbuffer)
1887 const gchar *p = tbuffer->data->str;
1890 if (tbuffer->data->len < 4 * 5)
1892 mlength = net_int (&p);
1893 if (tbuffer->data->len < mlength)
1895 msg.log_type = net_int (&p);
1896 msg.n_strings = net_int (&p);
1897 msg.n_nums = net_int (&p);
1898 if (net_int (&p) == 0)
1901 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
1902 msg.nums = g_new0 (long double, msg.n_nums);
1903 for (ui = 0; ui < msg.n_strings; ui++)
1905 guint sl = net_int (&p);
1906 msg.strings[ui] = g_strndup (p, sl);
1909 for (ui = 0; ui < msg.n_nums; ui++)
1910 msg.nums[ui] = net_double (&p);
1911 if (p <= tbuffer->data->str + mlength)
1913 g_string_erase (tbuffer->data, 0, mlength);
1914 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
1919 g_strfreev (msg.strings);
1920 g_error ("corrupt log stream from test program");
1925 * g_test_log_buffer_new:
1927 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1930 g_test_log_buffer_new (void)
1932 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
1933 tb->data = g_string_sized_new (1024);
1938 * g_test_log_buffer_free
1940 * Internal function for gtester to free test log messages, no ABI guarantees provided.
1943 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
1945 g_return_if_fail (tbuffer != NULL);
1946 while (tbuffer->msgs)
1947 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
1948 g_string_free (tbuffer->data, TRUE);
1953 * g_test_log_buffer_push
1955 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1958 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
1960 const guint8 *bytes)
1962 g_return_if_fail (tbuffer != NULL);
1965 gboolean more_messages;
1966 g_return_if_fail (bytes != NULL);
1967 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
1969 more_messages = g_test_log_extract (tbuffer);
1970 while (more_messages);
1975 * g_test_log_buffer_pop:
1977 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
1980 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
1982 GTestLogMsg *msg = NULL;
1983 g_return_val_if_fail (tbuffer != NULL, NULL);
1986 GSList *slist = g_slist_last (tbuffer->msgs);
1988 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
1994 * g_test_log_msg_free:
1996 * Internal function for gtester to free test log messages, no ABI guarantees provided.
1999 g_test_log_msg_free (GTestLogMsg *tmsg)
2001 g_return_if_fail (tmsg != NULL);
2002 g_strfreev (tmsg->strings);
2003 g_free (tmsg->nums);
2007 /* --- macros docs START --- */
2010 * @testpath: The test path for a new test case.
2011 * @Fixture: The type of a fixture data structure.
2012 * @tdata: Data argument for the test functions.
2013 * @fsetup: The function to set up the fixture data.
2014 * @ftest: The actual test function.
2015 * @fteardown: The function to tear down the fixture data.
2017 * Hook up a new test case at @testpath, similar to g_test_add_func().
2018 * A fixture data structure with setup and teardown function may be provided
2019 * though, similar to g_test_create_case().
2020 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2021 * fteardown() callbacks can expect a @Fixture pointer as first argument in
2022 * a type safe manner.
2026 /* --- macros docs END --- */
2028 #define __G_TEST_UTILS_C__
2029 #include "galiasdef.c"