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 may provoke assertions and other formally-undefined
147 * behaviour under g_test_trap_fork(), to verify that appropriate warnings
148 * are given. It can be useful to turn this off if running tests under
151 * Returns: %TRUE if tests may provoke programming errors
157 * Returns %TRUE if tests are run in verbose mode.
158 * The default is neither g_test_verbose() nor g_test_quiet().
160 * Returns: %TRUE if in verbose mode
166 * Returns %TRUE if tests are run in quiet mode.
167 * The default is neither g_test_verbose() nor g_test_quiet().
169 * Returns: %TRUE if in quiet mode
173 * g_test_queue_unref:
174 * @gobject: the object to unref
176 * Enqueue an object to be released with g_object_unref() during
177 * the next teardown phase. This is equivalent to calling
178 * g_test_queue_destroy() with a destroy callback of g_object_unref().
185 * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
186 * <filename>/dev/null</filename> so it cannot be observed on the
187 * console during test runs. The actual output is still captured
188 * though to allow later tests with g_test_trap_assert_stdout().
189 * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
190 * <filename>/dev/null</filename> so it cannot be observed on the
191 * console during test runs. The actual output is still captured
192 * though to allow later tests with g_test_trap_assert_stderr().
193 * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
194 * forked child process is shared with stdin of its parent process.
195 * It is redirected to <filename>/dev/null</filename> otherwise.
197 * Test traps are guards around forked tests.
198 * These flags determine what traps to set.
202 * g_test_trap_assert_passed:
204 * Assert that the last forked test passed.
205 * See g_test_trap_fork().
211 * g_test_trap_assert_failed:
213 * Assert that the last forked test failed.
214 * See g_test_trap_fork().
220 * g_test_trap_assert_stdout:
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 matches
225 * @soutpattern. See g_test_trap_fork().
231 * g_test_trap_assert_stdout_unmatched:
232 * @soutpattern: a glob-style
233 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
235 * Assert that the stdout output of the last forked test
236 * does not match @soutpattern. See g_test_trap_fork().
242 * g_test_trap_assert_stderr:
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 * matches @serrpattern. See g_test_trap_fork().
253 * g_test_trap_assert_stderr_unmatched:
254 * @serrpattern: a glob-style
255 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
257 * Assert that the stderr output of the last forked test
258 * does not match @serrpattern. See g_test_trap_fork().
266 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
267 * for details on test case random numbers.
274 * @expr: the expression to check
276 * Debugging macro to terminate the application if the assertion
277 * fails. If the assertion fails (i.e. the expression is not true),
278 * an error message is logged and the 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.
285 * g_assert_not_reached:
287 * Debugging macro to terminate the application if it is ever
288 * reached. If it is reached, an error message is logged and the
289 * application is terminated.
291 * The macro can be turned off in final releases of code by defining
292 * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
297 * @s1: a string (may be %NULL)
298 * @cmp: The comparison operator to use.
299 * One of ==, !=, <, >, <=, >=.
300 * @s2: another string (may be %NULL)
302 * Debugging macro to terminate the application with a warning
303 * message if a string comparison fails. The strings are compared
306 * The effect of <literal>g_assert_cmpstr (s1, op, s2)</literal> is
307 * the same as <literal>g_assert (g_strcmp0 (s1, s2) op 0)</literal>.
308 * The advantage of this macro is that it can produce a message that
309 * includes the actual values of @s1 and @s2.
312 * g_assert_cmpstr (mystring, ==, "fubar");
321 * @cmp: The comparison operator to use.
322 * One of ==, !=, <, >, <=, >=.
323 * @n2: another integer
325 * Debugging macro to terminate the application with a warning
326 * message if an integer comparison fails.
328 * The effect of <literal>g_assert_cmpint (n1, op, n2)</literal> is
329 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
330 * of this macro is that it can produce a message that includes the
331 * actual values of @n1 and @n2.
338 * @n1: an unsigned integer
339 * @cmp: The comparison operator to use.
340 * One of ==, !=, <, >, <=, >=.
341 * @n2: another unsigned integer
343 * Debugging macro to terminate the application with a warning
344 * message if an unsigned integer comparison fails.
346 * The effect of <literal>g_assert_cmpuint (n1, op, n2)</literal> is
347 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
348 * of this macro is that it can produce a message that includes the
349 * actual values of @n1 and @n2.
356 * @n1: an unsigned integer
357 * @cmp: The comparison operator to use.
358 * One of ==, !=, <, >, <=, >=.
359 * @n2: another unsigned integer
361 * Debugging macro to terminate the application with a warning
362 * message if an unsigned integer comparison fails.
364 * This is a variant of g_assert_cmpuint() that displays the numbers
365 * in hexadecimal notation in the message.
372 * @n1: an floating point number
373 * @cmp: The comparison operator to use.
374 * One of ==, !=, <, >, <=, >=.
375 * @n2: another floating point number
377 * Debugging macro to terminate the application with a warning
378 * message if a floating point number comparison fails.
380 * The effect of <literal>g_assert_cmpfloat (n1, op, n2)</literal> is
381 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
382 * of this macro is that it can produce a message that includes the
383 * actual values of @n1 and @n2.
390 * @err: a #GError, possibly %NULL
392 * Debugging macro to terminate the application with a warning
393 * message if a method has returned a #GError.
395 * The effect of <literal>g_assert_no_error (err)</literal> is
396 * the same as <literal>g_assert (err == NULL)</literal>. The advantage
397 * of this macro is that it can produce a message that includes
398 * the error message and code.
405 * @err: a #GError, possibly %NULL
406 * @dom: the expected error domain (a #GQuark)
407 * @c: the expected error code
409 * Debugging macro to terminate the application with a warning
410 * message if a method has not returned the correct #GError.
412 * The effect of <literal>g_assert_error (err, dom, c)</literal> is
413 * the same as <literal>g_assert (err != NULL && err->domain
414 * == dom && err->code == c)</literal>. The advantage of this
415 * macro is that it can produce a message that includes the incorrect
416 * error message and code.
418 * This can only be used to test for a specific error. If you want to
419 * test that @err is set, but don't care what it's set to, just use
420 * <literal>g_assert (err != NULL)</literal>
428 * An opaque structure representing a test case.
434 * An opaque structure representing a test suite.
438 /* Global variable for storing assertion messages; this is the counterpart to
439 * glibc's (private) __abort_msg variable, and allows developers and crash
440 * analysis systems like Apport and ABRT to fish out assertion messages from
441 * core dumps, instead of having to catch them on screen output.
443 char *__glib_assert_msg = NULL;
445 /* --- structures --- */
450 void (*fixture_setup) (void*, gconstpointer);
451 void (*fixture_test) (void*, gconstpointer);
452 void (*fixture_teardown) (void*, gconstpointer);
461 typedef struct DestroyEntry DestroyEntry;
465 GDestroyNotify destroy_func;
466 gpointer destroy_data;
469 /* --- prototypes --- */
470 static void test_run_seed (const gchar *rseed);
471 static void test_trap_clear (void);
472 static guint8* g_test_log_dump (GTestLogMsg *msg,
474 static void gtest_default_log_handler (const gchar *log_domain,
475 GLogLevelFlags log_level,
476 const gchar *message,
477 gpointer unused_data);
480 /* --- variables --- */
481 static int test_log_fd = -1;
482 static gboolean test_mode_fatal = TRUE;
483 static gboolean g_test_run_once = TRUE;
484 static gboolean test_run_list = FALSE;
485 static gchar *test_run_seedstr = NULL;
486 static GRand *test_run_rand = NULL;
487 static gchar *test_run_name = "";
488 static guint test_run_forks = 0;
489 static guint test_run_count = 0;
490 static guint test_run_success = FALSE;
491 static guint test_skip_count = 0;
492 static GTimer *test_user_timer = NULL;
493 static double test_user_stamp = 0;
494 static GSList *test_paths = NULL;
495 static GSList *test_paths_skipped = NULL;
496 static GTestSuite *test_suite_root = NULL;
497 static int test_trap_last_status = 0;
498 static int test_trap_last_pid = 0;
499 static char *test_trap_last_stdout = NULL;
500 static char *test_trap_last_stderr = NULL;
501 static char *test_uri_base = NULL;
502 static gboolean test_debug_log = FALSE;
503 static DestroyEntry *test_destroy_queue = NULL;
504 static GTestConfig mutable_test_config_vars = {
505 FALSE, /* test_initialized */
506 TRUE, /* test_quick */
507 FALSE, /* test_perf */
508 FALSE, /* test_verbose */
509 FALSE, /* test_quiet */
510 TRUE, /* test_undefined */
512 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
514 /* --- functions --- */
516 g_test_log_type_name (GTestLogType log_type)
520 case G_TEST_LOG_NONE: return "none";
521 case G_TEST_LOG_ERROR: return "error";
522 case G_TEST_LOG_START_BINARY: return "binary";
523 case G_TEST_LOG_LIST_CASE: return "list";
524 case G_TEST_LOG_SKIP_CASE: return "skip";
525 case G_TEST_LOG_START_CASE: return "start";
526 case G_TEST_LOG_STOP_CASE: return "stop";
527 case G_TEST_LOG_MIN_RESULT: return "minperf";
528 case G_TEST_LOG_MAX_RESULT: return "maxperf";
529 case G_TEST_LOG_MESSAGE: return "message";
535 g_test_log_send (guint n_bytes,
536 const guint8 *buffer)
538 if (test_log_fd >= 0)
542 r = write (test_log_fd, buffer, n_bytes);
543 while (r < 0 && errno == EINTR);
547 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
550 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
551 msg = g_test_log_buffer_pop (lbuffer);
552 g_warn_if_fail (msg != NULL);
553 g_warn_if_fail (lbuffer->data->len == 0);
554 g_test_log_buffer_free (lbuffer);
556 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
557 for (ui = 0; ui < msg->n_strings; ui++)
558 g_printerr (":{%s}", msg->strings[ui]);
562 for (ui = 0; ui < msg->n_nums; ui++)
563 g_printerr ("%s%.16Lg", ui ? ";" : "", msg->nums[ui]);
566 g_printerr (":LOG*}\n");
567 g_test_log_msg_free (msg);
572 g_test_log (GTestLogType lbit,
573 const gchar *string1,
574 const gchar *string2,
578 gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
580 gchar *astrings[3] = { NULL, NULL, NULL };
586 case G_TEST_LOG_START_BINARY:
587 if (g_test_verbose())
588 g_print ("GTest: random seed: %s\n", string2);
590 case G_TEST_LOG_STOP_CASE:
591 if (g_test_verbose())
592 g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
593 else if (!g_test_quiet())
594 g_print ("%s\n", fail ? "FAIL" : "OK");
595 if (fail && test_mode_fatal)
598 case G_TEST_LOG_MIN_RESULT:
599 if (g_test_verbose())
600 g_print ("(MINPERF:%s)\n", string1);
602 case G_TEST_LOG_MAX_RESULT:
603 if (g_test_verbose())
604 g_print ("(MAXPERF:%s)\n", string1);
606 case G_TEST_LOG_MESSAGE:
607 if (g_test_verbose())
608 g_print ("(MSG: %s)\n", string1);
614 msg.n_strings = (string1 != NULL) + (string1 && string2);
615 msg.strings = astrings;
616 astrings[0] = (gchar*) string1;
617 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
620 dbuffer = g_test_log_dump (&msg, &dbufferlen);
621 g_test_log_send (dbufferlen, dbuffer);
626 case G_TEST_LOG_START_CASE:
627 if (g_test_verbose())
628 g_print ("GTest: run: %s\n", string1);
629 else if (!g_test_quiet())
630 g_print ("%s: ", string1);
636 /* We intentionally parse the command line without GOptionContext
637 * because otherwise you would never be able to test it.
640 parse_args (gint *argc_p,
643 guint argc = *argc_p;
644 gchar **argv = *argv_p;
646 /* parse known args */
647 for (i = 1; i < argc; i++)
649 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
651 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
652 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
653 g_log_set_always_fatal (fatal_mask);
656 else if (strcmp (argv[i], "--keep-going") == 0 ||
657 strcmp (argv[i], "-k") == 0)
659 test_mode_fatal = FALSE;
662 else if (strcmp (argv[i], "--debug-log") == 0)
664 test_debug_log = TRUE;
667 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
669 gchar *equal = argv[i] + 12;
671 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
672 else if (i + 1 < argc)
675 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
679 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
681 gchar *equal = argv[i] + 16;
683 test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
684 else if (i + 1 < argc)
687 test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
691 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
693 gchar *equal = argv[i] + 2;
695 test_paths = g_slist_prepend (test_paths, equal + 1);
696 else if (i + 1 < argc)
699 test_paths = g_slist_prepend (test_paths, argv[i]);
703 else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
705 gchar *equal = argv[i] + 2;
707 test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
708 else if (i + 1 < argc)
711 test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
715 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
717 gchar *equal = argv[i] + 2;
718 const gchar *mode = "";
721 else if (i + 1 < argc)
726 if (strcmp (mode, "perf") == 0)
727 mutable_test_config_vars.test_perf = TRUE;
728 else if (strcmp (mode, "slow") == 0)
729 mutable_test_config_vars.test_quick = FALSE;
730 else if (strcmp (mode, "thorough") == 0)
731 mutable_test_config_vars.test_quick = FALSE;
732 else if (strcmp (mode, "quick") == 0)
734 mutable_test_config_vars.test_quick = TRUE;
735 mutable_test_config_vars.test_perf = FALSE;
737 else if (strcmp (mode, "undefined") == 0)
738 mutable_test_config_vars.test_undefined = TRUE;
739 else if (strcmp (mode, "no-undefined") == 0)
740 mutable_test_config_vars.test_undefined = FALSE;
742 g_error ("unknown test mode: -m %s", mode);
745 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
747 mutable_test_config_vars.test_quiet = TRUE;
748 mutable_test_config_vars.test_verbose = FALSE;
751 else if (strcmp ("--verbose", argv[i]) == 0)
753 mutable_test_config_vars.test_quiet = FALSE;
754 mutable_test_config_vars.test_verbose = TRUE;
757 else if (strcmp ("-l", argv[i]) == 0)
759 test_run_list = TRUE;
762 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
764 gchar *equal = argv[i] + 6;
766 test_run_seedstr = equal + 1;
767 else if (i + 1 < argc)
770 test_run_seedstr = argv[i];
774 else if (strcmp ("-?", argv[i]) == 0 || strcmp ("--help", argv[i]) == 0)
777 " %s [OPTION...]\n\n"
779 " -?, --help Show help options\n"
781 " -l List test cases available in a test executable\n"
782 " -seed=RANDOMSEED Provide a random seed to reproduce test\n"
783 " runs using random numbers\n"
784 " --verbose Run tests verbosely\n"
785 " -q, --quiet Run tests quietly\n"
786 " -p TESTPATH execute all tests matching TESTPATH\n"
787 " -s TESTPATH skip all tests matching TESTPATH\n"
788 " -m {perf|slow|thorough|quick} Execute tests according modes\n"
789 " -m {undefined|no-undefined} Execute tests according modes\n"
790 " --debug-log debug test logging output\n"
791 " -k, --keep-going gtester-specific argument\n"
792 " --GTestLogFD=N gtester-specific argument\n"
793 " --GTestSkipCount=N gtester-specific argument\n",
800 for (i = 1; i < argc; i++)
812 * @argc: Address of the @argc parameter of the main() function.
813 * Changed if any arguments were handled.
814 * @argv: Address of the @argv parameter of main().
815 * Any parameters understood by g_test_init() stripped before return.
816 * @...: Reserved for future extension. Currently, you must pass %NULL.
818 * Initialize the GLib testing framework, e.g. by seeding the
819 * test random number generator, the name for g_get_prgname()
820 * and parsing test related command line args.
821 * So far, the following arguments are understood:
824 * <term><option>-l</option></term>
826 * list test cases available in a test executable.
830 * <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
832 * provide a random seed to reproduce test runs using random numbers.
836 * <term><option>--verbose</option></term>
837 * <listitem><para>run tests verbosely.</para></listitem>
840 * <term><option>-q</option>, <option>--quiet</option></term>
841 * <listitem><para>run tests quietly.</para></listitem>
844 * <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
846 * execute all tests matching <replaceable>TESTPATH</replaceable>.
850 * <term><option>-m {perf|slow|thorough|quick|undefined|no-undefined}</option></term>
852 * execute tests according to these test modes:
857 * performance tests, may take long and report results.
861 * <term>slow, thorough</term>
863 * slow and thorough tests, may take quite long and
870 * quick tests, should run really quickly and give good coverage.
874 * <term>undefined</term>
876 * tests for undefined behaviour, may provoke programming errors
877 * under g_test_trap_fork() to check that appropriate assertions
878 * or warnings are given
882 * <term>no-undefined</term>
884 * avoid tests for undefined behaviour
891 * <term><option>--debug-log</option></term>
892 * <listitem><para>debug test logging output.</para></listitem>
895 * <term><option>-k</option>, <option>--keep-going</option></term>
896 * <listitem><para>gtester-specific argument.</para></listitem>
899 * <term><option>--GTestLogFD <replaceable>N</replaceable></option></term>
900 * <listitem><para>gtester-specific argument.</para></listitem>
903 * <term><option>--GTestSkipCount <replaceable>N</replaceable></option></term>
904 * <listitem><para>gtester-specific argument.</para></listitem>
911 g_test_init (int *argc,
915 static char seedstr[4 + 4 * 8 + 1];
918 /* make warnings and criticals fatal for all test programs */
919 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
920 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
921 g_log_set_always_fatal (fatal_mask);
922 /* check caller args */
923 g_return_if_fail (argc != NULL);
924 g_return_if_fail (argv != NULL);
925 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
926 mutable_test_config_vars.test_initialized = TRUE;
928 va_start (args, argv);
929 vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
931 g_return_if_fail (vararg1 == NULL);
933 /* setup random seed string */
934 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
935 test_run_seedstr = seedstr;
937 /* parse args, sets up mode, changes seed, etc. */
938 parse_args (argc, argv);
939 if (!g_get_prgname())
940 g_set_prgname ((*argv)[0]);
942 /* verify GRand reliability, needed for reliable seeds */
945 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
946 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
947 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
948 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
949 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
953 /* check rand seed */
954 test_run_seed (test_run_seedstr);
956 /* report program start */
957 g_log_set_default_handler (gtest_default_log_handler, NULL);
958 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
962 test_run_seed (const gchar *rseed)
964 guint seed_failed = 0;
966 g_rand_free (test_run_rand);
967 test_run_rand = NULL;
968 while (strchr (" \t\v\r\n\f", *rseed))
970 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
972 const char *s = rseed + 4;
973 if (strlen (s) >= 32) /* require 4 * 8 chars */
975 guint32 seedarray[4];
976 gchar *p, hexbuf[9] = { 0, };
977 memcpy (hexbuf, s + 0, 8);
978 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
979 seed_failed += p != NULL && *p != 0;
980 memcpy (hexbuf, s + 8, 8);
981 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
982 seed_failed += p != NULL && *p != 0;
983 memcpy (hexbuf, s + 16, 8);
984 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
985 seed_failed += p != NULL && *p != 0;
986 memcpy (hexbuf, s + 24, 8);
987 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
988 seed_failed += p != NULL && *p != 0;
991 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
996 g_error ("Unknown or invalid random seed: %s", rseed);
1002 * Get a reproducible random integer number.
1004 * The random numbers generated by the g_test_rand_*() family of functions
1005 * change with every new test program start, unless the --seed option is
1006 * given when starting test programs.
1008 * For individual test cases however, the random number generator is
1009 * reseeded, to avoid dependencies between tests and to make --seed
1010 * effective for all test cases.
1012 * Returns: a random number from the seeded random number generator.
1017 g_test_rand_int (void)
1019 return g_rand_int (test_run_rand);
1023 * g_test_rand_int_range:
1024 * @begin: the minimum value returned by this function
1025 * @end: the smallest value not to be returned by this function
1027 * Get a reproducible random integer number out of a specified range,
1028 * see g_test_rand_int() for details on test case random numbers.
1030 * Returns: a number with @begin <= number < @end.
1035 g_test_rand_int_range (gint32 begin,
1038 return g_rand_int_range (test_run_rand, begin, end);
1042 * g_test_rand_double:
1044 * Get a reproducible random floating point number,
1045 * see g_test_rand_int() for details on test case random numbers.
1047 * Returns: a random number from the seeded random number generator.
1052 g_test_rand_double (void)
1054 return g_rand_double (test_run_rand);
1058 * g_test_rand_double_range:
1059 * @range_start: the minimum value returned by this function
1060 * @range_end: the minimum value not returned by this function
1062 * Get a reproducible random floating pointer number out of a specified range,
1063 * see g_test_rand_int() for details on test case random numbers.
1065 * Returns: a number with @range_start <= number < @range_end.
1070 g_test_rand_double_range (double range_start,
1073 return g_rand_double_range (test_run_rand, range_start, range_end);
1077 * g_test_timer_start:
1079 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1080 * to be done. Call this function again to restart the timer.
1085 g_test_timer_start (void)
1087 if (!test_user_timer)
1088 test_user_timer = g_timer_new();
1089 test_user_stamp = 0;
1090 g_timer_start (test_user_timer);
1094 * g_test_timer_elapsed:
1096 * Get the time since the last start of the timer with g_test_timer_start().
1098 * Returns: the time since the last start of the timer, as a double
1103 g_test_timer_elapsed (void)
1105 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1106 return test_user_stamp;
1110 * g_test_timer_last:
1112 * Report the last result of g_test_timer_elapsed().
1114 * Returns: the last result of g_test_timer_elapsed(), as a double
1119 g_test_timer_last (void)
1121 return test_user_stamp;
1125 * g_test_minimized_result:
1126 * @minimized_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 minimize the reported
1132 * quantities (smaller values are better than larger ones),
1133 * this and @minimized_quantity can determine sorting
1134 * order for test result reports.
1139 g_test_minimized_result (double minimized_quantity,
1143 long double largs = minimized_quantity;
1147 va_start (args, format);
1148 buffer = g_strdup_vprintf (format, args);
1151 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1156 * g_test_maximized_result:
1157 * @maximized_quantity: the reported value
1158 * @format: the format string of the report message
1159 * @...: arguments to pass to the printf() function
1161 * Report the result of a performance or measurement test.
1162 * The test should generally strive to maximize the reported
1163 * quantities (larger values are better than smaller ones),
1164 * this and @maximized_quantity can determine sorting
1165 * order for test result reports.
1170 g_test_maximized_result (double maximized_quantity,
1174 long double largs = maximized_quantity;
1178 va_start (args, format);
1179 buffer = g_strdup_vprintf (format, args);
1182 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1188 * @format: the format string
1189 * @...: printf-like arguments to @format
1191 * Add a message to the test report.
1196 g_test_message (const char *format,
1202 va_start (args, format);
1203 buffer = g_strdup_vprintf (format, args);
1206 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1212 * @uri_pattern: the base pattern for bug URIs
1214 * Specify the base URI for bug reports.
1216 * The base URI is used to construct bug report messages for
1217 * g_test_message() when g_test_bug() is called.
1218 * Calling this function outside of a test case sets the
1219 * default base URI for all test cases. Calling it from within
1220 * a test case changes the base URI for the scope of the test
1222 * Bug URIs are constructed by appending a bug specific URI
1223 * portion to @uri_pattern, or by replacing the special string
1224 * '\%s' within @uri_pattern if that is present.
1229 g_test_bug_base (const char *uri_pattern)
1231 g_free (test_uri_base);
1232 test_uri_base = g_strdup (uri_pattern);
1237 * @bug_uri_snippet: Bug specific bug tracker URI portion.
1239 * This function adds a message to test reports that
1240 * associates a bug URI with a test case.
1241 * Bug URIs are constructed from a base URI set with g_test_bug_base()
1242 * and @bug_uri_snippet.
1247 g_test_bug (const char *bug_uri_snippet)
1251 g_return_if_fail (test_uri_base != NULL);
1252 g_return_if_fail (bug_uri_snippet != NULL);
1254 c = strstr (test_uri_base, "%s");
1257 char *b = g_strndup (test_uri_base, c - test_uri_base);
1258 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1260 g_test_message ("Bug Reference: %s", s);
1264 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1270 * Get the toplevel test suite for the test path API.
1272 * Returns: the toplevel #GTestSuite
1277 g_test_get_root (void)
1279 if (!test_suite_root)
1281 test_suite_root = g_test_create_suite ("root");
1282 g_free (test_suite_root->name);
1283 test_suite_root->name = g_strdup ("");
1286 return test_suite_root;
1292 * Runs all tests under the toplevel suite which can be retrieved
1293 * with g_test_get_root(). Similar to g_test_run_suite(), the test
1294 * cases to be run are filtered according to
1295 * test path arguments (-p <replaceable>testpath</replaceable>) as
1296 * parsed by g_test_init().
1297 * g_test_run_suite() or g_test_run() may only be called once
1300 * Returns: 0 on success
1307 return g_test_run_suite (g_test_get_root());
1311 * g_test_create_case:
1312 * @test_name: the name for the test case
1313 * @data_size: the size of the fixture data structure
1314 * @test_data: test data argument for the test functions
1315 * @data_setup: the function to set up the fixture data
1316 * @data_test: the actual test function
1317 * @data_teardown: the function to teardown the fixture data
1319 * Create a new #GTestCase, named @test_name, this API is fairly
1320 * low level, calling g_test_add() or g_test_add_func() is preferable.
1321 * When this test is executed, a fixture structure of size @data_size
1322 * will be allocated and filled with 0s. Then @data_setup is called
1323 * to initialize the fixture. After fixture setup, the actual test
1324 * function @data_test is called. Once the test run completed, the
1325 * fixture structure is torn down by calling @data_teardown and
1326 * after that the memory is released.
1328 * Splitting up a test run into fixture setup, test function and
1329 * fixture teardown is most usful if the same fixture is used for
1330 * multiple tests. In this cases, g_test_create_case() will be
1331 * called with the same fixture, but varying @test_name and
1332 * @data_test arguments.
1334 * Returns: a newly allocated #GTestCase.
1339 g_test_create_case (const char *test_name,
1341 gconstpointer test_data,
1342 GTestFixtureFunc data_setup,
1343 GTestFixtureFunc data_test,
1344 GTestFixtureFunc data_teardown)
1348 g_return_val_if_fail (test_name != NULL, NULL);
1349 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1350 g_return_val_if_fail (test_name[0] != 0, NULL);
1351 g_return_val_if_fail (data_test != NULL, NULL);
1353 tc = g_slice_new0 (GTestCase);
1354 tc->name = g_strdup (test_name);
1355 tc->test_data = (gpointer) test_data;
1356 tc->fixture_size = data_size;
1357 tc->fixture_setup = (void*) data_setup;
1358 tc->fixture_test = (void*) data_test;
1359 tc->fixture_teardown = (void*) data_teardown;
1366 * @fixture: the test fixture
1367 * @user_data: the data provided when registering the test
1369 * The type used for functions that operate on test fixtures. This is
1370 * used for the fixture setup and teardown functions as well as for the
1371 * testcases themselves.
1373 * @user_data is a pointer to the data that was given when registering
1376 * @fixture will be a pointer to the area of memory allocated by the
1377 * test framework, of the size requested. If the requested size was
1378 * zero then @fixture will be equal to @user_data.
1383 g_test_add_vtable (const char *testpath,
1385 gconstpointer test_data,
1386 GTestFixtureFunc data_setup,
1387 GTestFixtureFunc fixture_test_func,
1388 GTestFixtureFunc data_teardown)
1394 g_return_if_fail (testpath != NULL);
1395 g_return_if_fail (testpath[0] == '/');
1396 g_return_if_fail (fixture_test_func != NULL);
1398 if (g_slist_find_custom (test_paths_skipped, testpath, (GCompareFunc)g_strcmp0))
1401 suite = g_test_get_root();
1402 segments = g_strsplit (testpath, "/", -1);
1403 for (ui = 0; segments[ui] != NULL; ui++)
1405 const char *seg = segments[ui];
1406 gboolean islast = segments[ui + 1] == NULL;
1407 if (islast && !seg[0])
1408 g_error ("invalid test case path: %s", testpath);
1410 continue; /* initial or duplicate slash */
1413 GTestSuite *csuite = g_test_create_suite (seg);
1414 g_test_suite_add_suite (suite, csuite);
1419 GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1420 g_test_suite_add (suite, tc);
1423 g_strfreev (segments);
1429 * Indicates that a test failed. This function can be called
1430 * multiple times from the same test. You can use this function
1431 * if your test failed in a recoverable way.
1433 * Do not use this function if the failure of a test could cause
1434 * other tests to malfunction.
1436 * Calling this function will not stop the test from running, you
1437 * need to return from the test function yourself. So you can
1438 * produce additional diagnostic messages or even continue running
1441 * If not called from inside a test, this function does nothing.
1448 test_run_success = FALSE;
1454 * The type used for test case functions.
1461 * @testpath: Slash-separated test case path name for the test.
1462 * @test_func: The test function to invoke for this test.
1464 * Create a new test case, similar to g_test_create_case(). However
1465 * the test is assumed to use no fixture, and test suites are automatically
1466 * created on the fly and added to the root fixture, based on the
1467 * slash-separated portions of @testpath.
1472 g_test_add_func (const char *testpath,
1473 GTestFunc test_func)
1475 g_return_if_fail (testpath != NULL);
1476 g_return_if_fail (testpath[0] == '/');
1477 g_return_if_fail (test_func != NULL);
1478 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1483 * @user_data: the data provided when registering the test
1485 * The type used for test case functions that take an extra pointer
1492 * g_test_add_data_func:
1493 * @testpath: Slash-separated test case path name for the test.
1494 * @test_data: Test data argument for the test function.
1495 * @test_func: The test function to invoke for this test.
1497 * Create a new test case, similar to g_test_create_case(). However
1498 * the test is assumed to use no fixture, and test suites are automatically
1499 * created on the fly and added to the root fixture, based on the
1500 * slash-separated portions of @testpath. The @test_data argument
1501 * will be passed as first argument to @test_func.
1506 g_test_add_data_func (const char *testpath,
1507 gconstpointer test_data,
1508 GTestDataFunc test_func)
1510 g_return_if_fail (testpath != NULL);
1511 g_return_if_fail (testpath[0] == '/');
1512 g_return_if_fail (test_func != NULL);
1513 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1517 * g_test_create_suite:
1518 * @suite_name: a name for the suite
1520 * Create a new test suite with the name @suite_name.
1522 * Returns: A newly allocated #GTestSuite instance.
1527 g_test_create_suite (const char *suite_name)
1530 g_return_val_if_fail (suite_name != NULL, NULL);
1531 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1532 g_return_val_if_fail (suite_name[0] != 0, NULL);
1533 ts = g_slice_new0 (GTestSuite);
1534 ts->name = g_strdup (suite_name);
1540 * @suite: a #GTestSuite
1541 * @test_case: a #GTestCase
1543 * Adds @test_case to @suite.
1548 g_test_suite_add (GTestSuite *suite,
1549 GTestCase *test_case)
1551 g_return_if_fail (suite != NULL);
1552 g_return_if_fail (test_case != NULL);
1554 suite->cases = g_slist_prepend (suite->cases, test_case);
1558 * g_test_suite_add_suite:
1559 * @suite: a #GTestSuite
1560 * @nestedsuite: another #GTestSuite
1562 * Adds @nestedsuite to @suite.
1567 g_test_suite_add_suite (GTestSuite *suite,
1568 GTestSuite *nestedsuite)
1570 g_return_if_fail (suite != NULL);
1571 g_return_if_fail (nestedsuite != NULL);
1573 suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1577 * g_test_queue_free:
1578 * @gfree_pointer: the pointer to be stored.
1580 * Enqueue a pointer to be released with g_free() during the next
1581 * teardown phase. This is equivalent to calling g_test_queue_destroy()
1582 * with a destroy callback of g_free().
1587 g_test_queue_free (gpointer gfree_pointer)
1590 g_test_queue_destroy (g_free, gfree_pointer);
1594 * g_test_queue_destroy:
1595 * @destroy_func: Destroy callback for teardown phase.
1596 * @destroy_data: Destroy callback data.
1598 * This function enqueus a callback @destroy_func to be executed
1599 * during the next test case teardown phase. This is most useful
1600 * to auto destruct allocted test resources at the end of a test run.
1601 * Resources are released in reverse queue order, that means enqueueing
1602 * callback A before callback B will cause B() to be called before
1603 * A() during teardown.
1608 g_test_queue_destroy (GDestroyNotify destroy_func,
1609 gpointer destroy_data)
1611 DestroyEntry *dentry;
1613 g_return_if_fail (destroy_func != NULL);
1615 dentry = g_slice_new0 (DestroyEntry);
1616 dentry->destroy_func = destroy_func;
1617 dentry->destroy_data = destroy_data;
1618 dentry->next = test_destroy_queue;
1619 test_destroy_queue = dentry;
1623 test_case_run (GTestCase *tc)
1625 gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1626 gboolean success = TRUE;
1628 test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1629 if (++test_run_count <= test_skip_count)
1630 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1631 else if (test_run_list)
1633 g_print ("%s\n", test_run_name);
1634 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1638 GTimer *test_run_timer = g_timer_new();
1639 long double largs[3];
1641 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1643 test_run_success = TRUE;
1644 g_test_log_set_fatal_handler (NULL, NULL);
1645 g_timer_start (test_run_timer);
1646 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1647 test_run_seed (test_run_seedstr);
1648 if (tc->fixture_setup)
1649 tc->fixture_setup (fixture, tc->test_data);
1650 tc->fixture_test (fixture, tc->test_data);
1652 while (test_destroy_queue)
1654 DestroyEntry *dentry = test_destroy_queue;
1655 test_destroy_queue = dentry->next;
1656 dentry->destroy_func (dentry->destroy_data);
1657 g_slice_free (DestroyEntry, dentry);
1659 if (tc->fixture_teardown)
1660 tc->fixture_teardown (fixture, tc->test_data);
1661 if (tc->fixture_size)
1663 g_timer_stop (test_run_timer);
1664 success = test_run_success;
1665 test_run_success = FALSE;
1666 largs[0] = success ? 0 : 1; /* OK */
1667 largs[1] = test_run_forks;
1668 largs[2] = g_timer_elapsed (test_run_timer, NULL);
1669 g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1670 g_timer_destroy (test_run_timer);
1672 g_free (test_run_name);
1673 test_run_name = old_name;
1674 g_free (test_uri_base);
1675 test_uri_base = old_base;
1681 g_test_run_suite_internal (GTestSuite *suite,
1685 gchar *rest, *old_name = test_run_name;
1686 GSList *slist, *reversed;
1688 g_return_val_if_fail (suite != NULL, -1);
1690 while (path[0] == '/')
1693 rest = strchr (path, '/');
1694 l = rest ? MIN (l, rest - path) : l;
1695 test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1696 reversed = g_slist_reverse (g_slist_copy (suite->cases));
1697 for (slist = reversed; slist; slist = slist->next)
1699 GTestCase *tc = slist->data;
1700 guint n = l ? strlen (tc->name) : 0;
1701 if (l == n && strncmp (path, tc->name, n) == 0)
1703 if (!test_case_run (tc))
1707 g_slist_free (reversed);
1708 reversed = g_slist_reverse (g_slist_copy (suite->suites));
1709 for (slist = reversed; slist; slist = slist->next)
1711 GTestSuite *ts = slist->data;
1712 guint n = l ? strlen (ts->name) : 0;
1713 if (l == n && strncmp (path, ts->name, n) == 0)
1714 n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
1716 g_slist_free (reversed);
1717 g_free (test_run_name);
1718 test_run_name = old_name;
1725 * @suite: a #GTestSuite
1727 * Execute the tests within @suite and all nested #GTestSuites.
1728 * The test suites to be executed are filtered according to
1729 * test path arguments (-p <replaceable>testpath</replaceable>)
1730 * as parsed by g_test_init().
1731 * g_test_run_suite() or g_test_run() may only be called once
1734 * Returns: 0 on success
1739 g_test_run_suite (GTestSuite *suite)
1743 g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1744 g_return_val_if_fail (g_test_run_once == TRUE, -1);
1746 g_test_run_once = FALSE;
1749 test_paths = g_slist_prepend (test_paths, "");
1752 const char *rest, *path = test_paths->data;
1753 guint l, n = strlen (suite->name);
1754 test_paths = g_slist_delete_link (test_paths, test_paths);
1755 while (path[0] == '/')
1757 if (!n) /* root suite, run unconditionally */
1759 n_bad += g_test_run_suite_internal (suite, path);
1762 /* regular suite, match path */
1763 rest = strchr (path, '/');
1765 l = rest ? MIN (l, rest - path) : l;
1766 if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1767 n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
1774 gtest_default_log_handler (const gchar *log_domain,
1775 GLogLevelFlags log_level,
1776 const gchar *message,
1777 gpointer unused_data)
1779 const gchar *strv[16];
1780 gboolean fatal = FALSE;
1786 strv[i++] = log_domain;
1789 if (log_level & G_LOG_FLAG_FATAL)
1791 strv[i++] = "FATAL-";
1794 if (log_level & G_LOG_FLAG_RECURSION)
1795 strv[i++] = "RECURSIVE-";
1796 if (log_level & G_LOG_LEVEL_ERROR)
1797 strv[i++] = "ERROR";
1798 if (log_level & G_LOG_LEVEL_CRITICAL)
1799 strv[i++] = "CRITICAL";
1800 if (log_level & G_LOG_LEVEL_WARNING)
1801 strv[i++] = "WARNING";
1802 if (log_level & G_LOG_LEVEL_MESSAGE)
1803 strv[i++] = "MESSAGE";
1804 if (log_level & G_LOG_LEVEL_INFO)
1806 if (log_level & G_LOG_LEVEL_DEBUG)
1807 strv[i++] = "DEBUG";
1809 strv[i++] = message;
1812 msg = g_strjoinv ("", (gchar**) strv);
1813 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
1814 g_log_default_handler (log_domain, log_level, message, unused_data);
1820 g_assertion_message (const char *domain,
1824 const char *message)
1830 message = "code should not be reached";
1831 g_snprintf (lstr, 32, "%d", line);
1832 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1833 "ERROR:", file, ":", lstr, ":",
1834 func, func[0] ? ":" : "",
1835 " ", message, NULL);
1836 g_printerr ("**\n%s\n", s);
1838 /* store assertion message in global variable, so that it can be found in a
1840 if (__glib_assert_msg != NULL)
1841 /* free the old one */
1842 free (__glib_assert_msg);
1843 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
1844 strcpy (__glib_assert_msg, s);
1846 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
1852 g_assertion_message_expr (const char *domain,
1858 char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1859 g_assertion_message (domain, file, line, func, s);
1864 g_assertion_message_cmpnum (const char *domain,
1877 case 'i': s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
1878 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;
1879 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
1880 /* ideally use: floats=%.7g double=%.17g */
1882 g_assertion_message (domain, file, line, func, s);
1887 g_assertion_message_cmpstr (const char *domain,
1896 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1897 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1898 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1901 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1904 g_assertion_message (domain, file, line, func, s);
1909 g_assertion_message_error (const char *domain,
1914 const GError *error,
1915 GQuark error_domain,
1920 /* This is used by both g_assert_error() and g_assert_no_error(), so there
1921 * are three cases: expected an error but got the wrong error, expected
1922 * an error but got no error, and expected no error but got an error.
1925 gstring = g_string_new ("assertion failed ");
1927 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
1928 g_quark_to_string (error_domain), error_code);
1930 g_string_append_printf (gstring, "(%s == NULL): ", expr);
1933 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
1934 g_quark_to_string (error->domain), error->code);
1936 g_string_append_printf (gstring, "%s is NULL", expr);
1938 g_assertion_message (domain, file, line, func, gstring->str);
1939 g_string_free (gstring, TRUE);
1944 * @str1: a C string or %NULL
1945 * @str2: another C string or %NULL
1947 * Compares @str1 and @str2 like strcmp(). Handles %NULL
1948 * gracefully by sorting it before non-%NULL strings.
1949 * Comparing two %NULL pointers returns 0.
1951 * Returns: -1, 0 or 1, if @str1 is <, == or > than @str2.
1956 g_strcmp0 (const char *str1,
1960 return -(str1 != str2);
1962 return str1 != str2;
1963 return strcmp (str1, str2);
1967 static int /* 0 on success */
1968 kill_child (int pid,
1973 if (patience >= 3) /* try graceful reap */
1975 if (waitpid (pid, status, WNOHANG) > 0)
1978 if (patience >= 2) /* try SIGHUP */
1981 if (waitpid (pid, status, WNOHANG) > 0)
1983 g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1984 if (waitpid (pid, status, WNOHANG) > 0)
1986 g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
1987 if (waitpid (pid, status, WNOHANG) > 0)
1989 g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
1990 if (waitpid (pid, status, WNOHANG) > 0)
1993 if (patience >= 1) /* try SIGTERM */
1995 kill (pid, SIGTERM);
1996 if (waitpid (pid, status, WNOHANG) > 0)
1998 g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
1999 if (waitpid (pid, status, WNOHANG) > 0)
2001 g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
2002 if (waitpid (pid, status, WNOHANG) > 0)
2006 kill (pid, SIGKILL);
2008 wr = waitpid (pid, status, 0);
2009 while (wr < 0 && errno == EINTR);
2015 g_string_must_read (GString *gstring,
2018 #define STRING_BUFFER_SIZE 4096
2019 char buf[STRING_BUFFER_SIZE];
2022 bytes = read (fd, buf, sizeof (buf));
2024 return 0; /* EOF, calling this function assumes data is available */
2027 g_string_append_len (gstring, buf, bytes);
2030 else if (bytes < 0 && errno == EINTR)
2032 else /* bytes < 0 */
2034 g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2035 return 1; /* ignore error after warning */
2040 g_string_write_out (GString *gstring,
2044 if (*stringpos < gstring->len)
2048 r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
2049 while (r < 0 && errno == EINTR);
2050 *stringpos += MAX (r, 0);
2055 test_trap_clear (void)
2057 test_trap_last_status = 0;
2058 test_trap_last_pid = 0;
2059 g_free (test_trap_last_stdout);
2060 test_trap_last_stdout = NULL;
2061 g_free (test_trap_last_stderr);
2062 test_trap_last_stderr = NULL;
2073 ret = dup2 (fd1, fd2);
2074 while (ret < 0 && errno == EINTR);
2079 test_time_stamp (void)
2083 g_get_current_time (&tv);
2085 stamp = stamp * 1000000 + tv.tv_usec;
2093 * @usec_timeout: Timeout for the forked test in micro seconds.
2094 * @test_trap_flags: Flags to modify forking behaviour.
2096 * Fork the current test program to execute a test case that might
2097 * not return or that might abort. The forked test case is aborted
2098 * and considered failing if its run time exceeds @usec_timeout.
2100 * The forking behavior can be configured with the #GTestTrapFlags flags.
2102 * In the following example, the test code forks, the forked child
2103 * process produces some sample output and exits successfully.
2104 * The forking parent process then asserts successful child program
2105 * termination and validates child program outputs.
2109 * test_fork_patterns (void)
2111 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2113 * g_print ("some stdout text: somagic17\n");
2114 * g_printerr ("some stderr text: semagic43\n");
2115 * exit (0); /* successful test run */
2117 * g_test_trap_assert_passed();
2118 * g_test_trap_assert_stdout ("*somagic17*");
2119 * g_test_trap_assert_stderr ("*semagic43*");
2123 * This function is implemented only on Unix platforms.
2125 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2130 g_test_trap_fork (guint64 usec_timeout,
2131 GTestTrapFlags test_trap_flags)
2134 gboolean pass_on_forked_log = FALSE;
2135 int stdout_pipe[2] = { -1, -1 };
2136 int stderr_pipe[2] = { -1, -1 };
2137 int stdtst_pipe[2] = { -1, -1 };
2139 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
2140 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
2141 signal (SIGCHLD, SIG_DFL);
2142 test_trap_last_pid = fork ();
2143 if (test_trap_last_pid < 0)
2144 g_error ("failed to fork test program: %s", g_strerror (errno));
2145 if (test_trap_last_pid == 0) /* child */
2148 close (stdout_pipe[0]);
2149 close (stderr_pipe[0]);
2150 close (stdtst_pipe[0]);
2151 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2152 fd0 = open ("/dev/null", O_RDONLY);
2153 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2154 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
2157 if (stdout_pipe[1] >= 3)
2158 close (stdout_pipe[1]);
2159 if (stderr_pipe[1] >= 3)
2160 close (stderr_pipe[1]);
2161 test_log_fd = stdtst_pipe[1];
2166 GString *sout = g_string_new (NULL);
2167 GString *serr = g_string_new (NULL);
2169 int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
2171 close (stdout_pipe[1]);
2172 close (stderr_pipe[1]);
2173 close (stdtst_pipe[1]);
2174 sstamp = test_time_stamp();
2175 /* read data until we get EOF on all pipes */
2176 while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
2182 if (stdout_pipe[0] >= 0)
2183 FD_SET (stdout_pipe[0], &fds);
2184 if (stderr_pipe[0] >= 0)
2185 FD_SET (stderr_pipe[0], &fds);
2186 if (stdtst_pipe[0] >= 0)
2187 FD_SET (stdtst_pipe[0], &fds);
2189 tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
2190 ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
2191 if (ret < 0 && errno != EINTR)
2193 g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2196 if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
2197 g_string_must_read (sout, stdout_pipe[0]) == 0)
2199 close (stdout_pipe[0]);
2200 stdout_pipe[0] = -1;
2202 if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
2203 g_string_must_read (serr, stderr_pipe[0]) == 0)
2205 close (stderr_pipe[0]);
2206 stderr_pipe[0] = -1;
2208 if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
2210 guint8 buffer[4096];
2211 gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
2212 if (r > 0 && test_log_fd > 0)
2214 l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
2215 while (l < 0 && errno == EINTR);
2216 if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
2218 close (stdtst_pipe[0]);
2219 stdtst_pipe[0] = -1;
2222 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
2223 g_string_write_out (sout, 1, &soutpos);
2224 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
2225 g_string_write_out (serr, 2, &serrpos);
2228 guint64 nstamp = test_time_stamp();
2230 sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
2231 if (usec_timeout < nstamp - sstamp)
2233 /* timeout reached, need to abort the child now */
2234 kill_child (test_trap_last_pid, &status, 3);
2235 test_trap_last_status = 1024; /* timeout */
2236 if (0 && WIFSIGNALED (status))
2237 g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
2243 if (stdout_pipe[0] != -1)
2244 close (stdout_pipe[0]);
2245 if (stderr_pipe[0] != -1)
2246 close (stderr_pipe[0]);
2247 if (stdtst_pipe[0] != -1)
2248 close (stdtst_pipe[0]);
2253 wr = waitpid (test_trap_last_pid, &status, 0);
2254 while (wr < 0 && errno == EINTR);
2255 if (WIFEXITED (status)) /* normal exit */
2256 test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
2257 else if (WIFSIGNALED (status))
2258 test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
2259 else /* WCOREDUMP (status) */
2260 test_trap_last_status = 512; /* coredump */
2262 test_trap_last_stdout = g_string_free (sout, FALSE);
2263 test_trap_last_stderr = g_string_free (serr, FALSE);
2267 g_message ("Not implemented: g_test_trap_fork");
2274 * g_test_trap_has_passed:
2276 * Check the result of the last g_test_trap_fork() call.
2278 * Returns: %TRUE if the last forked child terminated successfully.
2283 g_test_trap_has_passed (void)
2285 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
2289 * g_test_trap_reached_timeout:
2291 * Check the result of the last g_test_trap_fork() call.
2293 * Returns: %TRUE if the last forked child got killed due to a fork timeout.
2298 g_test_trap_reached_timeout (void)
2300 return 0 != (test_trap_last_status & 1024); /* timeout flag */
2304 g_test_trap_assertions (const char *domain,
2308 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
2309 const char *pattern)
2312 gboolean must_pass = assertion_flags == 0;
2313 gboolean must_fail = assertion_flags == 1;
2314 gboolean match_result = 0 == (assertion_flags & 1);
2315 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
2316 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
2317 const char *match_error = match_result ? "failed to match" : "contains invalid match";
2318 if (test_trap_last_pid == 0)
2319 g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
2320 if (must_pass && !g_test_trap_has_passed())
2322 char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
2323 g_assertion_message (domain, file, line, func, msg);
2326 if (must_fail && g_test_trap_has_passed())
2328 char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
2329 g_assertion_message (domain, file, line, func, msg);
2332 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
2334 char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
2335 g_assertion_message (domain, file, line, func, msg);
2338 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
2340 char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
2341 g_assertion_message (domain, file, line, func, msg);
2348 gstring_overwrite_int (GString *gstring,
2352 vuint = g_htonl (vuint);
2353 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
2357 gstring_append_int (GString *gstring,
2360 vuint = g_htonl (vuint);
2361 g_string_append_len (gstring, (const gchar*) &vuint, 4);
2365 gstring_append_double (GString *gstring,
2368 union { double vdouble; guint64 vuint64; } u;
2369 u.vdouble = vdouble;
2370 u.vuint64 = GUINT64_TO_BE (u.vuint64);
2371 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
2375 g_test_log_dump (GTestLogMsg *msg,
2378 GString *gstring = g_string_sized_new (1024);
2380 gstring_append_int (gstring, 0); /* message length */
2381 gstring_append_int (gstring, msg->log_type);
2382 gstring_append_int (gstring, msg->n_strings);
2383 gstring_append_int (gstring, msg->n_nums);
2384 gstring_append_int (gstring, 0); /* reserved */
2385 for (ui = 0; ui < msg->n_strings; ui++)
2387 guint l = strlen (msg->strings[ui]);
2388 gstring_append_int (gstring, l);
2389 g_string_append_len (gstring, msg->strings[ui], l);
2391 for (ui = 0; ui < msg->n_nums; ui++)
2392 gstring_append_double (gstring, msg->nums[ui]);
2393 *len = gstring->len;
2394 gstring_overwrite_int (gstring, 0, *len); /* message length */
2395 return (guint8*) g_string_free (gstring, FALSE);
2398 static inline long double
2399 net_double (const gchar **ipointer)
2401 union { guint64 vuint64; double vdouble; } u;
2402 guint64 aligned_int64;
2403 memcpy (&aligned_int64, *ipointer, 8);
2405 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
2409 static inline guint32
2410 net_int (const gchar **ipointer)
2412 guint32 aligned_int;
2413 memcpy (&aligned_int, *ipointer, 4);
2415 return g_ntohl (aligned_int);
2419 g_test_log_extract (GTestLogBuffer *tbuffer)
2421 const gchar *p = tbuffer->data->str;
2424 if (tbuffer->data->len < 4 * 5)
2426 mlength = net_int (&p);
2427 if (tbuffer->data->len < mlength)
2429 msg.log_type = net_int (&p);
2430 msg.n_strings = net_int (&p);
2431 msg.n_nums = net_int (&p);
2432 if (net_int (&p) == 0)
2435 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
2436 msg.nums = g_new0 (long double, msg.n_nums);
2437 for (ui = 0; ui < msg.n_strings; ui++)
2439 guint sl = net_int (&p);
2440 msg.strings[ui] = g_strndup (p, sl);
2443 for (ui = 0; ui < msg.n_nums; ui++)
2444 msg.nums[ui] = net_double (&p);
2445 if (p <= tbuffer->data->str + mlength)
2447 g_string_erase (tbuffer->data, 0, mlength);
2448 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
2453 g_strfreev (msg.strings);
2454 g_error ("corrupt log stream from test program");
2459 * g_test_log_buffer_new:
2461 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2464 g_test_log_buffer_new (void)
2466 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
2467 tb->data = g_string_sized_new (1024);
2472 * g_test_log_buffer_free
2474 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2477 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
2479 g_return_if_fail (tbuffer != NULL);
2480 while (tbuffer->msgs)
2481 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
2482 g_string_free (tbuffer->data, TRUE);
2487 * g_test_log_buffer_push
2489 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2492 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
2494 const guint8 *bytes)
2496 g_return_if_fail (tbuffer != NULL);
2499 gboolean more_messages;
2500 g_return_if_fail (bytes != NULL);
2501 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
2503 more_messages = g_test_log_extract (tbuffer);
2504 while (more_messages);
2509 * g_test_log_buffer_pop:
2511 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
2514 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
2516 GTestLogMsg *msg = NULL;
2517 g_return_val_if_fail (tbuffer != NULL, NULL);
2520 GSList *slist = g_slist_last (tbuffer->msgs);
2522 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
2528 * g_test_log_msg_free:
2530 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2533 g_test_log_msg_free (GTestLogMsg *tmsg)
2535 g_return_if_fail (tmsg != NULL);
2536 g_strfreev (tmsg->strings);
2537 g_free (tmsg->nums);
2541 /* --- macros docs START --- */
2544 * @testpath: The test path for a new test case.
2545 * @Fixture: The type of a fixture data structure.
2546 * @tdata: Data argument for the test functions.
2547 * @fsetup: The function to set up the fixture data.
2548 * @ftest: The actual test function.
2549 * @fteardown: The function to tear down the fixture data.
2551 * Hook up a new test case at @testpath, similar to g_test_add_func().
2552 * A fixture data structure with setup and teardown function may be provided
2553 * though, similar to g_test_create_case().
2554 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2555 * fteardown() callbacks can expect a @Fixture pointer as first argument in
2556 * a type safe manner.
2560 /* --- macros docs END --- */