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.
111 * Returns: %TRUE if in quick mode
117 * Returns %TRUE if tests are run in slow mode.
119 * Returns: %TRUE if in slow mode
125 * Returns %TRUE if tests are run in thorough mode.
127 * Returns: %TRUE if in thorough mode
133 * Returns %TRUE if tests are run in performance mode.
135 * Returns: %TRUE if in performance mode
141 * Returns %TRUE if tests are run in verbose mode.
143 * Returns: %TRUE if in verbose mode
149 * Returns %TRUE if tests are run in quiet mode.
151 * Returns: %TRUE if in quied mode
155 * g_test_queue_unref:
156 * @gobject: the object to unref
158 * Enqueue an object to be released with g_object_unref() during
159 * the next teardown phase. This is equivalent to calling
160 * g_test_queue_destroy() with a destroy callback of g_object_unref().
167 * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
168 * <filename>/dev/null</filename> so it cannot be observed on the
169 * console during test runs. The actual output is still captured
170 * though to allow later tests with g_test_trap_assert_stdout().
171 * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
172 * <filename>/dev/null</filename> so it cannot be observed on the
173 * console during test runs. The actual output is still captured
174 * though to allow later tests with g_test_trap_assert_stderr().
175 * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
176 * forked child process is shared with stdin of its parent process.
177 * It is redirected to <filename>/dev/null</filename> otherwise.
179 * Test traps are guards around forked tests.
180 * These flags determine what traps to set.
184 * g_test_trap_assert_passed:
186 * Assert that the last forked test passed.
187 * See g_test_trap_fork().
193 * g_test_trap_assert_failed:
195 * Assert that the last forked test failed.
196 * See g_test_trap_fork().
202 * g_test_trap_assert_stdout:
203 * @soutpattern: a glob-style
204 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
206 * Assert that the stdout output of the last forked test matches
207 * @soutpattern. See g_test_trap_fork().
213 * g_test_trap_assert_stdout_unmatched:
214 * @soutpattern: a glob-style
215 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
217 * Assert that the stdout output of the last forked test
218 * does not match @soutpattern. See g_test_trap_fork().
224 * g_test_trap_assert_stderr:
225 * @serrpattern: a glob-style
226 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
228 * Assert that the stderr output of the last forked test
229 * matches @serrpattern. See g_test_trap_fork().
235 * g_test_trap_assert_stderr_unmatched:
236 * @serrpattern: a glob-style
237 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
239 * Assert that the stderr output of the last forked test
240 * does not match @serrpattern. See g_test_trap_fork().
248 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
249 * for details on test case random numbers.
256 * @expr: the expression to check
258 * Debugging macro to terminate the application if the assertion
259 * fails. If the assertion fails (i.e. the expression is not true),
260 * an error message is logged and the application is terminated.
262 * The macro can be turned off in final releases of code by defining
263 * #G_DISABLE_ASSERT when compiling the application.
267 * g_assert_not_reached:
269 * Debugging macro to terminate the application if it is ever
270 * reached. If it is reached, an error message is logged and the
271 * application is terminated.
273 * The macro can be turned off in final releases of code by defining
274 * #G_DISABLE_ASSERT when compiling the application.
279 * @s1: a string (may be %NULL)
280 * @cmp: The comparison operator to use.
281 * One of ==, !=, <, >, <=, >=.
282 * @s2: another string (may be %NULL)
284 * Debugging macro to terminate the application with a warning
285 * message if a string comparison fails. The strings are compared
288 * The effect of <literal>g_assert_cmpstr (s1, op, s2)</literal> is
289 * the same as <literal>g_assert (g_strcmp0 (s1, s2) op 0)</literal>.
290 * The advantage of this macro is that it can produce a message that
291 * includes the actual values of @s1 and @s2.
294 * g_assert_cmpstr (mystring, ==, "fubar");
303 * @cmp: The comparison operator to use.
304 * One of ==, !=, <, >, <=, >=.
305 * @n2: another integer
307 * Debugging macro to terminate the application with a warning
308 * message if an integer comparison fails.
310 * The effect of <literal>g_assert_cmpint (n1, op, n2)</literal> is
311 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
312 * of this macro is that it can produce a message that includes the
313 * actual values of @n1 and @n2.
320 * @n1: an unsigned integer
321 * @cmp: The comparison operator to use.
322 * One of ==, !=, <, >, <=, >=.
323 * @n2: another unsigned integer
325 * Debugging macro to terminate the application with a warning
326 * message if an unsigned integer comparison fails.
328 * The effect of <literal>g_assert_cmpuint (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 * This is a variant of g_assert_cmpuint() that displays the numbers
347 * in hexadecimal notation in the message.
354 * @n1: an floating point number
355 * @cmp: The comparison operator to use.
356 * One of ==, !=, <, >, <=, >=.
357 * @n2: another floating point number
359 * Debugging macro to terminate the application with a warning
360 * message if a floating point number comparison fails.
362 * The effect of <literal>g_assert_cmpfloat (n1, op, n2)</literal> is
363 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
364 * of this macro is that it can produce a message that includes the
365 * actual values of @n1 and @n2.
372 * @err: a #GError, possibly %NULL
374 * Debugging macro to terminate the application with a warning
375 * message if a method has returned a #GError.
377 * The effect of <literal>g_assert_no_error (err)</literal> is
378 * the same as <literal>g_assert (err == NULL)</literal>. The advantage
379 * of this macro is that it can produce a message that includes
380 * the error message and code.
387 * @err: a #GError, possibly %NULL
388 * @dom: the expected error domain (a #GQuark)
389 * @c: the expected error code
391 * Debugging macro to terminate the application with a warning
392 * message if a method has not returned the correct #GError.
394 * The effect of <literal>g_assert_error (err, dom, c)</literal> is
395 * the same as <literal>g_assert (err != NULL && err->domain
396 * == dom && err->code == c)</literal>. The advantage of this
397 * macro is that it can produce a message that includes the incorrect
398 * error message and code.
400 * This can only be used to test for a specific error. If you want to
401 * test that @err is set, but don't care what it's set to, just use
402 * <literal>g_assert (err != NULL)</literal>
410 * An opaque structure representing a test case.
416 * An opaque structure representing a test suite.
420 /* Global variable for storing assertion messages; this is the counterpart to
421 * glibc's (private) __abort_msg variable, and allows developers and crash
422 * analysis systems like Apport and ABRT to fish out assertion messages from
423 * core dumps, instead of having to catch them on screen output.
425 char *__glib_assert_msg = NULL;
427 /* --- structures --- */
432 void (*fixture_setup) (void*, gconstpointer);
433 void (*fixture_test) (void*, gconstpointer);
434 void (*fixture_teardown) (void*, gconstpointer);
443 typedef struct DestroyEntry DestroyEntry;
447 GDestroyNotify destroy_func;
448 gpointer destroy_data;
451 /* --- prototypes --- */
452 static void test_run_seed (const gchar *rseed);
453 static void test_trap_clear (void);
454 static guint8* g_test_log_dump (GTestLogMsg *msg,
456 static void gtest_default_log_handler (const gchar *log_domain,
457 GLogLevelFlags log_level,
458 const gchar *message,
459 gpointer unused_data);
462 /* --- variables --- */
463 static int test_log_fd = -1;
464 static gboolean test_mode_fatal = TRUE;
465 static gboolean g_test_run_once = TRUE;
466 static gboolean test_run_list = FALSE;
467 static gchar *test_run_seedstr = NULL;
468 static GRand *test_run_rand = NULL;
469 static gchar *test_run_name = "";
470 static guint test_run_forks = 0;
471 static guint test_run_count = 0;
472 static guint test_run_success = FALSE;
473 static guint test_skip_count = 0;
474 static GTimer *test_user_timer = NULL;
475 static double test_user_stamp = 0;
476 static GSList *test_paths = NULL;
477 static GSList *test_paths_skipped = NULL;
478 static GTestSuite *test_suite_root = NULL;
479 static int test_trap_last_status = 0;
480 static int test_trap_last_pid = 0;
481 static char *test_trap_last_stdout = NULL;
482 static char *test_trap_last_stderr = NULL;
483 static char *test_uri_base = NULL;
484 static gboolean test_debug_log = FALSE;
485 static DestroyEntry *test_destroy_queue = NULL;
486 static GTestConfig mutable_test_config_vars = {
487 FALSE, /* test_initialized */
488 TRUE, /* test_quick */
489 FALSE, /* test_perf */
490 FALSE, /* test_verbose */
491 FALSE, /* test_quiet */
493 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
495 /* --- functions --- */
497 g_test_log_type_name (GTestLogType log_type)
501 case G_TEST_LOG_NONE: return "none";
502 case G_TEST_LOG_ERROR: return "error";
503 case G_TEST_LOG_START_BINARY: return "binary";
504 case G_TEST_LOG_LIST_CASE: return "list";
505 case G_TEST_LOG_SKIP_CASE: return "skip";
506 case G_TEST_LOG_START_CASE: return "start";
507 case G_TEST_LOG_STOP_CASE: return "stop";
508 case G_TEST_LOG_MIN_RESULT: return "minperf";
509 case G_TEST_LOG_MAX_RESULT: return "maxperf";
510 case G_TEST_LOG_MESSAGE: return "message";
516 g_test_log_send (guint n_bytes,
517 const guint8 *buffer)
519 if (test_log_fd >= 0)
523 r = write (test_log_fd, buffer, n_bytes);
524 while (r < 0 && errno == EINTR);
528 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
531 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
532 msg = g_test_log_buffer_pop (lbuffer);
533 g_warn_if_fail (msg != NULL);
534 g_warn_if_fail (lbuffer->data->len == 0);
535 g_test_log_buffer_free (lbuffer);
537 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
538 for (ui = 0; ui < msg->n_strings; ui++)
539 g_printerr (":{%s}", msg->strings[ui]);
543 for (ui = 0; ui < msg->n_nums; ui++)
544 g_printerr ("%s%.16Lg", ui ? ";" : "", msg->nums[ui]);
547 g_printerr (":LOG*}\n");
548 g_test_log_msg_free (msg);
553 g_test_log (GTestLogType lbit,
554 const gchar *string1,
555 const gchar *string2,
559 gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
561 gchar *astrings[3] = { NULL, NULL, NULL };
567 case G_TEST_LOG_START_BINARY:
568 if (g_test_verbose())
569 g_print ("GTest: random seed: %s\n", string2);
571 case G_TEST_LOG_STOP_CASE:
572 if (g_test_verbose())
573 g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
574 else if (!g_test_quiet())
575 g_print ("%s\n", fail ? "FAIL" : "OK");
576 if (fail && test_mode_fatal)
579 case G_TEST_LOG_MIN_RESULT:
580 if (g_test_verbose())
581 g_print ("(MINPERF:%s)\n", string1);
583 case G_TEST_LOG_MAX_RESULT:
584 if (g_test_verbose())
585 g_print ("(MAXPERF:%s)\n", string1);
587 case G_TEST_LOG_MESSAGE:
588 if (g_test_verbose())
589 g_print ("(MSG: %s)\n", string1);
595 msg.n_strings = (string1 != NULL) + (string1 && string2);
596 msg.strings = astrings;
597 astrings[0] = (gchar*) string1;
598 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
601 dbuffer = g_test_log_dump (&msg, &dbufferlen);
602 g_test_log_send (dbufferlen, dbuffer);
607 case G_TEST_LOG_START_CASE:
608 if (g_test_verbose())
609 g_print ("GTest: run: %s\n", string1);
610 else if (!g_test_quiet())
611 g_print ("%s: ", string1);
617 /* We intentionally parse the command line without GOptionContext
618 * because otherwise you would never be able to test it.
621 parse_args (gint *argc_p,
624 guint argc = *argc_p;
625 gchar **argv = *argv_p;
627 /* parse known args */
628 for (i = 1; i < argc; i++)
630 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
632 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
633 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
634 g_log_set_always_fatal (fatal_mask);
637 else if (strcmp (argv[i], "--keep-going") == 0 ||
638 strcmp (argv[i], "-k") == 0)
640 test_mode_fatal = FALSE;
643 else if (strcmp (argv[i], "--debug-log") == 0)
645 test_debug_log = TRUE;
648 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
650 gchar *equal = argv[i] + 12;
652 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
653 else if (i + 1 < argc)
656 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
660 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
662 gchar *equal = argv[i] + 16;
664 test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
665 else if (i + 1 < argc)
668 test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
672 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
674 gchar *equal = argv[i] + 2;
676 test_paths = g_slist_prepend (test_paths, equal + 1);
677 else if (i + 1 < argc)
680 test_paths = g_slist_prepend (test_paths, argv[i]);
684 else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
686 gchar *equal = argv[i] + 2;
688 test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
689 else if (i + 1 < argc)
692 test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
696 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
698 gchar *equal = argv[i] + 2;
699 const gchar *mode = "";
702 else if (i + 1 < argc)
707 if (strcmp (mode, "perf") == 0)
708 mutable_test_config_vars.test_perf = TRUE;
709 else if (strcmp (mode, "slow") == 0)
710 mutable_test_config_vars.test_quick = FALSE;
711 else if (strcmp (mode, "thorough") == 0)
712 mutable_test_config_vars.test_quick = FALSE;
713 else if (strcmp (mode, "quick") == 0)
715 mutable_test_config_vars.test_quick = TRUE;
716 mutable_test_config_vars.test_perf = FALSE;
719 g_error ("unknown test mode: -m %s", mode);
722 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
724 mutable_test_config_vars.test_quiet = TRUE;
725 mutable_test_config_vars.test_verbose = FALSE;
728 else if (strcmp ("--verbose", argv[i]) == 0)
730 mutable_test_config_vars.test_quiet = FALSE;
731 mutable_test_config_vars.test_verbose = TRUE;
734 else if (strcmp ("-l", argv[i]) == 0)
736 test_run_list = TRUE;
739 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
741 gchar *equal = argv[i] + 6;
743 test_run_seedstr = equal + 1;
744 else if (i + 1 < argc)
747 test_run_seedstr = argv[i];
751 else if (strcmp ("-?", argv[i]) == 0 || strcmp ("--help", argv[i]) == 0)
754 " %s [OPTION...]\n\n"
756 " -?, --help Show help options\n"
758 " -l List test cases available in a test executable\n"
759 " -seed=RANDOMSEED Provide a random seed to reproduce test\n"
760 " runs using random numbers\n"
761 " --verbose Run tests verbosely\n"
762 " -q, --quiet Run tests quietly\n"
763 " -p TESTPATH execute all tests matching TESTPATH\n"
764 " -s TESTPATH skip all tests matching TESTPATH\n"
765 " -m {perf|slow|thorough|quick} Execute tests according modes\n"
766 " --debug-log debug test logging output\n"
767 " -k, --keep-going gtester-specific argument\n"
768 " --GTestLogFD=N gtester-specific argument\n"
769 " --GTestSkipCount=N gtester-specific argument\n",
776 for (i = 1; i < argc; i++)
788 * @argc: Address of the @argc parameter of the main() function.
789 * Changed if any arguments were handled.
790 * @argv: Address of the @argv parameter of main().
791 * Any parameters understood by g_test_init() stripped before return.
792 * @...: Reserved for future extension. Currently, you must pass %NULL.
794 * Initialize the GLib testing framework, e.g. by seeding the
795 * test random number generator, the name for g_get_prgname()
796 * and parsing test related command line args.
797 * So far, the following arguments are understood:
800 * <term><option>-l</option></term>
802 * list test cases available in a test executable.
806 * <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
808 * provide a random seed to reproduce test runs using random numbers.
812 * <term><option>--verbose</option></term>
813 * <listitem><para>run tests verbosely.</para></listitem>
816 * <term><option>-q</option>, <option>--quiet</option></term>
817 * <listitem><para>run tests quietly.</para></listitem>
820 * <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
822 * execute all tests matching <replaceable>TESTPATH</replaceable>.
826 * <term><option>-m {perf|slow|thorough|quick}</option></term>
828 * execute tests according to these test modes:
833 * performance tests, may take long and report results.
837 * <term>slow, thorough</term>
839 * slow and thorough tests, may take quite long and
846 * quick tests, should run really quickly and give good coverage.
853 * <term><option>--debug-log</option></term>
854 * <listitem><para>debug test logging output.</para></listitem>
857 * <term><option>-k</option>, <option>--keep-going</option></term>
858 * <listitem><para>gtester-specific argument.</para></listitem>
861 * <term><option>--GTestLogFD <replaceable>N</replaceable></option></term>
862 * <listitem><para>gtester-specific argument.</para></listitem>
865 * <term><option>--GTestSkipCount <replaceable>N</replaceable></option></term>
866 * <listitem><para>gtester-specific argument.</para></listitem>
873 g_test_init (int *argc,
877 static char seedstr[4 + 4 * 8 + 1];
880 /* make warnings and criticals fatal for all test programs */
881 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
882 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
883 g_log_set_always_fatal (fatal_mask);
884 /* check caller args */
885 g_return_if_fail (argc != NULL);
886 g_return_if_fail (argv != NULL);
887 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
888 mutable_test_config_vars.test_initialized = TRUE;
890 va_start (args, argv);
891 vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
893 g_return_if_fail (vararg1 == NULL);
895 /* setup random seed string */
896 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
897 test_run_seedstr = seedstr;
899 /* parse args, sets up mode, changes seed, etc. */
900 parse_args (argc, argv);
901 if (!g_get_prgname())
902 g_set_prgname ((*argv)[0]);
904 /* verify GRand reliability, needed for reliable seeds */
907 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
908 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
909 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
910 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
911 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
915 /* check rand seed */
916 test_run_seed (test_run_seedstr);
918 /* report program start */
919 g_log_set_default_handler (gtest_default_log_handler, NULL);
920 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
924 test_run_seed (const gchar *rseed)
926 guint seed_failed = 0;
928 g_rand_free (test_run_rand);
929 test_run_rand = NULL;
930 while (strchr (" \t\v\r\n\f", *rseed))
932 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
934 const char *s = rseed + 4;
935 if (strlen (s) >= 32) /* require 4 * 8 chars */
937 guint32 seedarray[4];
938 gchar *p, hexbuf[9] = { 0, };
939 memcpy (hexbuf, s + 0, 8);
940 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
941 seed_failed += p != NULL && *p != 0;
942 memcpy (hexbuf, s + 8, 8);
943 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
944 seed_failed += p != NULL && *p != 0;
945 memcpy (hexbuf, s + 16, 8);
946 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
947 seed_failed += p != NULL && *p != 0;
948 memcpy (hexbuf, s + 24, 8);
949 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
950 seed_failed += p != NULL && *p != 0;
953 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
958 g_error ("Unknown or invalid random seed: %s", rseed);
964 * Get a reproducible random integer number.
966 * The random numbers generated by the g_test_rand_*() family of functions
967 * change with every new test program start, unless the --seed option is
968 * given when starting test programs.
970 * For individual test cases however, the random number generator is
971 * reseeded, to avoid dependencies between tests and to make --seed
972 * effective for all test cases.
974 * Returns: a random number from the seeded random number generator.
979 g_test_rand_int (void)
981 return g_rand_int (test_run_rand);
985 * g_test_rand_int_range:
986 * @begin: the minimum value returned by this function
987 * @end: the smallest value not to be returned by this function
989 * Get a reproducible random integer number out of a specified range,
990 * see g_test_rand_int() for details on test case random numbers.
992 * Returns: a number with @begin <= number < @end.
997 g_test_rand_int_range (gint32 begin,
1000 return g_rand_int_range (test_run_rand, begin, end);
1004 * g_test_rand_double:
1006 * Get a reproducible random floating point number,
1007 * see g_test_rand_int() for details on test case random numbers.
1009 * Returns: a random number from the seeded random number generator.
1014 g_test_rand_double (void)
1016 return g_rand_double (test_run_rand);
1020 * g_test_rand_double_range:
1021 * @range_start: the minimum value returned by this function
1022 * @range_end: the minimum value not returned by this function
1024 * Get a reproducible random floating pointer number out of a specified range,
1025 * see g_test_rand_int() for details on test case random numbers.
1027 * Returns: a number with @range_start <= number < @range_end.
1032 g_test_rand_double_range (double range_start,
1035 return g_rand_double_range (test_run_rand, range_start, range_end);
1039 * g_test_timer_start:
1041 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1042 * to be done. Call this function again to restart the timer.
1047 g_test_timer_start (void)
1049 if (!test_user_timer)
1050 test_user_timer = g_timer_new();
1051 test_user_stamp = 0;
1052 g_timer_start (test_user_timer);
1056 * g_test_timer_elapsed:
1058 * Get the time since the last start of the timer with g_test_timer_start().
1060 * Returns: the time since the last start of the timer, as a double
1065 g_test_timer_elapsed (void)
1067 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1068 return test_user_stamp;
1072 * g_test_timer_last:
1074 * Report the last result of g_test_timer_elapsed().
1076 * Returns: the last result of g_test_timer_elapsed(), as a double
1081 g_test_timer_last (void)
1083 return test_user_stamp;
1087 * g_test_minimized_result:
1088 * @minimized_quantity: the reported value
1089 * @format: the format string of the report message
1090 * @...: arguments to pass to the printf() function
1092 * Report the result of a performance or measurement test.
1093 * The test should generally strive to minimize the reported
1094 * quantities (smaller values are better than larger ones),
1095 * this and @minimized_quantity can determine sorting
1096 * order for test result reports.
1101 g_test_minimized_result (double minimized_quantity,
1105 long double largs = minimized_quantity;
1109 va_start (args, format);
1110 buffer = g_strdup_vprintf (format, args);
1113 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1118 * g_test_maximized_result:
1119 * @maximized_quantity: the reported value
1120 * @format: the format string of the report message
1121 * @...: arguments to pass to the printf() function
1123 * Report the result of a performance or measurement test.
1124 * The test should generally strive to maximize the reported
1125 * quantities (larger values are better than smaller ones),
1126 * this and @maximized_quantity can determine sorting
1127 * order for test result reports.
1132 g_test_maximized_result (double maximized_quantity,
1136 long double largs = maximized_quantity;
1140 va_start (args, format);
1141 buffer = g_strdup_vprintf (format, args);
1144 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1150 * @format: the format string
1151 * @...: printf-like arguments to @format
1153 * Add a message to the test report.
1158 g_test_message (const char *format,
1164 va_start (args, format);
1165 buffer = g_strdup_vprintf (format, args);
1168 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1174 * @uri_pattern: the base pattern for bug URIs
1176 * Specify the base URI for bug reports.
1178 * The base URI is used to construct bug report messages for
1179 * g_test_message() when g_test_bug() is called.
1180 * Calling this function outside of a test case sets the
1181 * default base URI for all test cases. Calling it from within
1182 * a test case changes the base URI for the scope of the test
1184 * Bug URIs are constructed by appending a bug specific URI
1185 * portion to @uri_pattern, or by replacing the special string
1186 * '\%s' within @uri_pattern if that is present.
1191 g_test_bug_base (const char *uri_pattern)
1193 g_free (test_uri_base);
1194 test_uri_base = g_strdup (uri_pattern);
1199 * @bug_uri_snippet: Bug specific bug tracker URI portion.
1201 * This function adds a message to test reports that
1202 * associates a bug URI with a test case.
1203 * Bug URIs are constructed from a base URI set with g_test_bug_base()
1204 * and @bug_uri_snippet.
1209 g_test_bug (const char *bug_uri_snippet)
1213 g_return_if_fail (test_uri_base != NULL);
1214 g_return_if_fail (bug_uri_snippet != NULL);
1216 c = strstr (test_uri_base, "%s");
1219 char *b = g_strndup (test_uri_base, c - test_uri_base);
1220 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1222 g_test_message ("Bug Reference: %s", s);
1226 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1232 * Get the toplevel test suite for the test path API.
1234 * Returns: the toplevel #GTestSuite
1239 g_test_get_root (void)
1241 if (!test_suite_root)
1243 test_suite_root = g_test_create_suite ("root");
1244 g_free (test_suite_root->name);
1245 test_suite_root->name = g_strdup ("");
1248 return test_suite_root;
1254 * Runs all tests under the toplevel suite which can be retrieved
1255 * with g_test_get_root(). Similar to g_test_run_suite(), the test
1256 * cases to be run are filtered according to
1257 * test path arguments (-p <replaceable>testpath</replaceable>) as
1258 * parsed by g_test_init().
1259 * g_test_run_suite() or g_test_run() may only be called once
1262 * Returns: 0 on success
1269 return g_test_run_suite (g_test_get_root());
1273 * g_test_create_case:
1274 * @test_name: the name for the test case
1275 * @data_size: the size of the fixture data structure
1276 * @test_data: test data argument for the test functions
1277 * @data_setup: the function to set up the fixture data
1278 * @data_test: the actual test function
1279 * @data_teardown: the function to teardown the fixture data
1281 * Create a new #GTestCase, named @test_name, this API is fairly
1282 * low level, calling g_test_add() or g_test_add_func() is preferable.
1283 * When this test is executed, a fixture structure of size @data_size
1284 * will be allocated and filled with 0s. Then data_setup() is called
1285 * to initialize the fixture. After fixture setup, the actual test
1286 * function data_test() is called. Once the test run completed, the
1287 * fixture structure is torn down by calling data_teardown() and
1288 * after that the memory is released.
1290 * Splitting up a test run into fixture setup, test function and
1291 * fixture teardown is most usful if the same fixture is used for
1292 * multiple tests. In this cases, g_test_create_case() will be
1293 * called with the same fixture, but varying @test_name and
1294 * @data_test arguments.
1296 * Returns: a newly allocated #GTestCase.
1301 g_test_create_case (const char *test_name,
1303 gconstpointer test_data,
1304 GTestFixtureFunc data_setup,
1305 GTestFixtureFunc data_test,
1306 GTestFixtureFunc data_teardown)
1310 g_return_val_if_fail (test_name != NULL, NULL);
1311 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1312 g_return_val_if_fail (test_name[0] != 0, NULL);
1313 g_return_val_if_fail (data_test != NULL, NULL);
1315 tc = g_slice_new0 (GTestCase);
1316 tc->name = g_strdup (test_name);
1317 tc->test_data = (gpointer) test_data;
1318 tc->fixture_size = data_size;
1319 tc->fixture_setup = (void*) data_setup;
1320 tc->fixture_test = (void*) data_test;
1321 tc->fixture_teardown = (void*) data_teardown;
1328 * @fixture: the test fixture
1329 * @user_data: the data provided when registering the test
1331 * The type used for functions that operate on test fixtures. This is
1332 * used for the fixture setup and teardown functions as well as for the
1333 * testcases themselves.
1335 * @user_data is a pointer to the data that was given when registering
1338 * @fixture will be a pointer to the area of memory allocated by the
1339 * test framework, of the size requested. If the requested size was
1340 * zero then @fixture will be equal to @user_data.
1345 g_test_add_vtable (const char *testpath,
1347 gconstpointer test_data,
1348 GTestFixtureFunc data_setup,
1349 GTestFixtureFunc fixture_test_func,
1350 GTestFixtureFunc data_teardown)
1356 g_return_if_fail (testpath != NULL);
1357 g_return_if_fail (testpath[0] == '/');
1358 g_return_if_fail (fixture_test_func != NULL);
1360 if (g_slist_find_custom (test_paths_skipped, testpath, (GCompareFunc)g_strcmp0))
1363 suite = g_test_get_root();
1364 segments = g_strsplit (testpath, "/", -1);
1365 for (ui = 0; segments[ui] != NULL; ui++)
1367 const char *seg = segments[ui];
1368 gboolean islast = segments[ui + 1] == NULL;
1369 if (islast && !seg[0])
1370 g_error ("invalid test case path: %s", testpath);
1372 continue; /* initial or duplicate slash */
1375 GTestSuite *csuite = g_test_create_suite (seg);
1376 g_test_suite_add_suite (suite, csuite);
1381 GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1382 g_test_suite_add (suite, tc);
1385 g_strfreev (segments);
1391 * Indicates that a test failed. This function can be called
1392 * multiple times from the same test. You can use this function
1393 * if your test failed in a recoverable way.
1395 * Do not use this function if the failure of a test could cause
1396 * other tests to malfunction.
1398 * Calling this function will not stop the test from running, you
1399 * need to return from the test function yourself. So you can
1400 * produce additional diagnostic messages or even continue running
1403 * If not called from inside a test, this function does nothing.
1410 test_run_success = FALSE;
1416 * The type used for test case functions.
1423 * @testpath: Slash-separated test case path name for the test.
1424 * @test_func: The test function to invoke for this test.
1426 * Create a new test case, similar to g_test_create_case(). However
1427 * the test is assumed to use no fixture, and test suites are automatically
1428 * created on the fly and added to the root fixture, based on the
1429 * slash-separated portions of @testpath.
1434 g_test_add_func (const char *testpath,
1435 GTestFunc test_func)
1437 g_return_if_fail (testpath != NULL);
1438 g_return_if_fail (testpath[0] == '/');
1439 g_return_if_fail (test_func != NULL);
1440 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1445 * @user_data: the data provided when registering the test
1447 * The type used for test case functions that take an extra pointer
1454 * g_test_add_data_func:
1455 * @testpath: Slash-separated test case path name for the test.
1456 * @test_data: Test data argument for the test function.
1457 * @test_func: The test function to invoke for this test.
1459 * Create a new test case, similar to g_test_create_case(). However
1460 * the test is assumed to use no fixture, and test suites are automatically
1461 * created on the fly and added to the root fixture, based on the
1462 * slash-separated portions of @testpath. The @test_data argument
1463 * will be passed as first argument to @test_func.
1468 g_test_add_data_func (const char *testpath,
1469 gconstpointer test_data,
1470 GTestDataFunc test_func)
1472 g_return_if_fail (testpath != NULL);
1473 g_return_if_fail (testpath[0] == '/');
1474 g_return_if_fail (test_func != NULL);
1475 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1479 * g_test_create_suite:
1480 * @suite_name: a name for the suite
1482 * Create a new test suite with the name @suite_name.
1484 * Returns: A newly allocated #GTestSuite instance.
1489 g_test_create_suite (const char *suite_name)
1492 g_return_val_if_fail (suite_name != NULL, NULL);
1493 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1494 g_return_val_if_fail (suite_name[0] != 0, NULL);
1495 ts = g_slice_new0 (GTestSuite);
1496 ts->name = g_strdup (suite_name);
1502 * @suite: a #GTestSuite
1503 * @test_case: a #GTestCase
1505 * Adds @test_case to @suite.
1510 g_test_suite_add (GTestSuite *suite,
1511 GTestCase *test_case)
1513 g_return_if_fail (suite != NULL);
1514 g_return_if_fail (test_case != NULL);
1516 suite->cases = g_slist_prepend (suite->cases, test_case);
1520 * g_test_suite_add_suite:
1521 * @suite: a #GTestSuite
1522 * @nestedsuite: another #GTestSuite
1524 * Adds @nestedsuite to @suite.
1529 g_test_suite_add_suite (GTestSuite *suite,
1530 GTestSuite *nestedsuite)
1532 g_return_if_fail (suite != NULL);
1533 g_return_if_fail (nestedsuite != NULL);
1535 suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1539 * g_test_queue_free:
1540 * @gfree_pointer: the pointer to be stored.
1542 * Enqueue a pointer to be released with g_free() during the next
1543 * teardown phase. This is equivalent to calling g_test_queue_destroy()
1544 * with a destroy callback of g_free().
1549 g_test_queue_free (gpointer gfree_pointer)
1552 g_test_queue_destroy (g_free, gfree_pointer);
1556 * g_test_queue_destroy:
1557 * @destroy_func: Destroy callback for teardown phase.
1558 * @destroy_data: Destroy callback data.
1560 * This function enqueus a callback @destroy_func() to be executed
1561 * during the next test case teardown phase. This is most useful
1562 * to auto destruct allocted test resources at the end of a test run.
1563 * Resources are released in reverse queue order, that means enqueueing
1564 * callback A before callback B will cause B() to be called before
1565 * A() during teardown.
1570 g_test_queue_destroy (GDestroyNotify destroy_func,
1571 gpointer destroy_data)
1573 DestroyEntry *dentry;
1575 g_return_if_fail (destroy_func != NULL);
1577 dentry = g_slice_new0 (DestroyEntry);
1578 dentry->destroy_func = destroy_func;
1579 dentry->destroy_data = destroy_data;
1580 dentry->next = test_destroy_queue;
1581 test_destroy_queue = dentry;
1585 test_case_run (GTestCase *tc)
1587 gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1588 gboolean success = TRUE;
1590 test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1591 if (++test_run_count <= test_skip_count)
1592 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1593 else if (test_run_list)
1595 g_print ("%s\n", test_run_name);
1596 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1600 GTimer *test_run_timer = g_timer_new();
1601 long double largs[3];
1603 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1605 test_run_success = TRUE;
1606 g_test_log_set_fatal_handler (NULL, NULL);
1607 g_timer_start (test_run_timer);
1608 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1609 test_run_seed (test_run_seedstr);
1610 if (tc->fixture_setup)
1611 tc->fixture_setup (fixture, tc->test_data);
1612 tc->fixture_test (fixture, tc->test_data);
1614 while (test_destroy_queue)
1616 DestroyEntry *dentry = test_destroy_queue;
1617 test_destroy_queue = dentry->next;
1618 dentry->destroy_func (dentry->destroy_data);
1619 g_slice_free (DestroyEntry, dentry);
1621 if (tc->fixture_teardown)
1622 tc->fixture_teardown (fixture, tc->test_data);
1623 if (tc->fixture_size)
1625 g_timer_stop (test_run_timer);
1626 success = test_run_success;
1627 test_run_success = FALSE;
1628 largs[0] = success ? 0 : 1; /* OK */
1629 largs[1] = test_run_forks;
1630 largs[2] = g_timer_elapsed (test_run_timer, NULL);
1631 g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1632 g_timer_destroy (test_run_timer);
1634 g_free (test_run_name);
1635 test_run_name = old_name;
1636 g_free (test_uri_base);
1637 test_uri_base = old_base;
1643 g_test_run_suite_internal (GTestSuite *suite,
1647 gchar *rest, *old_name = test_run_name;
1648 GSList *slist, *reversed;
1650 g_return_val_if_fail (suite != NULL, -1);
1652 while (path[0] == '/')
1655 rest = strchr (path, '/');
1656 l = rest ? MIN (l, rest - path) : l;
1657 test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1658 reversed = g_slist_reverse (g_slist_copy (suite->cases));
1659 for (slist = reversed; slist; slist = slist->next)
1661 GTestCase *tc = slist->data;
1662 guint n = l ? strlen (tc->name) : 0;
1663 if (l == n && strncmp (path, tc->name, n) == 0)
1665 if (!test_case_run (tc))
1669 g_slist_free (reversed);
1670 reversed = g_slist_reverse (g_slist_copy (suite->suites));
1671 for (slist = reversed; slist; slist = slist->next)
1673 GTestSuite *ts = slist->data;
1674 guint n = l ? strlen (ts->name) : 0;
1675 if (l == n && strncmp (path, ts->name, n) == 0)
1676 n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
1678 g_slist_free (reversed);
1679 g_free (test_run_name);
1680 test_run_name = old_name;
1687 * @suite: a #GTestSuite
1689 * Execute the tests within @suite and all nested #GTestSuites.
1690 * The test suites to be executed are filtered according to
1691 * test path arguments (-p <replaceable>testpath</replaceable>)
1692 * as parsed by g_test_init().
1693 * g_test_run_suite() or g_test_run() may only be called once
1696 * Returns: 0 on success
1701 g_test_run_suite (GTestSuite *suite)
1705 g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1706 g_return_val_if_fail (g_test_run_once == TRUE, -1);
1708 g_test_run_once = FALSE;
1711 test_paths = g_slist_prepend (test_paths, "");
1714 const char *rest, *path = test_paths->data;
1715 guint l, n = strlen (suite->name);
1716 test_paths = g_slist_delete_link (test_paths, test_paths);
1717 while (path[0] == '/')
1719 if (!n) /* root suite, run unconditionally */
1721 n_bad += g_test_run_suite_internal (suite, path);
1724 /* regular suite, match path */
1725 rest = strchr (path, '/');
1727 l = rest ? MIN (l, rest - path) : l;
1728 if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1729 n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
1736 gtest_default_log_handler (const gchar *log_domain,
1737 GLogLevelFlags log_level,
1738 const gchar *message,
1739 gpointer unused_data)
1741 const gchar *strv[16];
1742 gboolean fatal = FALSE;
1748 strv[i++] = log_domain;
1751 if (log_level & G_LOG_FLAG_FATAL)
1753 strv[i++] = "FATAL-";
1756 if (log_level & G_LOG_FLAG_RECURSION)
1757 strv[i++] = "RECURSIVE-";
1758 if (log_level & G_LOG_LEVEL_ERROR)
1759 strv[i++] = "ERROR";
1760 if (log_level & G_LOG_LEVEL_CRITICAL)
1761 strv[i++] = "CRITICAL";
1762 if (log_level & G_LOG_LEVEL_WARNING)
1763 strv[i++] = "WARNING";
1764 if (log_level & G_LOG_LEVEL_MESSAGE)
1765 strv[i++] = "MESSAGE";
1766 if (log_level & G_LOG_LEVEL_INFO)
1768 if (log_level & G_LOG_LEVEL_DEBUG)
1769 strv[i++] = "DEBUG";
1771 strv[i++] = message;
1774 msg = g_strjoinv ("", (gchar**) strv);
1775 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
1776 g_log_default_handler (log_domain, log_level, message, unused_data);
1782 g_assertion_message (const char *domain,
1786 const char *message)
1792 message = "code should not be reached";
1793 g_snprintf (lstr, 32, "%d", line);
1794 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1795 "ERROR:", file, ":", lstr, ":",
1796 func, func[0] ? ":" : "",
1797 " ", message, NULL);
1798 g_printerr ("**\n%s\n", s);
1800 /* store assertion message in global variable, so that it can be found in a
1802 if (__glib_assert_msg != NULL)
1803 /* free the old one */
1804 free (__glib_assert_msg);
1805 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
1806 strcpy (__glib_assert_msg, s);
1808 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
1814 g_assertion_message_expr (const char *domain,
1820 char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1821 g_assertion_message (domain, file, line, func, s);
1826 g_assertion_message_cmpnum (const char *domain,
1839 case 'i': s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
1840 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;
1841 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
1842 /* ideally use: floats=%.7g double=%.17g */
1844 g_assertion_message (domain, file, line, func, s);
1849 g_assertion_message_cmpstr (const char *domain,
1858 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1859 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1860 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1863 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1866 g_assertion_message (domain, file, line, func, s);
1871 g_assertion_message_error (const char *domain,
1876 const GError *error,
1877 GQuark error_domain,
1882 /* This is used by both g_assert_error() and g_assert_no_error(), so there
1883 * are three cases: expected an error but got the wrong error, expected
1884 * an error but got no error, and expected no error but got an error.
1887 gstring = g_string_new ("assertion failed ");
1889 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
1890 g_quark_to_string (error_domain), error_code);
1892 g_string_append_printf (gstring, "(%s == NULL): ", expr);
1895 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
1896 g_quark_to_string (error->domain), error->code);
1898 g_string_append_printf (gstring, "%s is NULL", expr);
1900 g_assertion_message (domain, file, line, func, gstring->str);
1901 g_string_free (gstring, TRUE);
1906 * @str1: a C string or %NULL
1907 * @str2: another C string or %NULL
1909 * Compares @str1 and @str2 like strcmp(). Handles %NULL
1910 * gracefully by sorting it before non-%NULL strings.
1911 * Comparing two %NULL pointers returns 0.
1913 * Returns: -1, 0 or 1, if @str1 is <, == or > than @str2.
1918 g_strcmp0 (const char *str1,
1922 return -(str1 != str2);
1924 return str1 != str2;
1925 return strcmp (str1, str2);
1929 static int /* 0 on success */
1930 kill_child (int pid,
1935 if (patience >= 3) /* try graceful reap */
1937 if (waitpid (pid, status, WNOHANG) > 0)
1940 if (patience >= 2) /* try SIGHUP */
1943 if (waitpid (pid, status, WNOHANG) > 0)
1945 g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1946 if (waitpid (pid, status, WNOHANG) > 0)
1948 g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
1949 if (waitpid (pid, status, WNOHANG) > 0)
1951 g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
1952 if (waitpid (pid, status, WNOHANG) > 0)
1955 if (patience >= 1) /* try SIGTERM */
1957 kill (pid, SIGTERM);
1958 if (waitpid (pid, status, WNOHANG) > 0)
1960 g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
1961 if (waitpid (pid, status, WNOHANG) > 0)
1963 g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
1964 if (waitpid (pid, status, WNOHANG) > 0)
1968 kill (pid, SIGKILL);
1970 wr = waitpid (pid, status, 0);
1971 while (wr < 0 && errno == EINTR);
1977 g_string_must_read (GString *gstring,
1980 #define STRING_BUFFER_SIZE 4096
1981 char buf[STRING_BUFFER_SIZE];
1984 bytes = read (fd, buf, sizeof (buf));
1986 return 0; /* EOF, calling this function assumes data is available */
1989 g_string_append_len (gstring, buf, bytes);
1992 else if (bytes < 0 && errno == EINTR)
1994 else /* bytes < 0 */
1996 g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1997 return 1; /* ignore error after warning */
2002 g_string_write_out (GString *gstring,
2006 if (*stringpos < gstring->len)
2010 r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
2011 while (r < 0 && errno == EINTR);
2012 *stringpos += MAX (r, 0);
2017 test_trap_clear (void)
2019 test_trap_last_status = 0;
2020 test_trap_last_pid = 0;
2021 g_free (test_trap_last_stdout);
2022 test_trap_last_stdout = NULL;
2023 g_free (test_trap_last_stderr);
2024 test_trap_last_stderr = NULL;
2035 ret = dup2 (fd1, fd2);
2036 while (ret < 0 && errno == EINTR);
2041 test_time_stamp (void)
2045 g_get_current_time (&tv);
2047 stamp = stamp * 1000000 + tv.tv_usec;
2055 * @usec_timeout: Timeout for the forked test in micro seconds.
2056 * @test_trap_flags: Flags to modify forking behaviour.
2058 * Fork the current test program to execute a test case that might
2059 * not return or that might abort. The forked test case is aborted
2060 * and considered failing if its run time exceeds @usec_timeout.
2062 * The forking behavior can be configured with the #GTestTrapFlags flags.
2064 * In the following example, the test code forks, the forked child
2065 * process produces some sample output and exits successfully.
2066 * The forking parent process then asserts successful child program
2067 * termination and validates child program outputs.
2071 * test_fork_patterns (void)
2073 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2075 * g_print ("some stdout text: somagic17\n");
2076 * g_printerr ("some stderr text: semagic43\n");
2077 * exit (0); /* successful test run */
2079 * g_test_trap_assert_passed();
2080 * g_test_trap_assert_stdout ("*somagic17*");
2081 * g_test_trap_assert_stderr ("*semagic43*");
2085 * This function is implemented only on Unix platforms.
2087 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2092 g_test_trap_fork (guint64 usec_timeout,
2093 GTestTrapFlags test_trap_flags)
2096 gboolean pass_on_forked_log = FALSE;
2097 int stdout_pipe[2] = { -1, -1 };
2098 int stderr_pipe[2] = { -1, -1 };
2099 int stdtst_pipe[2] = { -1, -1 };
2101 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
2102 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
2103 signal (SIGCHLD, SIG_DFL);
2104 test_trap_last_pid = fork ();
2105 if (test_trap_last_pid < 0)
2106 g_error ("failed to fork test program: %s", g_strerror (errno));
2107 if (test_trap_last_pid == 0) /* child */
2110 close (stdout_pipe[0]);
2111 close (stderr_pipe[0]);
2112 close (stdtst_pipe[0]);
2113 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2114 fd0 = open ("/dev/null", O_RDONLY);
2115 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2116 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
2119 if (stdout_pipe[1] >= 3)
2120 close (stdout_pipe[1]);
2121 if (stderr_pipe[1] >= 3)
2122 close (stderr_pipe[1]);
2123 test_log_fd = stdtst_pipe[1];
2128 GString *sout = g_string_new (NULL);
2129 GString *serr = g_string_new (NULL);
2131 int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
2133 close (stdout_pipe[1]);
2134 close (stderr_pipe[1]);
2135 close (stdtst_pipe[1]);
2136 sstamp = test_time_stamp();
2137 /* read data until we get EOF on all pipes */
2138 while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
2144 if (stdout_pipe[0] >= 0)
2145 FD_SET (stdout_pipe[0], &fds);
2146 if (stderr_pipe[0] >= 0)
2147 FD_SET (stderr_pipe[0], &fds);
2148 if (stdtst_pipe[0] >= 0)
2149 FD_SET (stdtst_pipe[0], &fds);
2151 tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
2152 ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
2153 if (ret < 0 && errno != EINTR)
2155 g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2158 if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
2159 g_string_must_read (sout, stdout_pipe[0]) == 0)
2161 close (stdout_pipe[0]);
2162 stdout_pipe[0] = -1;
2164 if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
2165 g_string_must_read (serr, stderr_pipe[0]) == 0)
2167 close (stderr_pipe[0]);
2168 stderr_pipe[0] = -1;
2170 if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
2172 guint8 buffer[4096];
2173 gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
2174 if (r > 0 && test_log_fd > 0)
2176 l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
2177 while (l < 0 && errno == EINTR);
2178 if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
2180 close (stdtst_pipe[0]);
2181 stdtst_pipe[0] = -1;
2184 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
2185 g_string_write_out (sout, 1, &soutpos);
2186 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
2187 g_string_write_out (serr, 2, &serrpos);
2190 guint64 nstamp = test_time_stamp();
2192 sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
2193 if (usec_timeout < nstamp - sstamp)
2195 /* timeout reached, need to abort the child now */
2196 kill_child (test_trap_last_pid, &status, 3);
2197 test_trap_last_status = 1024; /* timeout */
2198 if (0 && WIFSIGNALED (status))
2199 g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
2205 if (stdout_pipe[0] != -1)
2206 close (stdout_pipe[0]);
2207 if (stderr_pipe[0] != -1)
2208 close (stderr_pipe[0]);
2209 if (stdtst_pipe[0] != -1)
2210 close (stdtst_pipe[0]);
2215 wr = waitpid (test_trap_last_pid, &status, 0);
2216 while (wr < 0 && errno == EINTR);
2217 if (WIFEXITED (status)) /* normal exit */
2218 test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
2219 else if (WIFSIGNALED (status))
2220 test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
2221 else /* WCOREDUMP (status) */
2222 test_trap_last_status = 512; /* coredump */
2224 test_trap_last_stdout = g_string_free (sout, FALSE);
2225 test_trap_last_stderr = g_string_free (serr, FALSE);
2229 g_message ("Not implemented: g_test_trap_fork");
2236 * g_test_trap_has_passed:
2238 * Check the result of the last g_test_trap_fork() call.
2240 * Returns: %TRUE if the last forked child terminated successfully.
2245 g_test_trap_has_passed (void)
2247 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
2251 * g_test_trap_reached_timeout:
2253 * Check the result of the last g_test_trap_fork() call.
2255 * Returns: %TRUE if the last forked child got killed due to a fork timeout.
2260 g_test_trap_reached_timeout (void)
2262 return 0 != (test_trap_last_status & 1024); /* timeout flag */
2266 g_test_trap_assertions (const char *domain,
2270 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
2271 const char *pattern)
2274 gboolean must_pass = assertion_flags == 0;
2275 gboolean must_fail = assertion_flags == 1;
2276 gboolean match_result = 0 == (assertion_flags & 1);
2277 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
2278 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
2279 const char *match_error = match_result ? "failed to match" : "contains invalid match";
2280 if (test_trap_last_pid == 0)
2281 g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
2282 if (must_pass && !g_test_trap_has_passed())
2284 char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
2285 g_assertion_message (domain, file, line, func, msg);
2288 if (must_fail && g_test_trap_has_passed())
2290 char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
2291 g_assertion_message (domain, file, line, func, msg);
2294 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
2296 char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
2297 g_assertion_message (domain, file, line, func, msg);
2300 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
2302 char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
2303 g_assertion_message (domain, file, line, func, msg);
2310 gstring_overwrite_int (GString *gstring,
2314 vuint = g_htonl (vuint);
2315 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
2319 gstring_append_int (GString *gstring,
2322 vuint = g_htonl (vuint);
2323 g_string_append_len (gstring, (const gchar*) &vuint, 4);
2327 gstring_append_double (GString *gstring,
2330 union { double vdouble; guint64 vuint64; } u;
2331 u.vdouble = vdouble;
2332 u.vuint64 = GUINT64_TO_BE (u.vuint64);
2333 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
2337 g_test_log_dump (GTestLogMsg *msg,
2340 GString *gstring = g_string_sized_new (1024);
2342 gstring_append_int (gstring, 0); /* message length */
2343 gstring_append_int (gstring, msg->log_type);
2344 gstring_append_int (gstring, msg->n_strings);
2345 gstring_append_int (gstring, msg->n_nums);
2346 gstring_append_int (gstring, 0); /* reserved */
2347 for (ui = 0; ui < msg->n_strings; ui++)
2349 guint l = strlen (msg->strings[ui]);
2350 gstring_append_int (gstring, l);
2351 g_string_append_len (gstring, msg->strings[ui], l);
2353 for (ui = 0; ui < msg->n_nums; ui++)
2354 gstring_append_double (gstring, msg->nums[ui]);
2355 *len = gstring->len;
2356 gstring_overwrite_int (gstring, 0, *len); /* message length */
2357 return (guint8*) g_string_free (gstring, FALSE);
2360 static inline long double
2361 net_double (const gchar **ipointer)
2363 union { guint64 vuint64; double vdouble; } u;
2364 guint64 aligned_int64;
2365 memcpy (&aligned_int64, *ipointer, 8);
2367 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
2371 static inline guint32
2372 net_int (const gchar **ipointer)
2374 guint32 aligned_int;
2375 memcpy (&aligned_int, *ipointer, 4);
2377 return g_ntohl (aligned_int);
2381 g_test_log_extract (GTestLogBuffer *tbuffer)
2383 const gchar *p = tbuffer->data->str;
2386 if (tbuffer->data->len < 4 * 5)
2388 mlength = net_int (&p);
2389 if (tbuffer->data->len < mlength)
2391 msg.log_type = net_int (&p);
2392 msg.n_strings = net_int (&p);
2393 msg.n_nums = net_int (&p);
2394 if (net_int (&p) == 0)
2397 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
2398 msg.nums = g_new0 (long double, msg.n_nums);
2399 for (ui = 0; ui < msg.n_strings; ui++)
2401 guint sl = net_int (&p);
2402 msg.strings[ui] = g_strndup (p, sl);
2405 for (ui = 0; ui < msg.n_nums; ui++)
2406 msg.nums[ui] = net_double (&p);
2407 if (p <= tbuffer->data->str + mlength)
2409 g_string_erase (tbuffer->data, 0, mlength);
2410 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
2415 g_strfreev (msg.strings);
2416 g_error ("corrupt log stream from test program");
2421 * g_test_log_buffer_new:
2423 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2426 g_test_log_buffer_new (void)
2428 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
2429 tb->data = g_string_sized_new (1024);
2434 * g_test_log_buffer_free
2436 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2439 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
2441 g_return_if_fail (tbuffer != NULL);
2442 while (tbuffer->msgs)
2443 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
2444 g_string_free (tbuffer->data, TRUE);
2449 * g_test_log_buffer_push
2451 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2454 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
2456 const guint8 *bytes)
2458 g_return_if_fail (tbuffer != NULL);
2461 gboolean more_messages;
2462 g_return_if_fail (bytes != NULL);
2463 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
2465 more_messages = g_test_log_extract (tbuffer);
2466 while (more_messages);
2471 * g_test_log_buffer_pop:
2473 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
2476 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
2478 GTestLogMsg *msg = NULL;
2479 g_return_val_if_fail (tbuffer != NULL, NULL);
2482 GSList *slist = g_slist_last (tbuffer->msgs);
2484 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
2490 * g_test_log_msg_free:
2492 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2495 g_test_log_msg_free (GTestLogMsg *tmsg)
2497 g_return_if_fail (tmsg != NULL);
2498 g_strfreev (tmsg->strings);
2499 g_free (tmsg->nums);
2503 /* --- macros docs START --- */
2506 * @testpath: The test path for a new test case.
2507 * @Fixture: The type of a fixture data structure.
2508 * @tdata: Data argument for the test functions.
2509 * @fsetup: The function to set up the fixture data.
2510 * @ftest: The actual test function.
2511 * @fteardown: The function to tear down the fixture data.
2513 * Hook up a new test case at @testpath, similar to g_test_add_func().
2514 * A fixture data structure with setup and teardown function may be provided
2515 * though, similar to g_test_create_case().
2516 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2517 * fteardown() callbacks can expect a @Fixture pointer as first argument in
2518 * a type safe manner.
2522 /* --- macros docs END --- */