1 /* GLib testing utilities
2 * Copyright (C) 2007 Imendio AB
3 * Authors: Tim Janik, Sven Herzberg
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
23 #include "gtestutils.h"
25 #include <sys/types.h>
42 #ifdef HAVE_SYS_SELECT_H
43 #include <sys/select.h>
44 #endif /* HAVE_SYS_SELECT_H */
49 #include "gstrfuncs.h"
57 * @short_description: a test framework
58 * @see_also: <link linkend="gtester">gtester</link>,
59 * <link linkend="gtester-report">gtester-report</link>
61 * GLib provides a framework for writing and maintaining unit tests
62 * in parallel to the code they are testing. The API is designed according
63 * to established concepts found in the other test frameworks (JUnit, NUnit,
64 * RUnit), which in turn is based on smalltalk unit testing concepts.
68 * <term>Test case</term>
69 * <listitem>Tests (test methods) are grouped together with their
70 * fixture into test cases.</listitem>
73 * <term>Fixture</term>
74 * <listitem>A test fixture consists of fixture data and setup and
75 * teardown methods to establish the environment for the test
76 * functions. We use fresh fixtures, i.e. fixtures are newly set
77 * up and torn down around each test invocation to avoid dependencies
78 * between tests.</listitem>
81 * <term>Test suite</term>
82 * <listitem>Test cases can be grouped into test suites, to allow
83 * subsets of the available tests to be run. Test suites can be
84 * grouped into other test suites as well.</listitem>
87 * The API is designed to handle creation and registration of test suites
88 * and test cases implicitly. A simple call like
90 * g_test_add_func ("/misc/assertions", test_assertions);
92 * creates a test suite called "misc" with a single test case named
93 * "assertions", which consists of running the test_assertions function.
95 * In addition to the traditional g_assert(), the test framework provides
96 * an extended set of assertions for string and numerical comparisons:
97 * g_assert_cmpfloat(), g_assert_cmpint(), g_assert_cmpuint(),
98 * g_assert_cmphex(), g_assert_cmpstr(). The advantage of these variants
99 * over plain g_assert() is that the assertion messages can be more
100 * elaborate, and include the values of the compared entities.
102 * GLib ships with two utilities called gtester and gtester-report to
103 * facilitate running tests and producing nicely formatted test reports.
109 * Returns %TRUE if tests are run in quick mode.
110 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
111 * there is no "medium speed".
113 * Returns: %TRUE if in quick mode
119 * Returns %TRUE if tests are run in slow mode.
120 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
121 * there is no "medium speed".
123 * Returns: the opposite of g_test_quick()
129 * Returns %TRUE if tests are run in thorough mode, equivalent to
132 * Returns: the same thing as g_test_slow()
138 * Returns %TRUE if tests are run in performance mode.
140 * Returns: %TRUE if in performance mode
146 * Returns %TRUE if tests are run in verbose mode.
147 * The default is neither g_test_verbose() nor g_test_quiet().
149 * Returns: %TRUE if in verbose mode
155 * Returns %TRUE if tests are run in quiet mode.
156 * The default is neither g_test_verbose() nor g_test_quiet().
158 * Returns: %TRUE if in quiet mode
162 * g_test_queue_unref:
163 * @gobject: the object to unref
165 * Enqueue an object to be released with g_object_unref() during
166 * the next teardown phase. This is equivalent to calling
167 * g_test_queue_destroy() with a destroy callback of g_object_unref().
174 * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
175 * <filename>/dev/null</filename> so it cannot be observed on the
176 * console during test runs. The actual output is still captured
177 * though to allow later tests with g_test_trap_assert_stdout().
178 * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
179 * <filename>/dev/null</filename> so it cannot be observed on the
180 * console during test runs. The actual output is still captured
181 * though to allow later tests with g_test_trap_assert_stderr().
182 * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
183 * forked child process is shared with stdin of its parent process.
184 * It is redirected to <filename>/dev/null</filename> otherwise.
186 * Test traps are guards around forked tests.
187 * These flags determine what traps to set.
191 * g_test_trap_assert_passed:
193 * Assert that the last forked test passed.
194 * See g_test_trap_fork().
200 * g_test_trap_assert_failed:
202 * Assert that the last forked test failed.
203 * See g_test_trap_fork().
209 * g_test_trap_assert_stdout:
210 * @soutpattern: a glob-style
211 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
213 * Assert that the stdout output of the last forked test matches
214 * @soutpattern. See g_test_trap_fork().
220 * g_test_trap_assert_stdout_unmatched:
221 * @soutpattern: a glob-style
222 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
224 * Assert that the stdout output of the last forked test
225 * does not match @soutpattern. See g_test_trap_fork().
231 * g_test_trap_assert_stderr:
232 * @serrpattern: a glob-style
233 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
235 * Assert that the stderr output of the last forked test
236 * matches @serrpattern. See g_test_trap_fork().
242 * g_test_trap_assert_stderr_unmatched:
243 * @serrpattern: a glob-style
244 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
246 * Assert that the stderr output of the last forked test
247 * does not match @serrpattern. See g_test_trap_fork().
255 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
256 * for details on test case random numbers.
263 * @expr: the expression to check
265 * Debugging macro to terminate the application if the assertion
266 * fails. If the assertion fails (i.e. the expression is not true),
267 * an error message is logged and the application is terminated.
269 * The macro can be turned off in final releases of code by defining
270 * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
274 * g_assert_not_reached:
276 * Debugging macro to terminate the application if it is ever
277 * reached. If it is reached, an error message is logged and the
278 * application is terminated.
280 * The macro can be turned off in final releases of code by defining
281 * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
286 * @s1: a string (may be %NULL)
287 * @cmp: The comparison operator to use.
288 * One of ==, !=, <, >, <=, >=.
289 * @s2: another string (may be %NULL)
291 * Debugging macro to terminate the application with a warning
292 * message if a string comparison fails. The strings are compared
295 * The effect of <literal>g_assert_cmpstr (s1, op, s2)</literal> is
296 * the same as <literal>g_assert (g_strcmp0 (s1, s2) op 0)</literal>.
297 * The advantage of this macro is that it can produce a message that
298 * includes the actual values of @s1 and @s2.
301 * g_assert_cmpstr (mystring, ==, "fubar");
310 * @cmp: The comparison operator to use.
311 * One of ==, !=, <, >, <=, >=.
312 * @n2: another integer
314 * Debugging macro to terminate the application with a warning
315 * message if an integer comparison fails.
317 * The effect of <literal>g_assert_cmpint (n1, op, n2)</literal> is
318 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
319 * of this macro is that it can produce a message that includes the
320 * actual values of @n1 and @n2.
327 * @n1: an unsigned integer
328 * @cmp: The comparison operator to use.
329 * One of ==, !=, <, >, <=, >=.
330 * @n2: another unsigned integer
332 * Debugging macro to terminate the application with a warning
333 * message if an unsigned integer comparison fails.
335 * The effect of <literal>g_assert_cmpuint (n1, op, n2)</literal> is
336 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
337 * of this macro is that it can produce a message that includes the
338 * actual values of @n1 and @n2.
345 * @n1: an unsigned integer
346 * @cmp: The comparison operator to use.
347 * One of ==, !=, <, >, <=, >=.
348 * @n2: another unsigned integer
350 * Debugging macro to terminate the application with a warning
351 * message if an unsigned integer comparison fails.
353 * This is a variant of g_assert_cmpuint() that displays the numbers
354 * in hexadecimal notation in the message.
361 * @n1: an floating point number
362 * @cmp: The comparison operator to use.
363 * One of ==, !=, <, >, <=, >=.
364 * @n2: another floating point number
366 * Debugging macro to terminate the application with a warning
367 * message if a floating point number comparison fails.
369 * The effect of <literal>g_assert_cmpfloat (n1, op, n2)</literal> is
370 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
371 * of this macro is that it can produce a message that includes the
372 * actual values of @n1 and @n2.
379 * @err: a #GError, possibly %NULL
381 * Debugging macro to terminate the application with a warning
382 * message if a method has returned a #GError.
384 * The effect of <literal>g_assert_no_error (err)</literal> is
385 * the same as <literal>g_assert (err == NULL)</literal>. The advantage
386 * of this macro is that it can produce a message that includes
387 * the error message and code.
394 * @err: a #GError, possibly %NULL
395 * @dom: the expected error domain (a #GQuark)
396 * @c: the expected error code
398 * Debugging macro to terminate the application with a warning
399 * message if a method has not returned the correct #GError.
401 * The effect of <literal>g_assert_error (err, dom, c)</literal> is
402 * the same as <literal>g_assert (err != NULL && err->domain
403 * == dom && err->code == c)</literal>. The advantage of this
404 * macro is that it can produce a message that includes the incorrect
405 * error message and code.
407 * This can only be used to test for a specific error. If you want to
408 * test that @err is set, but don't care what it's set to, just use
409 * <literal>g_assert (err != NULL)</literal>
417 * An opaque structure representing a test case.
423 * An opaque structure representing a test suite.
427 /* Global variable for storing assertion messages; this is the counterpart to
428 * glibc's (private) __abort_msg variable, and allows developers and crash
429 * analysis systems like Apport and ABRT to fish out assertion messages from
430 * core dumps, instead of having to catch them on screen output.
432 char *__glib_assert_msg = NULL;
434 /* --- structures --- */
439 void (*fixture_setup) (void*, gconstpointer);
440 void (*fixture_test) (void*, gconstpointer);
441 void (*fixture_teardown) (void*, gconstpointer);
450 typedef struct DestroyEntry DestroyEntry;
454 GDestroyNotify destroy_func;
455 gpointer destroy_data;
458 /* --- prototypes --- */
459 static void test_run_seed (const gchar *rseed);
460 static void test_trap_clear (void);
461 static guint8* g_test_log_dump (GTestLogMsg *msg,
463 static void gtest_default_log_handler (const gchar *log_domain,
464 GLogLevelFlags log_level,
465 const gchar *message,
466 gpointer unused_data);
469 /* --- variables --- */
470 static int test_log_fd = -1;
471 static gboolean test_mode_fatal = TRUE;
472 static gboolean g_test_run_once = TRUE;
473 static gboolean test_run_list = FALSE;
474 static gchar *test_run_seedstr = NULL;
475 static GRand *test_run_rand = NULL;
476 static gchar *test_run_name = "";
477 static guint test_run_forks = 0;
478 static guint test_run_count = 0;
479 static guint test_run_success = FALSE;
480 static guint test_skip_count = 0;
481 static GTimer *test_user_timer = NULL;
482 static double test_user_stamp = 0;
483 static GSList *test_paths = NULL;
484 static GSList *test_paths_skipped = NULL;
485 static GTestSuite *test_suite_root = NULL;
486 static int test_trap_last_status = 0;
487 static int test_trap_last_pid = 0;
488 static char *test_trap_last_stdout = NULL;
489 static char *test_trap_last_stderr = NULL;
490 static char *test_uri_base = NULL;
491 static gboolean test_debug_log = FALSE;
492 static DestroyEntry *test_destroy_queue = NULL;
493 static GTestConfig mutable_test_config_vars = {
494 FALSE, /* test_initialized */
495 TRUE, /* test_quick */
496 FALSE, /* test_perf */
497 FALSE, /* test_verbose */
498 FALSE, /* test_quiet */
500 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
502 /* --- functions --- */
504 g_test_log_type_name (GTestLogType log_type)
508 case G_TEST_LOG_NONE: return "none";
509 case G_TEST_LOG_ERROR: return "error";
510 case G_TEST_LOG_START_BINARY: return "binary";
511 case G_TEST_LOG_LIST_CASE: return "list";
512 case G_TEST_LOG_SKIP_CASE: return "skip";
513 case G_TEST_LOG_START_CASE: return "start";
514 case G_TEST_LOG_STOP_CASE: return "stop";
515 case G_TEST_LOG_MIN_RESULT: return "minperf";
516 case G_TEST_LOG_MAX_RESULT: return "maxperf";
517 case G_TEST_LOG_MESSAGE: return "message";
523 g_test_log_send (guint n_bytes,
524 const guint8 *buffer)
526 if (test_log_fd >= 0)
530 r = write (test_log_fd, buffer, n_bytes);
531 while (r < 0 && errno == EINTR);
535 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
538 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
539 msg = g_test_log_buffer_pop (lbuffer);
540 g_warn_if_fail (msg != NULL);
541 g_warn_if_fail (lbuffer->data->len == 0);
542 g_test_log_buffer_free (lbuffer);
544 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
545 for (ui = 0; ui < msg->n_strings; ui++)
546 g_printerr (":{%s}", msg->strings[ui]);
550 for (ui = 0; ui < msg->n_nums; ui++)
551 g_printerr ("%s%.16Lg", ui ? ";" : "", msg->nums[ui]);
554 g_printerr (":LOG*}\n");
555 g_test_log_msg_free (msg);
560 g_test_log (GTestLogType lbit,
561 const gchar *string1,
562 const gchar *string2,
566 gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
568 gchar *astrings[3] = { NULL, NULL, NULL };
574 case G_TEST_LOG_START_BINARY:
575 if (g_test_verbose())
576 g_print ("GTest: random seed: %s\n", string2);
578 case G_TEST_LOG_STOP_CASE:
579 if (g_test_verbose())
580 g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
581 else if (!g_test_quiet())
582 g_print ("%s\n", fail ? "FAIL" : "OK");
583 if (fail && test_mode_fatal)
586 case G_TEST_LOG_MIN_RESULT:
587 if (g_test_verbose())
588 g_print ("(MINPERF:%s)\n", string1);
590 case G_TEST_LOG_MAX_RESULT:
591 if (g_test_verbose())
592 g_print ("(MAXPERF:%s)\n", string1);
594 case G_TEST_LOG_MESSAGE:
595 if (g_test_verbose())
596 g_print ("(MSG: %s)\n", string1);
602 msg.n_strings = (string1 != NULL) + (string1 && string2);
603 msg.strings = astrings;
604 astrings[0] = (gchar*) string1;
605 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
608 dbuffer = g_test_log_dump (&msg, &dbufferlen);
609 g_test_log_send (dbufferlen, dbuffer);
614 case G_TEST_LOG_START_CASE:
615 if (g_test_verbose())
616 g_print ("GTest: run: %s\n", string1);
617 else if (!g_test_quiet())
618 g_print ("%s: ", string1);
624 /* We intentionally parse the command line without GOptionContext
625 * because otherwise you would never be able to test it.
628 parse_args (gint *argc_p,
631 guint argc = *argc_p;
632 gchar **argv = *argv_p;
634 /* parse known args */
635 for (i = 1; i < argc; i++)
637 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
639 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
640 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
641 g_log_set_always_fatal (fatal_mask);
644 else if (strcmp (argv[i], "--keep-going") == 0 ||
645 strcmp (argv[i], "-k") == 0)
647 test_mode_fatal = FALSE;
650 else if (strcmp (argv[i], "--debug-log") == 0)
652 test_debug_log = TRUE;
655 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
657 gchar *equal = argv[i] + 12;
659 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
660 else if (i + 1 < argc)
663 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
667 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
669 gchar *equal = argv[i] + 16;
671 test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
672 else if (i + 1 < argc)
675 test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
679 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
681 gchar *equal = argv[i] + 2;
683 test_paths = g_slist_prepend (test_paths, equal + 1);
684 else if (i + 1 < argc)
687 test_paths = g_slist_prepend (test_paths, argv[i]);
691 else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
693 gchar *equal = argv[i] + 2;
695 test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
696 else if (i + 1 < argc)
699 test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
703 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
705 gchar *equal = argv[i] + 2;
706 const gchar *mode = "";
709 else if (i + 1 < argc)
714 if (strcmp (mode, "perf") == 0)
715 mutable_test_config_vars.test_perf = TRUE;
716 else if (strcmp (mode, "slow") == 0)
717 mutable_test_config_vars.test_quick = FALSE;
718 else if (strcmp (mode, "thorough") == 0)
719 mutable_test_config_vars.test_quick = FALSE;
720 else if (strcmp (mode, "quick") == 0)
722 mutable_test_config_vars.test_quick = TRUE;
723 mutable_test_config_vars.test_perf = FALSE;
726 g_error ("unknown test mode: -m %s", mode);
729 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
731 mutable_test_config_vars.test_quiet = TRUE;
732 mutable_test_config_vars.test_verbose = FALSE;
735 else if (strcmp ("--verbose", argv[i]) == 0)
737 mutable_test_config_vars.test_quiet = FALSE;
738 mutable_test_config_vars.test_verbose = TRUE;
741 else if (strcmp ("-l", argv[i]) == 0)
743 test_run_list = TRUE;
746 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
748 gchar *equal = argv[i] + 6;
750 test_run_seedstr = equal + 1;
751 else if (i + 1 < argc)
754 test_run_seedstr = argv[i];
758 else if (strcmp ("-?", argv[i]) == 0 || strcmp ("--help", argv[i]) == 0)
761 " %s [OPTION...]\n\n"
763 " -?, --help Show help options\n"
765 " -l List test cases available in a test executable\n"
766 " -seed=RANDOMSEED Provide a random seed to reproduce test\n"
767 " runs using random numbers\n"
768 " --verbose Run tests verbosely\n"
769 " -q, --quiet Run tests quietly\n"
770 " -p TESTPATH execute all tests matching TESTPATH\n"
771 " -s TESTPATH skip all tests matching TESTPATH\n"
772 " -m {perf|slow|thorough|quick} Execute tests according modes\n"
773 " --debug-log debug test logging output\n"
774 " -k, --keep-going gtester-specific argument\n"
775 " --GTestLogFD=N gtester-specific argument\n"
776 " --GTestSkipCount=N gtester-specific argument\n",
783 for (i = 1; i < argc; i++)
795 * @argc: Address of the @argc parameter of the main() function.
796 * Changed if any arguments were handled.
797 * @argv: Address of the @argv parameter of main().
798 * Any parameters understood by g_test_init() stripped before return.
799 * @...: Reserved for future extension. Currently, you must pass %NULL.
801 * Initialize the GLib testing framework, e.g. by seeding the
802 * test random number generator, the name for g_get_prgname()
803 * and parsing test related command line args.
804 * So far, the following arguments are understood:
807 * <term><option>-l</option></term>
809 * list test cases available in a test executable.
813 * <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
815 * provide a random seed to reproduce test runs using random numbers.
819 * <term><option>--verbose</option></term>
820 * <listitem><para>run tests verbosely.</para></listitem>
823 * <term><option>-q</option>, <option>--quiet</option></term>
824 * <listitem><para>run tests quietly.</para></listitem>
827 * <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
829 * execute all tests matching <replaceable>TESTPATH</replaceable>.
833 * <term><option>-m {perf|slow|thorough|quick}</option></term>
835 * execute tests according to these test modes:
840 * performance tests, may take long and report results.
844 * <term>slow, thorough</term>
846 * slow and thorough tests, may take quite long and
853 * quick tests, should run really quickly and give good coverage.
860 * <term><option>--debug-log</option></term>
861 * <listitem><para>debug test logging output.</para></listitem>
864 * <term><option>-k</option>, <option>--keep-going</option></term>
865 * <listitem><para>gtester-specific argument.</para></listitem>
868 * <term><option>--GTestLogFD <replaceable>N</replaceable></option></term>
869 * <listitem><para>gtester-specific argument.</para></listitem>
872 * <term><option>--GTestSkipCount <replaceable>N</replaceable></option></term>
873 * <listitem><para>gtester-specific argument.</para></listitem>
880 g_test_init (int *argc,
884 static char seedstr[4 + 4 * 8 + 1];
887 /* make warnings and criticals fatal for all test programs */
888 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
889 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
890 g_log_set_always_fatal (fatal_mask);
891 /* check caller args */
892 g_return_if_fail (argc != NULL);
893 g_return_if_fail (argv != NULL);
894 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
895 mutable_test_config_vars.test_initialized = TRUE;
897 va_start (args, argv);
898 vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
900 g_return_if_fail (vararg1 == NULL);
902 /* setup random seed string */
903 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
904 test_run_seedstr = seedstr;
906 /* parse args, sets up mode, changes seed, etc. */
907 parse_args (argc, argv);
908 if (!g_get_prgname())
909 g_set_prgname ((*argv)[0]);
911 /* verify GRand reliability, needed for reliable seeds */
914 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
915 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
916 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
917 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
918 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
922 /* check rand seed */
923 test_run_seed (test_run_seedstr);
925 /* report program start */
926 g_log_set_default_handler (gtest_default_log_handler, NULL);
927 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
931 test_run_seed (const gchar *rseed)
933 guint seed_failed = 0;
935 g_rand_free (test_run_rand);
936 test_run_rand = NULL;
937 while (strchr (" \t\v\r\n\f", *rseed))
939 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
941 const char *s = rseed + 4;
942 if (strlen (s) >= 32) /* require 4 * 8 chars */
944 guint32 seedarray[4];
945 gchar *p, hexbuf[9] = { 0, };
946 memcpy (hexbuf, s + 0, 8);
947 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
948 seed_failed += p != NULL && *p != 0;
949 memcpy (hexbuf, s + 8, 8);
950 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
951 seed_failed += p != NULL && *p != 0;
952 memcpy (hexbuf, s + 16, 8);
953 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
954 seed_failed += p != NULL && *p != 0;
955 memcpy (hexbuf, s + 24, 8);
956 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
957 seed_failed += p != NULL && *p != 0;
960 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
965 g_error ("Unknown or invalid random seed: %s", rseed);
971 * Get a reproducible random integer number.
973 * The random numbers generated by the g_test_rand_*() family of functions
974 * change with every new test program start, unless the --seed option is
975 * given when starting test programs.
977 * For individual test cases however, the random number generator is
978 * reseeded, to avoid dependencies between tests and to make --seed
979 * effective for all test cases.
981 * Returns: a random number from the seeded random number generator.
986 g_test_rand_int (void)
988 return g_rand_int (test_run_rand);
992 * g_test_rand_int_range:
993 * @begin: the minimum value returned by this function
994 * @end: the smallest value not to be returned by this function
996 * Get a reproducible random integer number out of a specified range,
997 * see g_test_rand_int() for details on test case random numbers.
999 * Returns: a number with @begin <= number < @end.
1004 g_test_rand_int_range (gint32 begin,
1007 return g_rand_int_range (test_run_rand, begin, end);
1011 * g_test_rand_double:
1013 * Get a reproducible random floating point number,
1014 * see g_test_rand_int() for details on test case random numbers.
1016 * Returns: a random number from the seeded random number generator.
1021 g_test_rand_double (void)
1023 return g_rand_double (test_run_rand);
1027 * g_test_rand_double_range:
1028 * @range_start: the minimum value returned by this function
1029 * @range_end: the minimum value not returned by this function
1031 * Get a reproducible random floating pointer number out of a specified range,
1032 * see g_test_rand_int() for details on test case random numbers.
1034 * Returns: a number with @range_start <= number < @range_end.
1039 g_test_rand_double_range (double range_start,
1042 return g_rand_double_range (test_run_rand, range_start, range_end);
1046 * g_test_timer_start:
1048 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1049 * to be done. Call this function again to restart the timer.
1054 g_test_timer_start (void)
1056 if (!test_user_timer)
1057 test_user_timer = g_timer_new();
1058 test_user_stamp = 0;
1059 g_timer_start (test_user_timer);
1063 * g_test_timer_elapsed:
1065 * Get the time since the last start of the timer with g_test_timer_start().
1067 * Returns: the time since the last start of the timer, as a double
1072 g_test_timer_elapsed (void)
1074 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1075 return test_user_stamp;
1079 * g_test_timer_last:
1081 * Report the last result of g_test_timer_elapsed().
1083 * Returns: the last result of g_test_timer_elapsed(), as a double
1088 g_test_timer_last (void)
1090 return test_user_stamp;
1094 * g_test_minimized_result:
1095 * @minimized_quantity: the reported value
1096 * @format: the format string of the report message
1097 * @...: arguments to pass to the printf() function
1099 * Report the result of a performance or measurement test.
1100 * The test should generally strive to minimize the reported
1101 * quantities (smaller values are better than larger ones),
1102 * this and @minimized_quantity can determine sorting
1103 * order for test result reports.
1108 g_test_minimized_result (double minimized_quantity,
1112 long double largs = minimized_quantity;
1116 va_start (args, format);
1117 buffer = g_strdup_vprintf (format, args);
1120 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1125 * g_test_maximized_result:
1126 * @maximized_quantity: the reported value
1127 * @format: the format string of the report message
1128 * @...: arguments to pass to the printf() function
1130 * Report the result of a performance or measurement test.
1131 * The test should generally strive to maximize the reported
1132 * quantities (larger values are better than smaller ones),
1133 * this and @maximized_quantity can determine sorting
1134 * order for test result reports.
1139 g_test_maximized_result (double maximized_quantity,
1143 long double largs = maximized_quantity;
1147 va_start (args, format);
1148 buffer = g_strdup_vprintf (format, args);
1151 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1157 * @format: the format string
1158 * @...: printf-like arguments to @format
1160 * Add a message to the test report.
1165 g_test_message (const char *format,
1171 va_start (args, format);
1172 buffer = g_strdup_vprintf (format, args);
1175 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1181 * @uri_pattern: the base pattern for bug URIs
1183 * Specify the base URI for bug reports.
1185 * The base URI is used to construct bug report messages for
1186 * g_test_message() when g_test_bug() is called.
1187 * Calling this function outside of a test case sets the
1188 * default base URI for all test cases. Calling it from within
1189 * a test case changes the base URI for the scope of the test
1191 * Bug URIs are constructed by appending a bug specific URI
1192 * portion to @uri_pattern, or by replacing the special string
1193 * '\%s' within @uri_pattern if that is present.
1198 g_test_bug_base (const char *uri_pattern)
1200 g_free (test_uri_base);
1201 test_uri_base = g_strdup (uri_pattern);
1206 * @bug_uri_snippet: Bug specific bug tracker URI portion.
1208 * This function adds a message to test reports that
1209 * associates a bug URI with a test case.
1210 * Bug URIs are constructed from a base URI set with g_test_bug_base()
1211 * and @bug_uri_snippet.
1216 g_test_bug (const char *bug_uri_snippet)
1220 g_return_if_fail (test_uri_base != NULL);
1221 g_return_if_fail (bug_uri_snippet != NULL);
1223 c = strstr (test_uri_base, "%s");
1226 char *b = g_strndup (test_uri_base, c - test_uri_base);
1227 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1229 g_test_message ("Bug Reference: %s", s);
1233 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1239 * Get the toplevel test suite for the test path API.
1241 * Returns: the toplevel #GTestSuite
1246 g_test_get_root (void)
1248 if (!test_suite_root)
1250 test_suite_root = g_test_create_suite ("root");
1251 g_free (test_suite_root->name);
1252 test_suite_root->name = g_strdup ("");
1255 return test_suite_root;
1261 * Runs all tests under the toplevel suite which can be retrieved
1262 * with g_test_get_root(). Similar to g_test_run_suite(), the test
1263 * cases to be run are filtered according to
1264 * test path arguments (-p <replaceable>testpath</replaceable>) as
1265 * parsed by g_test_init().
1266 * g_test_run_suite() or g_test_run() may only be called once
1269 * Returns: 0 on success
1276 return g_test_run_suite (g_test_get_root());
1280 * g_test_create_case:
1281 * @test_name: the name for the test case
1282 * @data_size: the size of the fixture data structure
1283 * @test_data: test data argument for the test functions
1284 * @data_setup: the function to set up the fixture data
1285 * @data_test: the actual test function
1286 * @data_teardown: the function to teardown the fixture data
1288 * Create a new #GTestCase, named @test_name, this API is fairly
1289 * low level, calling g_test_add() or g_test_add_func() is preferable.
1290 * When this test is executed, a fixture structure of size @data_size
1291 * will be allocated and filled with 0s. Then @data_setup is called
1292 * to initialize the fixture. After fixture setup, the actual test
1293 * function @data_test is called. Once the test run completed, the
1294 * fixture structure is torn down by calling @data_teardown and
1295 * after that the memory is released.
1297 * Splitting up a test run into fixture setup, test function and
1298 * fixture teardown is most usful if the same fixture is used for
1299 * multiple tests. In this cases, g_test_create_case() will be
1300 * called with the same fixture, but varying @test_name and
1301 * @data_test arguments.
1303 * Returns: a newly allocated #GTestCase.
1308 g_test_create_case (const char *test_name,
1310 gconstpointer test_data,
1311 GTestFixtureFunc data_setup,
1312 GTestFixtureFunc data_test,
1313 GTestFixtureFunc data_teardown)
1317 g_return_val_if_fail (test_name != NULL, NULL);
1318 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1319 g_return_val_if_fail (test_name[0] != 0, NULL);
1320 g_return_val_if_fail (data_test != NULL, NULL);
1322 tc = g_slice_new0 (GTestCase);
1323 tc->name = g_strdup (test_name);
1324 tc->test_data = (gpointer) test_data;
1325 tc->fixture_size = data_size;
1326 tc->fixture_setup = (void*) data_setup;
1327 tc->fixture_test = (void*) data_test;
1328 tc->fixture_teardown = (void*) data_teardown;
1335 * @fixture: the test fixture
1336 * @user_data: the data provided when registering the test
1338 * The type used for functions that operate on test fixtures. This is
1339 * used for the fixture setup and teardown functions as well as for the
1340 * testcases themselves.
1342 * @user_data is a pointer to the data that was given when registering
1345 * @fixture will be a pointer to the area of memory allocated by the
1346 * test framework, of the size requested. If the requested size was
1347 * zero then @fixture will be equal to @user_data.
1352 g_test_add_vtable (const char *testpath,
1354 gconstpointer test_data,
1355 GTestFixtureFunc data_setup,
1356 GTestFixtureFunc fixture_test_func,
1357 GTestFixtureFunc data_teardown)
1363 g_return_if_fail (testpath != NULL);
1364 g_return_if_fail (testpath[0] == '/');
1365 g_return_if_fail (fixture_test_func != NULL);
1367 if (g_slist_find_custom (test_paths_skipped, testpath, (GCompareFunc)g_strcmp0))
1370 suite = g_test_get_root();
1371 segments = g_strsplit (testpath, "/", -1);
1372 for (ui = 0; segments[ui] != NULL; ui++)
1374 const char *seg = segments[ui];
1375 gboolean islast = segments[ui + 1] == NULL;
1376 if (islast && !seg[0])
1377 g_error ("invalid test case path: %s", testpath);
1379 continue; /* initial or duplicate slash */
1382 GTestSuite *csuite = g_test_create_suite (seg);
1383 g_test_suite_add_suite (suite, csuite);
1388 GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1389 g_test_suite_add (suite, tc);
1392 g_strfreev (segments);
1398 * Indicates that a test failed. This function can be called
1399 * multiple times from the same test. You can use this function
1400 * if your test failed in a recoverable way.
1402 * Do not use this function if the failure of a test could cause
1403 * other tests to malfunction.
1405 * Calling this function will not stop the test from running, you
1406 * need to return from the test function yourself. So you can
1407 * produce additional diagnostic messages or even continue running
1410 * If not called from inside a test, this function does nothing.
1417 test_run_success = FALSE;
1423 * The type used for test case functions.
1430 * @testpath: Slash-separated test case path name for the test.
1431 * @test_func: The test function to invoke for this test.
1433 * Create a new test case, similar to g_test_create_case(). However
1434 * the test is assumed to use no fixture, and test suites are automatically
1435 * created on the fly and added to the root fixture, based on the
1436 * slash-separated portions of @testpath.
1441 g_test_add_func (const char *testpath,
1442 GTestFunc test_func)
1444 g_return_if_fail (testpath != NULL);
1445 g_return_if_fail (testpath[0] == '/');
1446 g_return_if_fail (test_func != NULL);
1447 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1452 * @user_data: the data provided when registering the test
1454 * The type used for test case functions that take an extra pointer
1461 * g_test_add_data_func:
1462 * @testpath: Slash-separated test case path name for the test.
1463 * @test_data: Test data argument for the test function.
1464 * @test_func: The test function to invoke for this test.
1466 * Create a new test case, similar to g_test_create_case(). However
1467 * the test is assumed to use no fixture, and test suites are automatically
1468 * created on the fly and added to the root fixture, based on the
1469 * slash-separated portions of @testpath. The @test_data argument
1470 * will be passed as first argument to @test_func.
1475 g_test_add_data_func (const char *testpath,
1476 gconstpointer test_data,
1477 GTestDataFunc test_func)
1479 g_return_if_fail (testpath != NULL);
1480 g_return_if_fail (testpath[0] == '/');
1481 g_return_if_fail (test_func != NULL);
1482 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1486 * g_test_create_suite:
1487 * @suite_name: a name for the suite
1489 * Create a new test suite with the name @suite_name.
1491 * Returns: A newly allocated #GTestSuite instance.
1496 g_test_create_suite (const char *suite_name)
1499 g_return_val_if_fail (suite_name != NULL, NULL);
1500 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1501 g_return_val_if_fail (suite_name[0] != 0, NULL);
1502 ts = g_slice_new0 (GTestSuite);
1503 ts->name = g_strdup (suite_name);
1509 * @suite: a #GTestSuite
1510 * @test_case: a #GTestCase
1512 * Adds @test_case to @suite.
1517 g_test_suite_add (GTestSuite *suite,
1518 GTestCase *test_case)
1520 g_return_if_fail (suite != NULL);
1521 g_return_if_fail (test_case != NULL);
1523 suite->cases = g_slist_prepend (suite->cases, test_case);
1527 * g_test_suite_add_suite:
1528 * @suite: a #GTestSuite
1529 * @nestedsuite: another #GTestSuite
1531 * Adds @nestedsuite to @suite.
1536 g_test_suite_add_suite (GTestSuite *suite,
1537 GTestSuite *nestedsuite)
1539 g_return_if_fail (suite != NULL);
1540 g_return_if_fail (nestedsuite != NULL);
1542 suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1546 * g_test_queue_free:
1547 * @gfree_pointer: the pointer to be stored.
1549 * Enqueue a pointer to be released with g_free() during the next
1550 * teardown phase. This is equivalent to calling g_test_queue_destroy()
1551 * with a destroy callback of g_free().
1556 g_test_queue_free (gpointer gfree_pointer)
1559 g_test_queue_destroy (g_free, gfree_pointer);
1563 * g_test_queue_destroy:
1564 * @destroy_func: Destroy callback for teardown phase.
1565 * @destroy_data: Destroy callback data.
1567 * This function enqueus a callback @destroy_func to be executed
1568 * during the next test case teardown phase. This is most useful
1569 * to auto destruct allocted test resources at the end of a test run.
1570 * Resources are released in reverse queue order, that means enqueueing
1571 * callback A before callback B will cause B() to be called before
1572 * A() during teardown.
1577 g_test_queue_destroy (GDestroyNotify destroy_func,
1578 gpointer destroy_data)
1580 DestroyEntry *dentry;
1582 g_return_if_fail (destroy_func != NULL);
1584 dentry = g_slice_new0 (DestroyEntry);
1585 dentry->destroy_func = destroy_func;
1586 dentry->destroy_data = destroy_data;
1587 dentry->next = test_destroy_queue;
1588 test_destroy_queue = dentry;
1592 test_case_run (GTestCase *tc)
1594 gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1595 gboolean success = TRUE;
1597 test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1598 if (++test_run_count <= test_skip_count)
1599 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1600 else if (test_run_list)
1602 g_print ("%s\n", test_run_name);
1603 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1607 GTimer *test_run_timer = g_timer_new();
1608 long double largs[3];
1610 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1612 test_run_success = TRUE;
1613 g_test_log_set_fatal_handler (NULL, NULL);
1614 g_timer_start (test_run_timer);
1615 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1616 test_run_seed (test_run_seedstr);
1617 if (tc->fixture_setup)
1618 tc->fixture_setup (fixture, tc->test_data);
1619 tc->fixture_test (fixture, tc->test_data);
1621 while (test_destroy_queue)
1623 DestroyEntry *dentry = test_destroy_queue;
1624 test_destroy_queue = dentry->next;
1625 dentry->destroy_func (dentry->destroy_data);
1626 g_slice_free (DestroyEntry, dentry);
1628 if (tc->fixture_teardown)
1629 tc->fixture_teardown (fixture, tc->test_data);
1630 if (tc->fixture_size)
1632 g_timer_stop (test_run_timer);
1633 success = test_run_success;
1634 test_run_success = FALSE;
1635 largs[0] = success ? 0 : 1; /* OK */
1636 largs[1] = test_run_forks;
1637 largs[2] = g_timer_elapsed (test_run_timer, NULL);
1638 g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1639 g_timer_destroy (test_run_timer);
1641 g_free (test_run_name);
1642 test_run_name = old_name;
1643 g_free (test_uri_base);
1644 test_uri_base = old_base;
1650 g_test_run_suite_internal (GTestSuite *suite,
1654 gchar *rest, *old_name = test_run_name;
1655 GSList *slist, *reversed;
1657 g_return_val_if_fail (suite != NULL, -1);
1659 while (path[0] == '/')
1662 rest = strchr (path, '/');
1663 l = rest ? MIN (l, rest - path) : l;
1664 test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1665 reversed = g_slist_reverse (g_slist_copy (suite->cases));
1666 for (slist = reversed; slist; slist = slist->next)
1668 GTestCase *tc = slist->data;
1669 guint n = l ? strlen (tc->name) : 0;
1670 if (l == n && strncmp (path, tc->name, n) == 0)
1672 if (!test_case_run (tc))
1676 g_slist_free (reversed);
1677 reversed = g_slist_reverse (g_slist_copy (suite->suites));
1678 for (slist = reversed; slist; slist = slist->next)
1680 GTestSuite *ts = slist->data;
1681 guint n = l ? strlen (ts->name) : 0;
1682 if (l == n && strncmp (path, ts->name, n) == 0)
1683 n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
1685 g_slist_free (reversed);
1686 g_free (test_run_name);
1687 test_run_name = old_name;
1694 * @suite: a #GTestSuite
1696 * Execute the tests within @suite and all nested #GTestSuites.
1697 * The test suites to be executed are filtered according to
1698 * test path arguments (-p <replaceable>testpath</replaceable>)
1699 * as parsed by g_test_init().
1700 * g_test_run_suite() or g_test_run() may only be called once
1703 * Returns: 0 on success
1708 g_test_run_suite (GTestSuite *suite)
1712 g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1713 g_return_val_if_fail (g_test_run_once == TRUE, -1);
1715 g_test_run_once = FALSE;
1718 test_paths = g_slist_prepend (test_paths, "");
1721 const char *rest, *path = test_paths->data;
1722 guint l, n = strlen (suite->name);
1723 test_paths = g_slist_delete_link (test_paths, test_paths);
1724 while (path[0] == '/')
1726 if (!n) /* root suite, run unconditionally */
1728 n_bad += g_test_run_suite_internal (suite, path);
1731 /* regular suite, match path */
1732 rest = strchr (path, '/');
1734 l = rest ? MIN (l, rest - path) : l;
1735 if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1736 n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
1743 gtest_default_log_handler (const gchar *log_domain,
1744 GLogLevelFlags log_level,
1745 const gchar *message,
1746 gpointer unused_data)
1748 const gchar *strv[16];
1749 gboolean fatal = FALSE;
1755 strv[i++] = log_domain;
1758 if (log_level & G_LOG_FLAG_FATAL)
1760 strv[i++] = "FATAL-";
1763 if (log_level & G_LOG_FLAG_RECURSION)
1764 strv[i++] = "RECURSIVE-";
1765 if (log_level & G_LOG_LEVEL_ERROR)
1766 strv[i++] = "ERROR";
1767 if (log_level & G_LOG_LEVEL_CRITICAL)
1768 strv[i++] = "CRITICAL";
1769 if (log_level & G_LOG_LEVEL_WARNING)
1770 strv[i++] = "WARNING";
1771 if (log_level & G_LOG_LEVEL_MESSAGE)
1772 strv[i++] = "MESSAGE";
1773 if (log_level & G_LOG_LEVEL_INFO)
1775 if (log_level & G_LOG_LEVEL_DEBUG)
1776 strv[i++] = "DEBUG";
1778 strv[i++] = message;
1781 msg = g_strjoinv ("", (gchar**) strv);
1782 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
1783 g_log_default_handler (log_domain, log_level, message, unused_data);
1789 g_assertion_message (const char *domain,
1793 const char *message)
1799 message = "code should not be reached";
1800 g_snprintf (lstr, 32, "%d", line);
1801 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1802 "ERROR:", file, ":", lstr, ":",
1803 func, func[0] ? ":" : "",
1804 " ", message, NULL);
1805 g_printerr ("**\n%s\n", s);
1807 /* store assertion message in global variable, so that it can be found in a
1809 if (__glib_assert_msg != NULL)
1810 /* free the old one */
1811 free (__glib_assert_msg);
1812 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
1813 strcpy (__glib_assert_msg, s);
1815 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
1821 g_assertion_message_expr (const char *domain,
1827 char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1828 g_assertion_message (domain, file, line, func, s);
1833 g_assertion_message_cmpnum (const char *domain,
1846 case 'i': s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
1847 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;
1848 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
1849 /* ideally use: floats=%.7g double=%.17g */
1851 g_assertion_message (domain, file, line, func, s);
1856 g_assertion_message_cmpstr (const char *domain,
1865 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1866 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1867 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1870 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1873 g_assertion_message (domain, file, line, func, s);
1878 g_assertion_message_error (const char *domain,
1883 const GError *error,
1884 GQuark error_domain,
1889 /* This is used by both g_assert_error() and g_assert_no_error(), so there
1890 * are three cases: expected an error but got the wrong error, expected
1891 * an error but got no error, and expected no error but got an error.
1894 gstring = g_string_new ("assertion failed ");
1896 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
1897 g_quark_to_string (error_domain), error_code);
1899 g_string_append_printf (gstring, "(%s == NULL): ", expr);
1902 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
1903 g_quark_to_string (error->domain), error->code);
1905 g_string_append_printf (gstring, "%s is NULL", expr);
1907 g_assertion_message (domain, file, line, func, gstring->str);
1908 g_string_free (gstring, TRUE);
1913 * @str1: a C string or %NULL
1914 * @str2: another C string or %NULL
1916 * Compares @str1 and @str2 like strcmp(). Handles %NULL
1917 * gracefully by sorting it before non-%NULL strings.
1918 * Comparing two %NULL pointers returns 0.
1920 * Returns: -1, 0 or 1, if @str1 is <, == or > than @str2.
1925 g_strcmp0 (const char *str1,
1929 return -(str1 != str2);
1931 return str1 != str2;
1932 return strcmp (str1, str2);
1936 static int /* 0 on success */
1937 kill_child (int pid,
1942 if (patience >= 3) /* try graceful reap */
1944 if (waitpid (pid, status, WNOHANG) > 0)
1947 if (patience >= 2) /* try SIGHUP */
1950 if (waitpid (pid, status, WNOHANG) > 0)
1952 g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1953 if (waitpid (pid, status, WNOHANG) > 0)
1955 g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
1956 if (waitpid (pid, status, WNOHANG) > 0)
1958 g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
1959 if (waitpid (pid, status, WNOHANG) > 0)
1962 if (patience >= 1) /* try SIGTERM */
1964 kill (pid, SIGTERM);
1965 if (waitpid (pid, status, WNOHANG) > 0)
1967 g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
1968 if (waitpid (pid, status, WNOHANG) > 0)
1970 g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
1971 if (waitpid (pid, status, WNOHANG) > 0)
1975 kill (pid, SIGKILL);
1977 wr = waitpid (pid, status, 0);
1978 while (wr < 0 && errno == EINTR);
1984 g_string_must_read (GString *gstring,
1987 #define STRING_BUFFER_SIZE 4096
1988 char buf[STRING_BUFFER_SIZE];
1991 bytes = read (fd, buf, sizeof (buf));
1993 return 0; /* EOF, calling this function assumes data is available */
1996 g_string_append_len (gstring, buf, bytes);
1999 else if (bytes < 0 && errno == EINTR)
2001 else /* bytes < 0 */
2003 g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2004 return 1; /* ignore error after warning */
2009 g_string_write_out (GString *gstring,
2013 if (*stringpos < gstring->len)
2017 r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
2018 while (r < 0 && errno == EINTR);
2019 *stringpos += MAX (r, 0);
2024 test_trap_clear (void)
2026 test_trap_last_status = 0;
2027 test_trap_last_pid = 0;
2028 g_free (test_trap_last_stdout);
2029 test_trap_last_stdout = NULL;
2030 g_free (test_trap_last_stderr);
2031 test_trap_last_stderr = NULL;
2042 ret = dup2 (fd1, fd2);
2043 while (ret < 0 && errno == EINTR);
2048 test_time_stamp (void)
2052 g_get_current_time (&tv);
2054 stamp = stamp * 1000000 + tv.tv_usec;
2062 * @usec_timeout: Timeout for the forked test in micro seconds.
2063 * @test_trap_flags: Flags to modify forking behaviour.
2065 * Fork the current test program to execute a test case that might
2066 * not return or that might abort. The forked test case is aborted
2067 * and considered failing if its run time exceeds @usec_timeout.
2069 * The forking behavior can be configured with the #GTestTrapFlags flags.
2071 * In the following example, the test code forks, the forked child
2072 * process produces some sample output and exits successfully.
2073 * The forking parent process then asserts successful child program
2074 * termination and validates child program outputs.
2078 * test_fork_patterns (void)
2080 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2082 * g_print ("some stdout text: somagic17\n");
2083 * g_printerr ("some stderr text: semagic43\n");
2084 * exit (0); /* successful test run */
2086 * g_test_trap_assert_passed();
2087 * g_test_trap_assert_stdout ("*somagic17*");
2088 * g_test_trap_assert_stderr ("*semagic43*");
2092 * This function is implemented only on Unix platforms.
2094 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2099 g_test_trap_fork (guint64 usec_timeout,
2100 GTestTrapFlags test_trap_flags)
2103 gboolean pass_on_forked_log = FALSE;
2104 int stdout_pipe[2] = { -1, -1 };
2105 int stderr_pipe[2] = { -1, -1 };
2106 int stdtst_pipe[2] = { -1, -1 };
2108 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
2109 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
2110 signal (SIGCHLD, SIG_DFL);
2111 test_trap_last_pid = fork ();
2112 if (test_trap_last_pid < 0)
2113 g_error ("failed to fork test program: %s", g_strerror (errno));
2114 if (test_trap_last_pid == 0) /* child */
2117 close (stdout_pipe[0]);
2118 close (stderr_pipe[0]);
2119 close (stdtst_pipe[0]);
2120 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2121 fd0 = open ("/dev/null", O_RDONLY);
2122 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2123 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
2126 if (stdout_pipe[1] >= 3)
2127 close (stdout_pipe[1]);
2128 if (stderr_pipe[1] >= 3)
2129 close (stderr_pipe[1]);
2130 test_log_fd = stdtst_pipe[1];
2135 GString *sout = g_string_new (NULL);
2136 GString *serr = g_string_new (NULL);
2138 int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
2140 close (stdout_pipe[1]);
2141 close (stderr_pipe[1]);
2142 close (stdtst_pipe[1]);
2143 sstamp = test_time_stamp();
2144 /* read data until we get EOF on all pipes */
2145 while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
2151 if (stdout_pipe[0] >= 0)
2152 FD_SET (stdout_pipe[0], &fds);
2153 if (stderr_pipe[0] >= 0)
2154 FD_SET (stderr_pipe[0], &fds);
2155 if (stdtst_pipe[0] >= 0)
2156 FD_SET (stdtst_pipe[0], &fds);
2158 tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
2159 ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
2160 if (ret < 0 && errno != EINTR)
2162 g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2165 if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
2166 g_string_must_read (sout, stdout_pipe[0]) == 0)
2168 close (stdout_pipe[0]);
2169 stdout_pipe[0] = -1;
2171 if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
2172 g_string_must_read (serr, stderr_pipe[0]) == 0)
2174 close (stderr_pipe[0]);
2175 stderr_pipe[0] = -1;
2177 if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
2179 guint8 buffer[4096];
2180 gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
2181 if (r > 0 && test_log_fd > 0)
2183 l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
2184 while (l < 0 && errno == EINTR);
2185 if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
2187 close (stdtst_pipe[0]);
2188 stdtst_pipe[0] = -1;
2191 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
2192 g_string_write_out (sout, 1, &soutpos);
2193 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
2194 g_string_write_out (serr, 2, &serrpos);
2197 guint64 nstamp = test_time_stamp();
2199 sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
2200 if (usec_timeout < nstamp - sstamp)
2202 /* timeout reached, need to abort the child now */
2203 kill_child (test_trap_last_pid, &status, 3);
2204 test_trap_last_status = 1024; /* timeout */
2205 if (0 && WIFSIGNALED (status))
2206 g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
2212 if (stdout_pipe[0] != -1)
2213 close (stdout_pipe[0]);
2214 if (stderr_pipe[0] != -1)
2215 close (stderr_pipe[0]);
2216 if (stdtst_pipe[0] != -1)
2217 close (stdtst_pipe[0]);
2222 wr = waitpid (test_trap_last_pid, &status, 0);
2223 while (wr < 0 && errno == EINTR);
2224 if (WIFEXITED (status)) /* normal exit */
2225 test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
2226 else if (WIFSIGNALED (status))
2227 test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
2228 else /* WCOREDUMP (status) */
2229 test_trap_last_status = 512; /* coredump */
2231 test_trap_last_stdout = g_string_free (sout, FALSE);
2232 test_trap_last_stderr = g_string_free (serr, FALSE);
2236 g_message ("Not implemented: g_test_trap_fork");
2243 * g_test_trap_has_passed:
2245 * Check the result of the last g_test_trap_fork() call.
2247 * Returns: %TRUE if the last forked child terminated successfully.
2252 g_test_trap_has_passed (void)
2254 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
2258 * g_test_trap_reached_timeout:
2260 * Check the result of the last g_test_trap_fork() call.
2262 * Returns: %TRUE if the last forked child got killed due to a fork timeout.
2267 g_test_trap_reached_timeout (void)
2269 return 0 != (test_trap_last_status & 1024); /* timeout flag */
2273 g_test_trap_assertions (const char *domain,
2277 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
2278 const char *pattern)
2281 gboolean must_pass = assertion_flags == 0;
2282 gboolean must_fail = assertion_flags == 1;
2283 gboolean match_result = 0 == (assertion_flags & 1);
2284 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
2285 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
2286 const char *match_error = match_result ? "failed to match" : "contains invalid match";
2287 if (test_trap_last_pid == 0)
2288 g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
2289 if (must_pass && !g_test_trap_has_passed())
2291 char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
2292 g_assertion_message (domain, file, line, func, msg);
2295 if (must_fail && g_test_trap_has_passed())
2297 char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
2298 g_assertion_message (domain, file, line, func, msg);
2301 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
2303 char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
2304 g_assertion_message (domain, file, line, func, msg);
2307 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
2309 char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
2310 g_assertion_message (domain, file, line, func, msg);
2317 gstring_overwrite_int (GString *gstring,
2321 vuint = g_htonl (vuint);
2322 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
2326 gstring_append_int (GString *gstring,
2329 vuint = g_htonl (vuint);
2330 g_string_append_len (gstring, (const gchar*) &vuint, 4);
2334 gstring_append_double (GString *gstring,
2337 union { double vdouble; guint64 vuint64; } u;
2338 u.vdouble = vdouble;
2339 u.vuint64 = GUINT64_TO_BE (u.vuint64);
2340 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
2344 g_test_log_dump (GTestLogMsg *msg,
2347 GString *gstring = g_string_sized_new (1024);
2349 gstring_append_int (gstring, 0); /* message length */
2350 gstring_append_int (gstring, msg->log_type);
2351 gstring_append_int (gstring, msg->n_strings);
2352 gstring_append_int (gstring, msg->n_nums);
2353 gstring_append_int (gstring, 0); /* reserved */
2354 for (ui = 0; ui < msg->n_strings; ui++)
2356 guint l = strlen (msg->strings[ui]);
2357 gstring_append_int (gstring, l);
2358 g_string_append_len (gstring, msg->strings[ui], l);
2360 for (ui = 0; ui < msg->n_nums; ui++)
2361 gstring_append_double (gstring, msg->nums[ui]);
2362 *len = gstring->len;
2363 gstring_overwrite_int (gstring, 0, *len); /* message length */
2364 return (guint8*) g_string_free (gstring, FALSE);
2367 static inline long double
2368 net_double (const gchar **ipointer)
2370 union { guint64 vuint64; double vdouble; } u;
2371 guint64 aligned_int64;
2372 memcpy (&aligned_int64, *ipointer, 8);
2374 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
2378 static inline guint32
2379 net_int (const gchar **ipointer)
2381 guint32 aligned_int;
2382 memcpy (&aligned_int, *ipointer, 4);
2384 return g_ntohl (aligned_int);
2388 g_test_log_extract (GTestLogBuffer *tbuffer)
2390 const gchar *p = tbuffer->data->str;
2393 if (tbuffer->data->len < 4 * 5)
2395 mlength = net_int (&p);
2396 if (tbuffer->data->len < mlength)
2398 msg.log_type = net_int (&p);
2399 msg.n_strings = net_int (&p);
2400 msg.n_nums = net_int (&p);
2401 if (net_int (&p) == 0)
2404 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
2405 msg.nums = g_new0 (long double, msg.n_nums);
2406 for (ui = 0; ui < msg.n_strings; ui++)
2408 guint sl = net_int (&p);
2409 msg.strings[ui] = g_strndup (p, sl);
2412 for (ui = 0; ui < msg.n_nums; ui++)
2413 msg.nums[ui] = net_double (&p);
2414 if (p <= tbuffer->data->str + mlength)
2416 g_string_erase (tbuffer->data, 0, mlength);
2417 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
2422 g_strfreev (msg.strings);
2423 g_error ("corrupt log stream from test program");
2428 * g_test_log_buffer_new:
2430 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2433 g_test_log_buffer_new (void)
2435 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
2436 tb->data = g_string_sized_new (1024);
2441 * g_test_log_buffer_free
2443 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2446 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
2448 g_return_if_fail (tbuffer != NULL);
2449 while (tbuffer->msgs)
2450 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
2451 g_string_free (tbuffer->data, TRUE);
2456 * g_test_log_buffer_push
2458 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2461 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
2463 const guint8 *bytes)
2465 g_return_if_fail (tbuffer != NULL);
2468 gboolean more_messages;
2469 g_return_if_fail (bytes != NULL);
2470 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
2472 more_messages = g_test_log_extract (tbuffer);
2473 while (more_messages);
2478 * g_test_log_buffer_pop:
2480 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
2483 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
2485 GTestLogMsg *msg = NULL;
2486 g_return_val_if_fail (tbuffer != NULL, NULL);
2489 GSList *slist = g_slist_last (tbuffer->msgs);
2491 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
2497 * g_test_log_msg_free:
2499 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2502 g_test_log_msg_free (GTestLogMsg *tmsg)
2504 g_return_if_fail (tmsg != NULL);
2505 g_strfreev (tmsg->strings);
2506 g_free (tmsg->nums);
2510 /* --- macros docs START --- */
2513 * @testpath: The test path for a new test case.
2514 * @Fixture: The type of a fixture data structure.
2515 * @tdata: Data argument for the test functions.
2516 * @fsetup: The function to set up the fixture data.
2517 * @ftest: The actual test function.
2518 * @fteardown: The function to tear down the fixture data.
2520 * Hook up a new test case at @testpath, similar to g_test_add_func().
2521 * A fixture data structure with setup and teardown function may be provided
2522 * though, similar to g_test_create_case().
2523 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2524 * fteardown() callbacks can expect a @Fixture pointer as first argument in
2525 * a type safe manner.
2529 /* --- macros docs END --- */