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"
24 #include "gfileutils.h"
26 #include <sys/types.h>
43 #ifdef HAVE_SYS_SELECT_H
44 #include <sys/select.h>
45 #endif /* HAVE_SYS_SELECT_H */
50 #include "gstrfuncs.h"
58 * @short_description: a test framework
59 * @see_also: <link linkend="gtester">gtester</link>,
60 * <link linkend="gtester-report">gtester-report</link>
62 * GLib provides a framework for writing and maintaining unit tests
63 * in parallel to the code they are testing. The API is designed according
64 * to established concepts found in the other test frameworks (JUnit, NUnit,
65 * RUnit), which in turn is based on smalltalk unit testing concepts.
69 * <term>Test case</term>
70 * <listitem>Tests (test methods) are grouped together with their
71 * fixture into test cases.</listitem>
74 * <term>Fixture</term>
75 * <listitem>A test fixture consists of fixture data and setup and
76 * teardown methods to establish the environment for the test
77 * functions. We use fresh fixtures, i.e. fixtures are newly set
78 * up and torn down around each test invocation to avoid dependencies
79 * between tests.</listitem>
82 * <term>Test suite</term>
83 * <listitem>Test cases can be grouped into test suites, to allow
84 * subsets of the available tests to be run. Test suites can be
85 * grouped into other test suites as well.</listitem>
88 * The API is designed to handle creation and registration of test suites
89 * and test cases implicitly. A simple call like
91 * g_test_add_func ("/misc/assertions", test_assertions);
93 * creates a test suite called "misc" with a single test case named
94 * "assertions", which consists of running the test_assertions function.
96 * In addition to the traditional g_assert(), the test framework provides
97 * an extended set of assertions for string and numerical comparisons:
98 * g_assert_cmpfloat(), g_assert_cmpint(), g_assert_cmpuint(),
99 * g_assert_cmphex(), g_assert_cmpstr(). The advantage of these variants
100 * over plain g_assert() is that the assertion messages can be more
101 * elaborate, and include the values of the compared entities.
103 * GLib ships with two utilities called gtester and gtester-report to
104 * facilitate running tests and producing nicely formatted test reports.
110 * Returns %TRUE if tests are run in quick mode.
111 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
112 * there is no "medium speed".
114 * Returns: %TRUE if in quick mode
120 * Returns %TRUE if tests are run in slow mode.
121 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
122 * there is no "medium speed".
124 * Returns: the opposite of g_test_quick()
130 * Returns %TRUE if tests are run in thorough mode, equivalent to
133 * Returns: the same thing as g_test_slow()
139 * Returns %TRUE if tests are run in performance mode.
141 * Returns: %TRUE if in performance mode
147 * Returns %TRUE if tests may provoke assertions and other formally-undefined
148 * behaviour under g_test_trap_fork(), to verify that appropriate warnings
149 * are given. It can be useful to turn this off if running tests under
152 * Returns: %TRUE if tests may provoke programming errors
158 * Returns %TRUE if tests are run in verbose mode.
159 * The default is neither g_test_verbose() nor g_test_quiet().
161 * Returns: %TRUE if in verbose mode
167 * Returns %TRUE if tests are run in quiet mode.
168 * The default is neither g_test_verbose() nor g_test_quiet().
170 * Returns: %TRUE if in quiet mode
174 * g_test_queue_unref:
175 * @gobject: the object to unref
177 * Enqueue an object to be released with g_object_unref() during
178 * the next teardown phase. This is equivalent to calling
179 * g_test_queue_destroy() with a destroy callback of g_object_unref().
186 * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
187 * <filename>/dev/null</filename> so it cannot be observed on the
188 * console during test runs. The actual output is still captured
189 * though to allow later tests with g_test_trap_assert_stdout().
190 * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
191 * <filename>/dev/null</filename> so it cannot be observed on the
192 * console during test runs. The actual output is still captured
193 * though to allow later tests with g_test_trap_assert_stderr().
194 * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
195 * forked child process is shared with stdin of its parent process.
196 * It is redirected to <filename>/dev/null</filename> otherwise.
198 * Test traps are guards around forked tests.
199 * These flags determine what traps to set.
203 * g_test_trap_assert_passed:
205 * Assert that the last forked test passed.
206 * See g_test_trap_fork().
212 * g_test_trap_assert_failed:
214 * Assert that the last forked test failed.
215 * See g_test_trap_fork().
217 * This is sometimes used to test situations that are formally considered to
218 * be undefined behaviour, like inputs that fail a g_return_if_fail()
219 * check. In these situations you should skip the entire test, including the
220 * call to g_test_trap_fork(), unless g_test_undefined() returns %TRUE
221 * to indicate that undefined behaviour may be tested.
227 * g_test_trap_assert_stdout:
228 * @soutpattern: a glob-style
229 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
231 * Assert that the stdout output of the last forked test matches
232 * @soutpattern. See g_test_trap_fork().
238 * g_test_trap_assert_stdout_unmatched:
239 * @soutpattern: a glob-style
240 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
242 * Assert that the stdout output of the last forked test
243 * does not match @soutpattern. See g_test_trap_fork().
249 * g_test_trap_assert_stderr:
250 * @serrpattern: a glob-style
251 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
253 * Assert that the stderr output of the last forked test
254 * matches @serrpattern. See g_test_trap_fork().
256 * This is sometimes used to test situations that are formally considered to
257 * be undefined behaviour, like inputs that fail a g_return_if_fail()
258 * check. In these situations you should skip the entire test, including the
259 * call to g_test_trap_fork(), unless g_test_undefined() returns %TRUE
260 * to indicate that undefined behaviour may be tested.
266 * g_test_trap_assert_stderr_unmatched:
267 * @serrpattern: a glob-style
268 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
270 * Assert that the stderr output of the last forked test
271 * does not match @serrpattern. See g_test_trap_fork().
279 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
280 * for details on test case random numbers.
287 * @expr: the expression to check
289 * Debugging macro to terminate the application if the assertion
290 * fails. If the assertion fails (i.e. the expression is not true),
291 * an error message is logged and the application is terminated.
293 * The macro can be turned off in final releases of code by defining
294 * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
298 * g_assert_not_reached:
300 * Debugging macro to terminate the application if it is ever
301 * reached. If it is reached, an error message is logged and the
302 * application is terminated.
304 * The macro can be turned off in final releases of code by defining
305 * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
310 * @s1: a string (may be %NULL)
311 * @cmp: The comparison operator to use.
312 * One of ==, !=, <, >, <=, >=.
313 * @s2: another string (may be %NULL)
315 * Debugging macro to terminate the application with a warning
316 * message if a string comparison fails. The strings are compared
319 * The effect of <literal>g_assert_cmpstr (s1, op, s2)</literal> is
320 * the same as <literal>g_assert (g_strcmp0 (s1, s2) op 0)</literal>.
321 * The advantage of this macro is that it can produce a message that
322 * includes the actual values of @s1 and @s2.
325 * g_assert_cmpstr (mystring, ==, "fubar");
334 * @cmp: The comparison operator to use.
335 * One of ==, !=, <, >, <=, >=.
336 * @n2: another integer
338 * Debugging macro to terminate the application with a warning
339 * message if an integer comparison fails.
341 * The effect of <literal>g_assert_cmpint (n1, op, n2)</literal> is
342 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
343 * of this macro is that it can produce a message that includes the
344 * actual values of @n1 and @n2.
351 * @n1: an unsigned integer
352 * @cmp: The comparison operator to use.
353 * One of ==, !=, <, >, <=, >=.
354 * @n2: another unsigned integer
356 * Debugging macro to terminate the application with a warning
357 * message if an unsigned integer comparison fails.
359 * The effect of <literal>g_assert_cmpuint (n1, op, n2)</literal> is
360 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
361 * of this macro is that it can produce a message that includes the
362 * actual values of @n1 and @n2.
369 * @n1: an unsigned integer
370 * @cmp: The comparison operator to use.
371 * One of ==, !=, <, >, <=, >=.
372 * @n2: another unsigned integer
374 * Debugging macro to terminate the application with a warning
375 * message if an unsigned integer comparison fails.
377 * This is a variant of g_assert_cmpuint() that displays the numbers
378 * in hexadecimal notation in the message.
385 * @n1: an floating point number
386 * @cmp: The comparison operator to use.
387 * One of ==, !=, <, >, <=, >=.
388 * @n2: another floating point number
390 * Debugging macro to terminate the application with a warning
391 * message if a floating point number comparison fails.
393 * The effect of <literal>g_assert_cmpfloat (n1, op, n2)</literal> is
394 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
395 * of this macro is that it can produce a message that includes the
396 * actual values of @n1 and @n2.
403 * @err: a #GError, possibly %NULL
405 * Debugging macro to terminate the application with a warning
406 * message if a method has returned a #GError.
408 * The effect of <literal>g_assert_no_error (err)</literal> is
409 * the same as <literal>g_assert (err == NULL)</literal>. The advantage
410 * of this macro is that it can produce a message that includes
411 * the error message and code.
418 * @err: a #GError, possibly %NULL
419 * @dom: the expected error domain (a #GQuark)
420 * @c: the expected error code
422 * Debugging macro to terminate the application with a warning
423 * message if a method has not returned the correct #GError.
425 * The effect of <literal>g_assert_error (err, dom, c)</literal> is
426 * the same as <literal>g_assert (err != NULL && err->domain
427 * == dom && err->code == c)</literal>. The advantage of this
428 * macro is that it can produce a message that includes the incorrect
429 * error message and code.
431 * This can only be used to test for a specific error. If you want to
432 * test that @err is set, but don't care what it's set to, just use
433 * <literal>g_assert (err != NULL)</literal>
441 * An opaque structure representing a test case.
447 * An opaque structure representing a test suite.
451 /* Global variable for storing assertion messages; this is the counterpart to
452 * glibc's (private) __abort_msg variable, and allows developers and crash
453 * analysis systems like Apport and ABRT to fish out assertion messages from
454 * core dumps, instead of having to catch them on screen output.
456 char *__glib_assert_msg = NULL;
458 /* --- structures --- */
463 void (*fixture_setup) (void*, gconstpointer);
464 void (*fixture_test) (void*, gconstpointer);
465 void (*fixture_teardown) (void*, gconstpointer);
474 typedef struct DestroyEntry DestroyEntry;
478 GDestroyNotify destroy_func;
479 gpointer destroy_data;
482 /* --- prototypes --- */
483 static void test_run_seed (const gchar *rseed);
484 static void test_trap_clear (void);
485 static guint8* g_test_log_dump (GTestLogMsg *msg,
487 static void gtest_default_log_handler (const gchar *log_domain,
488 GLogLevelFlags log_level,
489 const gchar *message,
490 gpointer unused_data);
493 /* --- variables --- */
494 static int test_log_fd = -1;
495 static gboolean test_mode_fatal = TRUE;
496 static gboolean g_test_run_once = TRUE;
497 static gboolean test_run_list = FALSE;
498 static gchar *test_run_seedstr = NULL;
499 static GRand *test_run_rand = NULL;
500 static gchar *test_run_name = "";
501 static guint test_run_forks = 0;
502 static guint test_run_count = 0;
503 static guint test_run_success = FALSE;
504 static guint test_skip_count = 0;
505 static GTimer *test_user_timer = NULL;
506 static double test_user_stamp = 0;
507 static GSList *test_paths = NULL;
508 static GSList *test_paths_skipped = NULL;
509 static GTestSuite *test_suite_root = NULL;
510 static int test_trap_last_status = 0;
511 static int test_trap_last_pid = 0;
512 static char *test_trap_last_stdout = NULL;
513 static char *test_trap_last_stderr = NULL;
514 static char *test_uri_base = NULL;
515 static gboolean test_debug_log = FALSE;
516 static DestroyEntry *test_destroy_queue = NULL;
517 static GTestConfig mutable_test_config_vars = {
518 FALSE, /* test_initialized */
519 TRUE, /* test_quick */
520 FALSE, /* test_perf */
521 FALSE, /* test_verbose */
522 FALSE, /* test_quiet */
523 TRUE, /* test_undefined */
525 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
527 /* --- functions --- */
529 g_test_log_type_name (GTestLogType log_type)
533 case G_TEST_LOG_NONE: return "none";
534 case G_TEST_LOG_ERROR: return "error";
535 case G_TEST_LOG_START_BINARY: return "binary";
536 case G_TEST_LOG_LIST_CASE: return "list";
537 case G_TEST_LOG_SKIP_CASE: return "skip";
538 case G_TEST_LOG_START_CASE: return "start";
539 case G_TEST_LOG_STOP_CASE: return "stop";
540 case G_TEST_LOG_MIN_RESULT: return "minperf";
541 case G_TEST_LOG_MAX_RESULT: return "maxperf";
542 case G_TEST_LOG_MESSAGE: return "message";
548 g_test_log_send (guint n_bytes,
549 const guint8 *buffer)
551 if (test_log_fd >= 0)
555 r = write (test_log_fd, buffer, n_bytes);
556 while (r < 0 && errno == EINTR);
560 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
563 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
564 msg = g_test_log_buffer_pop (lbuffer);
565 g_warn_if_fail (msg != NULL);
566 g_warn_if_fail (lbuffer->data->len == 0);
567 g_test_log_buffer_free (lbuffer);
569 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
570 for (ui = 0; ui < msg->n_strings; ui++)
571 g_printerr (":{%s}", msg->strings[ui]);
575 for (ui = 0; ui < msg->n_nums; ui++)
576 g_printerr ("%s%.16Lg", ui ? ";" : "", msg->nums[ui]);
579 g_printerr (":LOG*}\n");
580 g_test_log_msg_free (msg);
585 g_test_log (GTestLogType lbit,
586 const gchar *string1,
587 const gchar *string2,
591 gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
593 gchar *astrings[3] = { NULL, NULL, NULL };
599 case G_TEST_LOG_START_BINARY:
600 if (g_test_verbose())
601 g_print ("GTest: random seed: %s\n", string2);
603 case G_TEST_LOG_STOP_CASE:
604 if (g_test_verbose())
605 g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
606 else if (!g_test_quiet())
607 g_print ("%s\n", fail ? "FAIL" : "OK");
608 if (fail && test_mode_fatal)
611 case G_TEST_LOG_MIN_RESULT:
612 if (g_test_verbose())
613 g_print ("(MINPERF:%s)\n", string1);
615 case G_TEST_LOG_MAX_RESULT:
616 if (g_test_verbose())
617 g_print ("(MAXPERF:%s)\n", string1);
619 case G_TEST_LOG_MESSAGE:
620 if (g_test_verbose())
621 g_print ("(MSG: %s)\n", string1);
627 msg.n_strings = (string1 != NULL) + (string1 && string2);
628 msg.strings = astrings;
629 astrings[0] = (gchar*) string1;
630 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
633 dbuffer = g_test_log_dump (&msg, &dbufferlen);
634 g_test_log_send (dbufferlen, dbuffer);
639 case G_TEST_LOG_START_CASE:
640 if (g_test_verbose())
641 g_print ("GTest: run: %s\n", string1);
642 else if (!g_test_quiet())
643 g_print ("%s: ", string1);
649 /* We intentionally parse the command line without GOptionContext
650 * because otherwise you would never be able to test it.
653 parse_args (gint *argc_p,
656 guint argc = *argc_p;
657 gchar **argv = *argv_p;
659 /* parse known args */
660 for (i = 1; i < argc; i++)
662 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
664 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
665 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
666 g_log_set_always_fatal (fatal_mask);
669 else if (strcmp (argv[i], "--keep-going") == 0 ||
670 strcmp (argv[i], "-k") == 0)
672 test_mode_fatal = FALSE;
675 else if (strcmp (argv[i], "--debug-log") == 0)
677 test_debug_log = TRUE;
680 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
682 gchar *equal = argv[i] + 12;
684 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
685 else if (i + 1 < argc)
688 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
692 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
694 gchar *equal = argv[i] + 16;
696 test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
697 else if (i + 1 < argc)
700 test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
704 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
706 gchar *equal = argv[i] + 2;
708 test_paths = g_slist_prepend (test_paths, equal + 1);
709 else if (i + 1 < argc)
712 test_paths = g_slist_prepend (test_paths, argv[i]);
716 else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
718 gchar *equal = argv[i] + 2;
720 test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
721 else if (i + 1 < argc)
724 test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
728 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
730 gchar *equal = argv[i] + 2;
731 const gchar *mode = "";
734 else if (i + 1 < argc)
739 if (strcmp (mode, "perf") == 0)
740 mutable_test_config_vars.test_perf = TRUE;
741 else if (strcmp (mode, "slow") == 0)
742 mutable_test_config_vars.test_quick = FALSE;
743 else if (strcmp (mode, "thorough") == 0)
744 mutable_test_config_vars.test_quick = FALSE;
745 else if (strcmp (mode, "quick") == 0)
747 mutable_test_config_vars.test_quick = TRUE;
748 mutable_test_config_vars.test_perf = FALSE;
750 else if (strcmp (mode, "undefined") == 0)
751 mutable_test_config_vars.test_undefined = TRUE;
752 else if (strcmp (mode, "no-undefined") == 0)
753 mutable_test_config_vars.test_undefined = FALSE;
755 g_error ("unknown test mode: -m %s", mode);
758 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
760 mutable_test_config_vars.test_quiet = TRUE;
761 mutable_test_config_vars.test_verbose = FALSE;
764 else if (strcmp ("--verbose", argv[i]) == 0)
766 mutable_test_config_vars.test_quiet = FALSE;
767 mutable_test_config_vars.test_verbose = TRUE;
770 else if (strcmp ("-l", argv[i]) == 0)
772 test_run_list = TRUE;
775 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
777 gchar *equal = argv[i] + 6;
779 test_run_seedstr = equal + 1;
780 else if (i + 1 < argc)
783 test_run_seedstr = argv[i];
787 else if (strcmp ("-?", argv[i]) == 0 || strcmp ("--help", argv[i]) == 0)
790 " %s [OPTION...]\n\n"
792 " -?, --help Show help options\n"
794 " -l List test cases available in a test executable\n"
795 " -seed=RANDOMSEED Provide a random seed to reproduce test\n"
796 " runs using random numbers\n"
797 " --verbose Run tests verbosely\n"
798 " -q, --quiet Run tests quietly\n"
799 " -p TESTPATH execute all tests matching TESTPATH\n"
800 " -s TESTPATH skip all tests matching TESTPATH\n"
801 " -m {perf|slow|thorough|quick} Execute tests according modes\n"
802 " -m {undefined|no-undefined} Execute tests according modes\n"
803 " --debug-log debug test logging output\n"
804 " -k, --keep-going gtester-specific argument\n"
805 " --GTestLogFD=N gtester-specific argument\n"
806 " --GTestSkipCount=N gtester-specific argument\n",
813 for (i = 1; i < argc; i++)
825 * @argc: Address of the @argc parameter of the main() function.
826 * Changed if any arguments were handled.
827 * @argv: Address of the @argv parameter of main().
828 * Any parameters understood by g_test_init() stripped before return.
829 * @...: Reserved for future extension. Currently, you must pass %NULL.
831 * Initialize the GLib testing framework, e.g. by seeding the
832 * test random number generator, the name for g_get_prgname()
833 * and parsing test related command line args.
834 * So far, the following arguments are understood:
837 * <term><option>-l</option></term>
839 * list test cases available in a test executable.
843 * <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
845 * provide a random seed to reproduce test runs using random numbers.
849 * <term><option>--verbose</option></term>
850 * <listitem><para>run tests verbosely.</para></listitem>
853 * <term><option>-q</option>, <option>--quiet</option></term>
854 * <listitem><para>run tests quietly.</para></listitem>
857 * <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
859 * execute all tests matching <replaceable>TESTPATH</replaceable>.
863 * <term><option>-m {perf|slow|thorough|quick|undefined|no-undefined}</option></term>
865 * execute tests according to these test modes:
870 * performance tests, may take long and report results.
874 * <term>slow, thorough</term>
876 * slow and thorough tests, may take quite long and
883 * quick tests, should run really quickly and give good coverage.
887 * <term>undefined</term>
889 * tests for undefined behaviour, may provoke programming errors
890 * under g_test_trap_fork() to check that appropriate assertions
891 * or warnings are given
895 * <term>no-undefined</term>
897 * avoid tests for undefined behaviour
904 * <term><option>--debug-log</option></term>
905 * <listitem><para>debug test logging output.</para></listitem>
908 * <term><option>-k</option>, <option>--keep-going</option></term>
909 * <listitem><para>gtester-specific argument.</para></listitem>
912 * <term><option>--GTestLogFD <replaceable>N</replaceable></option></term>
913 * <listitem><para>gtester-specific argument.</para></listitem>
916 * <term><option>--GTestSkipCount <replaceable>N</replaceable></option></term>
917 * <listitem><para>gtester-specific argument.</para></listitem>
924 g_test_init (int *argc,
928 static char seedstr[4 + 4 * 8 + 1];
931 /* make warnings and criticals fatal for all test programs */
932 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
933 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
934 g_log_set_always_fatal (fatal_mask);
935 /* check caller args */
936 g_return_if_fail (argc != NULL);
937 g_return_if_fail (argv != NULL);
938 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
939 mutable_test_config_vars.test_initialized = TRUE;
941 va_start (args, argv);
942 vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
944 g_return_if_fail (vararg1 == NULL);
946 /* setup random seed string */
947 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
948 test_run_seedstr = seedstr;
950 /* parse args, sets up mode, changes seed, etc. */
951 parse_args (argc, argv);
952 if (!g_get_prgname())
953 g_set_prgname ((*argv)[0]);
955 /* verify GRand reliability, needed for reliable seeds */
958 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
959 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
960 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
961 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
962 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
966 /* check rand seed */
967 test_run_seed (test_run_seedstr);
969 /* report program start */
970 g_log_set_default_handler (gtest_default_log_handler, NULL);
971 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
975 test_run_seed (const gchar *rseed)
977 guint seed_failed = 0;
979 g_rand_free (test_run_rand);
980 test_run_rand = NULL;
981 while (strchr (" \t\v\r\n\f", *rseed))
983 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
985 const char *s = rseed + 4;
986 if (strlen (s) >= 32) /* require 4 * 8 chars */
988 guint32 seedarray[4];
989 gchar *p, hexbuf[9] = { 0, };
990 memcpy (hexbuf, s + 0, 8);
991 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
992 seed_failed += p != NULL && *p != 0;
993 memcpy (hexbuf, s + 8, 8);
994 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
995 seed_failed += p != NULL && *p != 0;
996 memcpy (hexbuf, s + 16, 8);
997 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
998 seed_failed += p != NULL && *p != 0;
999 memcpy (hexbuf, s + 24, 8);
1000 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
1001 seed_failed += p != NULL && *p != 0;
1004 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
1009 g_error ("Unknown or invalid random seed: %s", rseed);
1015 * Get a reproducible random integer number.
1017 * The random numbers generated by the g_test_rand_*() family of functions
1018 * change with every new test program start, unless the --seed option is
1019 * given when starting test programs.
1021 * For individual test cases however, the random number generator is
1022 * reseeded, to avoid dependencies between tests and to make --seed
1023 * effective for all test cases.
1025 * Returns: a random number from the seeded random number generator.
1030 g_test_rand_int (void)
1032 return g_rand_int (test_run_rand);
1036 * g_test_rand_int_range:
1037 * @begin: the minimum value returned by this function
1038 * @end: the smallest value not to be returned by this function
1040 * Get a reproducible random integer number out of a specified range,
1041 * see g_test_rand_int() for details on test case random numbers.
1043 * Returns: a number with @begin <= number < @end.
1048 g_test_rand_int_range (gint32 begin,
1051 return g_rand_int_range (test_run_rand, begin, end);
1055 * g_test_rand_double:
1057 * Get a reproducible random floating point number,
1058 * see g_test_rand_int() for details on test case random numbers.
1060 * Returns: a random number from the seeded random number generator.
1065 g_test_rand_double (void)
1067 return g_rand_double (test_run_rand);
1071 * g_test_rand_double_range:
1072 * @range_start: the minimum value returned by this function
1073 * @range_end: the minimum value not returned by this function
1075 * Get a reproducible random floating pointer number out of a specified range,
1076 * see g_test_rand_int() for details on test case random numbers.
1078 * Returns: a number with @range_start <= number < @range_end.
1083 g_test_rand_double_range (double range_start,
1086 return g_rand_double_range (test_run_rand, range_start, range_end);
1090 * g_test_timer_start:
1092 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1093 * to be done. Call this function again to restart the timer.
1098 g_test_timer_start (void)
1100 if (!test_user_timer)
1101 test_user_timer = g_timer_new();
1102 test_user_stamp = 0;
1103 g_timer_start (test_user_timer);
1107 * g_test_timer_elapsed:
1109 * Get the time since the last start of the timer with g_test_timer_start().
1111 * Returns: the time since the last start of the timer, as a double
1116 g_test_timer_elapsed (void)
1118 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1119 return test_user_stamp;
1123 * g_test_timer_last:
1125 * Report the last result of g_test_timer_elapsed().
1127 * Returns: the last result of g_test_timer_elapsed(), as a double
1132 g_test_timer_last (void)
1134 return test_user_stamp;
1138 * g_test_minimized_result:
1139 * @minimized_quantity: the reported value
1140 * @format: the format string of the report message
1141 * @...: arguments to pass to the printf() function
1143 * Report the result of a performance or measurement test.
1144 * The test should generally strive to minimize the reported
1145 * quantities (smaller values are better than larger ones),
1146 * this and @minimized_quantity can determine sorting
1147 * order for test result reports.
1152 g_test_minimized_result (double minimized_quantity,
1156 long double largs = minimized_quantity;
1160 va_start (args, format);
1161 buffer = g_strdup_vprintf (format, args);
1164 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1169 * g_test_maximized_result:
1170 * @maximized_quantity: the reported value
1171 * @format: the format string of the report message
1172 * @...: arguments to pass to the printf() function
1174 * Report the result of a performance or measurement test.
1175 * The test should generally strive to maximize the reported
1176 * quantities (larger values are better than smaller ones),
1177 * this and @maximized_quantity can determine sorting
1178 * order for test result reports.
1183 g_test_maximized_result (double maximized_quantity,
1187 long double largs = maximized_quantity;
1191 va_start (args, format);
1192 buffer = g_strdup_vprintf (format, args);
1195 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1201 * @format: the format string
1202 * @...: printf-like arguments to @format
1204 * Add a message to the test report.
1209 g_test_message (const char *format,
1215 va_start (args, format);
1216 buffer = g_strdup_vprintf (format, args);
1219 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1225 * @uri_pattern: the base pattern for bug URIs
1227 * Specify the base URI for bug reports.
1229 * The base URI is used to construct bug report messages for
1230 * g_test_message() when g_test_bug() is called.
1231 * Calling this function outside of a test case sets the
1232 * default base URI for all test cases. Calling it from within
1233 * a test case changes the base URI for the scope of the test
1235 * Bug URIs are constructed by appending a bug specific URI
1236 * portion to @uri_pattern, or by replacing the special string
1237 * '\%s' within @uri_pattern if that is present.
1242 g_test_bug_base (const char *uri_pattern)
1244 g_free (test_uri_base);
1245 test_uri_base = g_strdup (uri_pattern);
1250 * @bug_uri_snippet: Bug specific bug tracker URI portion.
1252 * This function adds a message to test reports that
1253 * associates a bug URI with a test case.
1254 * Bug URIs are constructed from a base URI set with g_test_bug_base()
1255 * and @bug_uri_snippet.
1260 g_test_bug (const char *bug_uri_snippet)
1264 g_return_if_fail (test_uri_base != NULL);
1265 g_return_if_fail (bug_uri_snippet != NULL);
1267 c = strstr (test_uri_base, "%s");
1270 char *b = g_strndup (test_uri_base, c - test_uri_base);
1271 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1273 g_test_message ("Bug Reference: %s", s);
1277 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1283 * Get the toplevel test suite for the test path API.
1285 * Returns: the toplevel #GTestSuite
1290 g_test_get_root (void)
1292 if (!test_suite_root)
1294 test_suite_root = g_test_create_suite ("root");
1295 g_free (test_suite_root->name);
1296 test_suite_root->name = g_strdup ("");
1299 return test_suite_root;
1305 * Runs all tests under the toplevel suite which can be retrieved
1306 * with g_test_get_root(). Similar to g_test_run_suite(), the test
1307 * cases to be run are filtered according to
1308 * test path arguments (-p <replaceable>testpath</replaceable>) as
1309 * parsed by g_test_init().
1310 * g_test_run_suite() or g_test_run() may only be called once
1313 * Returns: 0 on success
1320 return g_test_run_suite (g_test_get_root());
1324 * g_test_create_case:
1325 * @test_name: the name for the test case
1326 * @data_size: the size of the fixture data structure
1327 * @test_data: test data argument for the test functions
1328 * @data_setup: the function to set up the fixture data
1329 * @data_test: the actual test function
1330 * @data_teardown: the function to teardown the fixture data
1332 * Create a new #GTestCase, named @test_name, this API is fairly
1333 * low level, calling g_test_add() or g_test_add_func() is preferable.
1334 * When this test is executed, a fixture structure of size @data_size
1335 * will be allocated and filled with 0s. Then @data_setup is called
1336 * to initialize the fixture. After fixture setup, the actual test
1337 * function @data_test is called. Once the test run completed, the
1338 * fixture structure is torn down by calling @data_teardown and
1339 * after that the memory is released.
1341 * Splitting up a test run into fixture setup, test function and
1342 * fixture teardown is most usful if the same fixture is used for
1343 * multiple tests. In this cases, g_test_create_case() will be
1344 * called with the same fixture, but varying @test_name and
1345 * @data_test arguments.
1347 * Returns: a newly allocated #GTestCase.
1352 g_test_create_case (const char *test_name,
1354 gconstpointer test_data,
1355 GTestFixtureFunc data_setup,
1356 GTestFixtureFunc data_test,
1357 GTestFixtureFunc data_teardown)
1361 g_return_val_if_fail (test_name != NULL, NULL);
1362 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1363 g_return_val_if_fail (test_name[0] != 0, NULL);
1364 g_return_val_if_fail (data_test != NULL, NULL);
1366 tc = g_slice_new0 (GTestCase);
1367 tc->name = g_strdup (test_name);
1368 tc->test_data = (gpointer) test_data;
1369 tc->fixture_size = data_size;
1370 tc->fixture_setup = (void*) data_setup;
1371 tc->fixture_test = (void*) data_test;
1372 tc->fixture_teardown = (void*) data_teardown;
1379 * @fixture: the test fixture
1380 * @user_data: the data provided when registering the test
1382 * The type used for functions that operate on test fixtures. This is
1383 * used for the fixture setup and teardown functions as well as for the
1384 * testcases themselves.
1386 * @user_data is a pointer to the data that was given when registering
1389 * @fixture will be a pointer to the area of memory allocated by the
1390 * test framework, of the size requested. If the requested size was
1391 * zero then @fixture will be equal to @user_data.
1396 g_test_add_vtable (const char *testpath,
1398 gconstpointer test_data,
1399 GTestFixtureFunc data_setup,
1400 GTestFixtureFunc fixture_test_func,
1401 GTestFixtureFunc data_teardown)
1407 g_return_if_fail (testpath != NULL);
1408 g_return_if_fail (g_path_is_absolute (testpath));
1409 g_return_if_fail (fixture_test_func != NULL);
1411 if (g_slist_find_custom (test_paths_skipped, testpath, (GCompareFunc)g_strcmp0))
1414 suite = g_test_get_root();
1415 segments = g_strsplit (testpath, "/", -1);
1416 for (ui = 0; segments[ui] != NULL; ui++)
1418 const char *seg = segments[ui];
1419 gboolean islast = segments[ui + 1] == NULL;
1420 if (islast && !seg[0])
1421 g_error ("invalid test case path: %s", testpath);
1423 continue; /* initial or duplicate slash */
1426 GTestSuite *csuite = g_test_create_suite (seg);
1427 g_test_suite_add_suite (suite, csuite);
1432 GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1433 g_test_suite_add (suite, tc);
1436 g_strfreev (segments);
1442 * Indicates that a test failed. This function can be called
1443 * multiple times from the same test. You can use this function
1444 * if your test failed in a recoverable way.
1446 * Do not use this function if the failure of a test could cause
1447 * other tests to malfunction.
1449 * Calling this function will not stop the test from running, you
1450 * need to return from the test function yourself. So you can
1451 * produce additional diagnostic messages or even continue running
1454 * If not called from inside a test, this function does nothing.
1461 test_run_success = FALSE;
1467 * The type used for test case functions.
1474 * @testpath: /-separated test case path name for the test.
1475 * @test_func: The test function to invoke for this test.
1477 * Create a new test case, similar to g_test_create_case(). However
1478 * the test is assumed to use no fixture, and test suites are automatically
1479 * created on the fly and added to the root fixture, based on the
1480 * slash-separated portions of @testpath.
1485 g_test_add_func (const char *testpath,
1486 GTestFunc test_func)
1488 g_return_if_fail (testpath != NULL);
1489 g_return_if_fail (testpath[0] == '/');
1490 g_return_if_fail (test_func != NULL);
1491 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1496 * @user_data: the data provided when registering the test
1498 * The type used for test case functions that take an extra pointer
1505 * g_test_add_data_func:
1506 * @testpath: /-separated test case path name for the test.
1507 * @test_data: Test data argument for the test function.
1508 * @test_func: The test function to invoke for this test.
1510 * Create a new test case, similar to g_test_create_case(). However
1511 * the test is assumed to use no fixture, and test suites are automatically
1512 * created on the fly and added to the root fixture, based on the
1513 * slash-separated portions of @testpath. The @test_data argument
1514 * will be passed as first argument to @test_func.
1519 g_test_add_data_func (const char *testpath,
1520 gconstpointer test_data,
1521 GTestDataFunc test_func)
1523 g_return_if_fail (testpath != NULL);
1524 g_return_if_fail (testpath[0] == '/');
1525 g_return_if_fail (test_func != NULL);
1526 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1530 * g_test_create_suite:
1531 * @suite_name: a name for the suite
1533 * Create a new test suite with the name @suite_name.
1535 * Returns: A newly allocated #GTestSuite instance.
1540 g_test_create_suite (const char *suite_name)
1543 g_return_val_if_fail (suite_name != NULL, NULL);
1544 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1545 g_return_val_if_fail (suite_name[0] != 0, NULL);
1546 ts = g_slice_new0 (GTestSuite);
1547 ts->name = g_strdup (suite_name);
1553 * @suite: a #GTestSuite
1554 * @test_case: a #GTestCase
1556 * Adds @test_case to @suite.
1561 g_test_suite_add (GTestSuite *suite,
1562 GTestCase *test_case)
1564 g_return_if_fail (suite != NULL);
1565 g_return_if_fail (test_case != NULL);
1567 suite->cases = g_slist_prepend (suite->cases, test_case);
1571 * g_test_suite_add_suite:
1572 * @suite: a #GTestSuite
1573 * @nestedsuite: another #GTestSuite
1575 * Adds @nestedsuite to @suite.
1580 g_test_suite_add_suite (GTestSuite *suite,
1581 GTestSuite *nestedsuite)
1583 g_return_if_fail (suite != NULL);
1584 g_return_if_fail (nestedsuite != NULL);
1586 suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1590 * g_test_queue_free:
1591 * @gfree_pointer: the pointer to be stored.
1593 * Enqueue a pointer to be released with g_free() during the next
1594 * teardown phase. This is equivalent to calling g_test_queue_destroy()
1595 * with a destroy callback of g_free().
1600 g_test_queue_free (gpointer gfree_pointer)
1603 g_test_queue_destroy (g_free, gfree_pointer);
1607 * g_test_queue_destroy:
1608 * @destroy_func: Destroy callback for teardown phase.
1609 * @destroy_data: Destroy callback data.
1611 * This function enqueus a callback @destroy_func to be executed
1612 * during the next test case teardown phase. This is most useful
1613 * to auto destruct allocted test resources at the end of a test run.
1614 * Resources are released in reverse queue order, that means enqueueing
1615 * callback A before callback B will cause B() to be called before
1616 * A() during teardown.
1621 g_test_queue_destroy (GDestroyNotify destroy_func,
1622 gpointer destroy_data)
1624 DestroyEntry *dentry;
1626 g_return_if_fail (destroy_func != NULL);
1628 dentry = g_slice_new0 (DestroyEntry);
1629 dentry->destroy_func = destroy_func;
1630 dentry->destroy_data = destroy_data;
1631 dentry->next = test_destroy_queue;
1632 test_destroy_queue = dentry;
1636 test_case_run (GTestCase *tc)
1638 gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1639 gboolean success = TRUE;
1641 test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1642 if (++test_run_count <= test_skip_count)
1643 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1644 else if (test_run_list)
1646 g_print ("%s\n", test_run_name);
1647 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1651 GTimer *test_run_timer = g_timer_new();
1652 long double largs[3];
1654 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1656 test_run_success = TRUE;
1657 g_test_log_set_fatal_handler (NULL, NULL);
1658 g_timer_start (test_run_timer);
1659 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1660 test_run_seed (test_run_seedstr);
1661 if (tc->fixture_setup)
1662 tc->fixture_setup (fixture, tc->test_data);
1663 tc->fixture_test (fixture, tc->test_data);
1665 while (test_destroy_queue)
1667 DestroyEntry *dentry = test_destroy_queue;
1668 test_destroy_queue = dentry->next;
1669 dentry->destroy_func (dentry->destroy_data);
1670 g_slice_free (DestroyEntry, dentry);
1672 if (tc->fixture_teardown)
1673 tc->fixture_teardown (fixture, tc->test_data);
1674 if (tc->fixture_size)
1676 g_timer_stop (test_run_timer);
1677 success = test_run_success;
1678 test_run_success = FALSE;
1679 largs[0] = success ? 0 : 1; /* OK */
1680 largs[1] = test_run_forks;
1681 largs[2] = g_timer_elapsed (test_run_timer, NULL);
1682 g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1683 g_timer_destroy (test_run_timer);
1685 g_free (test_run_name);
1686 test_run_name = old_name;
1687 g_free (test_uri_base);
1688 test_uri_base = old_base;
1694 g_test_run_suite_internal (GTestSuite *suite,
1698 gchar *rest, *old_name = test_run_name;
1699 GSList *slist, *reversed;
1701 g_return_val_if_fail (suite != NULL, -1);
1703 while (path[0] == '/')
1706 rest = strchr (path, '/');
1707 l = rest ? MIN (l, rest - path) : l;
1708 test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1709 reversed = g_slist_reverse (g_slist_copy (suite->cases));
1710 for (slist = reversed; slist; slist = slist->next)
1712 GTestCase *tc = slist->data;
1713 guint n = l ? strlen (tc->name) : 0;
1714 if (l == n && strncmp (path, tc->name, n) == 0)
1716 if (!test_case_run (tc))
1720 g_slist_free (reversed);
1721 reversed = g_slist_reverse (g_slist_copy (suite->suites));
1722 for (slist = reversed; slist; slist = slist->next)
1724 GTestSuite *ts = slist->data;
1725 guint n = l ? strlen (ts->name) : 0;
1726 if (l == n && strncmp (path, ts->name, n) == 0)
1727 n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
1729 g_slist_free (reversed);
1730 g_free (test_run_name);
1731 test_run_name = old_name;
1738 * @suite: a #GTestSuite
1740 * Execute the tests within @suite and all nested #GTestSuites.
1741 * The test suites to be executed are filtered according to
1742 * test path arguments (-p <replaceable>testpath</replaceable>)
1743 * as parsed by g_test_init().
1744 * g_test_run_suite() or g_test_run() may only be called once
1747 * Returns: 0 on success
1752 g_test_run_suite (GTestSuite *suite)
1756 g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1757 g_return_val_if_fail (g_test_run_once == TRUE, -1);
1759 g_test_run_once = FALSE;
1762 test_paths = g_slist_prepend (test_paths, "");
1765 const char *rest, *path = test_paths->data;
1766 guint l, n = strlen (suite->name);
1767 test_paths = g_slist_delete_link (test_paths, test_paths);
1768 while (path[0] == '/')
1770 if (!n) /* root suite, run unconditionally */
1772 n_bad += g_test_run_suite_internal (suite, path);
1775 /* regular suite, match path */
1776 rest = strchr (path, '/');
1778 l = rest ? MIN (l, rest - path) : l;
1779 if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1780 n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
1787 gtest_default_log_handler (const gchar *log_domain,
1788 GLogLevelFlags log_level,
1789 const gchar *message,
1790 gpointer unused_data)
1792 const gchar *strv[16];
1793 gboolean fatal = FALSE;
1799 strv[i++] = log_domain;
1802 if (log_level & G_LOG_FLAG_FATAL)
1804 strv[i++] = "FATAL-";
1807 if (log_level & G_LOG_FLAG_RECURSION)
1808 strv[i++] = "RECURSIVE-";
1809 if (log_level & G_LOG_LEVEL_ERROR)
1810 strv[i++] = "ERROR";
1811 if (log_level & G_LOG_LEVEL_CRITICAL)
1812 strv[i++] = "CRITICAL";
1813 if (log_level & G_LOG_LEVEL_WARNING)
1814 strv[i++] = "WARNING";
1815 if (log_level & G_LOG_LEVEL_MESSAGE)
1816 strv[i++] = "MESSAGE";
1817 if (log_level & G_LOG_LEVEL_INFO)
1819 if (log_level & G_LOG_LEVEL_DEBUG)
1820 strv[i++] = "DEBUG";
1822 strv[i++] = message;
1825 msg = g_strjoinv ("", (gchar**) strv);
1826 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
1827 g_log_default_handler (log_domain, log_level, message, unused_data);
1833 g_assertion_message (const char *domain,
1837 const char *message)
1843 message = "code should not be reached";
1844 g_snprintf (lstr, 32, "%d", line);
1845 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1846 "ERROR:", file, ":", lstr, ":",
1847 func, func[0] ? ":" : "",
1848 " ", message, NULL);
1849 g_printerr ("**\n%s\n", s);
1851 /* store assertion message in global variable, so that it can be found in a
1853 if (__glib_assert_msg != NULL)
1854 /* free the old one */
1855 free (__glib_assert_msg);
1856 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
1857 strcpy (__glib_assert_msg, s);
1859 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
1865 g_assertion_message_expr (const char *domain,
1871 char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1872 g_assertion_message (domain, file, line, func, s);
1877 g_assertion_message_cmpnum (const char *domain,
1890 case 'i': s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
1891 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;
1892 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
1893 /* ideally use: floats=%.7g double=%.17g */
1895 g_assertion_message (domain, file, line, func, s);
1900 g_assertion_message_cmpstr (const char *domain,
1909 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1910 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1911 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1914 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1917 g_assertion_message (domain, file, line, func, s);
1922 g_assertion_message_error (const char *domain,
1927 const GError *error,
1928 GQuark error_domain,
1933 /* This is used by both g_assert_error() and g_assert_no_error(), so there
1934 * are three cases: expected an error but got the wrong error, expected
1935 * an error but got no error, and expected no error but got an error.
1938 gstring = g_string_new ("assertion failed ");
1940 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
1941 g_quark_to_string (error_domain), error_code);
1943 g_string_append_printf (gstring, "(%s == NULL): ", expr);
1946 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
1947 g_quark_to_string (error->domain), error->code);
1949 g_string_append_printf (gstring, "%s is NULL", expr);
1951 g_assertion_message (domain, file, line, func, gstring->str);
1952 g_string_free (gstring, TRUE);
1957 * @str1: (allow-none): a C string or %NULL
1958 * @str2: (allow-none): another C string or %NULL
1960 * Compares @str1 and @str2 like strcmp(). Handles %NULL
1961 * gracefully by sorting it before non-%NULL strings.
1962 * Comparing two %NULL pointers returns 0.
1964 * Returns: -1, 0 or 1, if @str1 is <, == or > than @str2.
1969 g_strcmp0 (const char *str1,
1973 return -(str1 != str2);
1975 return str1 != str2;
1976 return strcmp (str1, str2);
1980 static int /* 0 on success */
1981 kill_child (int pid,
1986 if (patience >= 3) /* try graceful reap */
1988 if (waitpid (pid, status, WNOHANG) > 0)
1991 if (patience >= 2) /* try SIGHUP */
1994 if (waitpid (pid, status, WNOHANG) > 0)
1996 g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1997 if (waitpid (pid, status, WNOHANG) > 0)
1999 g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
2000 if (waitpid (pid, status, WNOHANG) > 0)
2002 g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
2003 if (waitpid (pid, status, WNOHANG) > 0)
2006 if (patience >= 1) /* try SIGTERM */
2008 kill (pid, SIGTERM);
2009 if (waitpid (pid, status, WNOHANG) > 0)
2011 g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
2012 if (waitpid (pid, status, WNOHANG) > 0)
2014 g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
2015 if (waitpid (pid, status, WNOHANG) > 0)
2019 kill (pid, SIGKILL);
2021 wr = waitpid (pid, status, 0);
2022 while (wr < 0 && errno == EINTR);
2028 g_string_must_read (GString *gstring,
2031 #define STRING_BUFFER_SIZE 4096
2032 char buf[STRING_BUFFER_SIZE];
2035 bytes = read (fd, buf, sizeof (buf));
2037 return 0; /* EOF, calling this function assumes data is available */
2040 g_string_append_len (gstring, buf, bytes);
2043 else if (bytes < 0 && errno == EINTR)
2045 else /* bytes < 0 */
2047 g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2048 return 1; /* ignore error after warning */
2053 g_string_write_out (GString *gstring,
2057 if (*stringpos < gstring->len)
2061 r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
2062 while (r < 0 && errno == EINTR);
2063 *stringpos += MAX (r, 0);
2068 test_trap_clear (void)
2070 test_trap_last_status = 0;
2071 test_trap_last_pid = 0;
2072 g_free (test_trap_last_stdout);
2073 test_trap_last_stdout = NULL;
2074 g_free (test_trap_last_stderr);
2075 test_trap_last_stderr = NULL;
2086 ret = dup2 (fd1, fd2);
2087 while (ret < 0 && errno == EINTR);
2092 test_time_stamp (void)
2096 g_get_current_time (&tv);
2098 stamp = stamp * 1000000 + tv.tv_usec;
2106 * @usec_timeout: Timeout for the forked test in micro seconds.
2107 * @test_trap_flags: Flags to modify forking behaviour.
2109 * Fork the current test program to execute a test case that might
2110 * not return or that might abort. The forked test case is aborted
2111 * and considered failing if its run time exceeds @usec_timeout.
2113 * The forking behavior can be configured with the #GTestTrapFlags flags.
2115 * In the following example, the test code forks, the forked child
2116 * process produces some sample output and exits successfully.
2117 * The forking parent process then asserts successful child program
2118 * termination and validates child program outputs.
2122 * test_fork_patterns (void)
2124 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2126 * g_print ("some stdout text: somagic17\n");
2127 * g_printerr ("some stderr text: semagic43\n");
2128 * exit (0); /* successful test run */
2130 * g_test_trap_assert_passed();
2131 * g_test_trap_assert_stdout ("*somagic17*");
2132 * g_test_trap_assert_stderr ("*semagic43*");
2136 * This function is implemented only on Unix platforms.
2138 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2143 g_test_trap_fork (guint64 usec_timeout,
2144 GTestTrapFlags test_trap_flags)
2147 gboolean pass_on_forked_log = FALSE;
2148 int stdout_pipe[2] = { -1, -1 };
2149 int stderr_pipe[2] = { -1, -1 };
2150 int stdtst_pipe[2] = { -1, -1 };
2152 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
2153 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
2154 signal (SIGCHLD, SIG_DFL);
2155 test_trap_last_pid = fork ();
2156 if (test_trap_last_pid < 0)
2157 g_error ("failed to fork test program: %s", g_strerror (errno));
2158 if (test_trap_last_pid == 0) /* child */
2161 close (stdout_pipe[0]);
2162 close (stderr_pipe[0]);
2163 close (stdtst_pipe[0]);
2164 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2165 fd0 = open ("/dev/null", O_RDONLY);
2166 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2167 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
2170 if (stdout_pipe[1] >= 3)
2171 close (stdout_pipe[1]);
2172 if (stderr_pipe[1] >= 3)
2173 close (stderr_pipe[1]);
2174 test_log_fd = stdtst_pipe[1];
2179 GString *sout = g_string_new (NULL);
2180 GString *serr = g_string_new (NULL);
2182 int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
2184 close (stdout_pipe[1]);
2185 close (stderr_pipe[1]);
2186 close (stdtst_pipe[1]);
2187 sstamp = test_time_stamp();
2188 /* read data until we get EOF on all pipes */
2189 while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
2195 if (stdout_pipe[0] >= 0)
2196 FD_SET (stdout_pipe[0], &fds);
2197 if (stderr_pipe[0] >= 0)
2198 FD_SET (stderr_pipe[0], &fds);
2199 if (stdtst_pipe[0] >= 0)
2200 FD_SET (stdtst_pipe[0], &fds);
2202 tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
2203 ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
2204 if (ret < 0 && errno != EINTR)
2206 g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2209 if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
2210 g_string_must_read (sout, stdout_pipe[0]) == 0)
2212 close (stdout_pipe[0]);
2213 stdout_pipe[0] = -1;
2215 if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
2216 g_string_must_read (serr, stderr_pipe[0]) == 0)
2218 close (stderr_pipe[0]);
2219 stderr_pipe[0] = -1;
2221 if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
2223 guint8 buffer[4096];
2224 gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
2225 if (r > 0 && test_log_fd > 0)
2227 l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
2228 while (l < 0 && errno == EINTR);
2229 if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
2231 close (stdtst_pipe[0]);
2232 stdtst_pipe[0] = -1;
2235 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
2236 g_string_write_out (sout, 1, &soutpos);
2237 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
2238 g_string_write_out (serr, 2, &serrpos);
2241 guint64 nstamp = test_time_stamp();
2243 sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
2244 if (usec_timeout < nstamp - sstamp)
2246 /* timeout reached, need to abort the child now */
2247 kill_child (test_trap_last_pid, &status, 3);
2248 test_trap_last_status = 1024; /* timeout */
2249 if (0 && WIFSIGNALED (status))
2250 g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
2256 if (stdout_pipe[0] != -1)
2257 close (stdout_pipe[0]);
2258 if (stderr_pipe[0] != -1)
2259 close (stderr_pipe[0]);
2260 if (stdtst_pipe[0] != -1)
2261 close (stdtst_pipe[0]);
2266 wr = waitpid (test_trap_last_pid, &status, 0);
2267 while (wr < 0 && errno == EINTR);
2268 if (WIFEXITED (status)) /* normal exit */
2269 test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
2270 else if (WIFSIGNALED (status))
2271 test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
2272 else /* WCOREDUMP (status) */
2273 test_trap_last_status = 512; /* coredump */
2275 test_trap_last_stdout = g_string_free (sout, FALSE);
2276 test_trap_last_stderr = g_string_free (serr, FALSE);
2280 g_message ("Not implemented: g_test_trap_fork");
2287 * g_test_trap_has_passed:
2289 * Check the result of the last g_test_trap_fork() call.
2291 * Returns: %TRUE if the last forked child terminated successfully.
2296 g_test_trap_has_passed (void)
2298 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
2302 * g_test_trap_reached_timeout:
2304 * Check the result of the last g_test_trap_fork() call.
2306 * Returns: %TRUE if the last forked child got killed due to a fork timeout.
2311 g_test_trap_reached_timeout (void)
2313 return 0 != (test_trap_last_status & 1024); /* timeout flag */
2317 g_test_trap_assertions (const char *domain,
2321 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
2322 const char *pattern)
2325 gboolean must_pass = assertion_flags == 0;
2326 gboolean must_fail = assertion_flags == 1;
2327 gboolean match_result = 0 == (assertion_flags & 1);
2328 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
2329 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
2330 const char *match_error = match_result ? "failed to match" : "contains invalid match";
2331 if (test_trap_last_pid == 0)
2332 g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
2333 if (must_pass && !g_test_trap_has_passed())
2335 char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
2336 g_assertion_message (domain, file, line, func, msg);
2339 if (must_fail && g_test_trap_has_passed())
2341 char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
2342 g_assertion_message (domain, file, line, func, msg);
2345 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
2347 char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
2348 g_assertion_message (domain, file, line, func, msg);
2351 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
2353 char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
2354 g_assertion_message (domain, file, line, func, msg);
2361 gstring_overwrite_int (GString *gstring,
2365 vuint = g_htonl (vuint);
2366 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
2370 gstring_append_int (GString *gstring,
2373 vuint = g_htonl (vuint);
2374 g_string_append_len (gstring, (const gchar*) &vuint, 4);
2378 gstring_append_double (GString *gstring,
2381 union { double vdouble; guint64 vuint64; } u;
2382 u.vdouble = vdouble;
2383 u.vuint64 = GUINT64_TO_BE (u.vuint64);
2384 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
2388 g_test_log_dump (GTestLogMsg *msg,
2391 GString *gstring = g_string_sized_new (1024);
2393 gstring_append_int (gstring, 0); /* message length */
2394 gstring_append_int (gstring, msg->log_type);
2395 gstring_append_int (gstring, msg->n_strings);
2396 gstring_append_int (gstring, msg->n_nums);
2397 gstring_append_int (gstring, 0); /* reserved */
2398 for (ui = 0; ui < msg->n_strings; ui++)
2400 guint l = strlen (msg->strings[ui]);
2401 gstring_append_int (gstring, l);
2402 g_string_append_len (gstring, msg->strings[ui], l);
2404 for (ui = 0; ui < msg->n_nums; ui++)
2405 gstring_append_double (gstring, msg->nums[ui]);
2406 *len = gstring->len;
2407 gstring_overwrite_int (gstring, 0, *len); /* message length */
2408 return (guint8*) g_string_free (gstring, FALSE);
2411 static inline long double
2412 net_double (const gchar **ipointer)
2414 union { guint64 vuint64; double vdouble; } u;
2415 guint64 aligned_int64;
2416 memcpy (&aligned_int64, *ipointer, 8);
2418 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
2422 static inline guint32
2423 net_int (const gchar **ipointer)
2425 guint32 aligned_int;
2426 memcpy (&aligned_int, *ipointer, 4);
2428 return g_ntohl (aligned_int);
2432 g_test_log_extract (GTestLogBuffer *tbuffer)
2434 const gchar *p = tbuffer->data->str;
2437 if (tbuffer->data->len < 4 * 5)
2439 mlength = net_int (&p);
2440 if (tbuffer->data->len < mlength)
2442 msg.log_type = net_int (&p);
2443 msg.n_strings = net_int (&p);
2444 msg.n_nums = net_int (&p);
2445 if (net_int (&p) == 0)
2448 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
2449 msg.nums = g_new0 (long double, msg.n_nums);
2450 for (ui = 0; ui < msg.n_strings; ui++)
2452 guint sl = net_int (&p);
2453 msg.strings[ui] = g_strndup (p, sl);
2456 for (ui = 0; ui < msg.n_nums; ui++)
2457 msg.nums[ui] = net_double (&p);
2458 if (p <= tbuffer->data->str + mlength)
2460 g_string_erase (tbuffer->data, 0, mlength);
2461 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
2466 g_strfreev (msg.strings);
2467 g_error ("corrupt log stream from test program");
2472 * g_test_log_buffer_new:
2474 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2477 g_test_log_buffer_new (void)
2479 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
2480 tb->data = g_string_sized_new (1024);
2485 * g_test_log_buffer_free:
2487 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2490 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
2492 g_return_if_fail (tbuffer != NULL);
2493 while (tbuffer->msgs)
2494 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
2495 g_string_free (tbuffer->data, TRUE);
2500 * g_test_log_buffer_push:
2502 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2505 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
2507 const guint8 *bytes)
2509 g_return_if_fail (tbuffer != NULL);
2512 gboolean more_messages;
2513 g_return_if_fail (bytes != NULL);
2514 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
2516 more_messages = g_test_log_extract (tbuffer);
2517 while (more_messages);
2522 * g_test_log_buffer_pop:
2524 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
2527 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
2529 GTestLogMsg *msg = NULL;
2530 g_return_val_if_fail (tbuffer != NULL, NULL);
2533 GSList *slist = g_slist_last (tbuffer->msgs);
2535 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
2541 * g_test_log_msg_free:
2543 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2546 g_test_log_msg_free (GTestLogMsg *tmsg)
2548 g_return_if_fail (tmsg != NULL);
2549 g_strfreev (tmsg->strings);
2550 g_free (tmsg->nums);
2554 /* --- macros docs START --- */
2557 * @testpath: The test path for a new test case.
2558 * @Fixture: The type of a fixture data structure.
2559 * @tdata: Data argument for the test functions.
2560 * @fsetup: The function to set up the fixture data.
2561 * @ftest: The actual test function.
2562 * @fteardown: The function to tear down the fixture data.
2564 * Hook up a new test case at @testpath, similar to g_test_add_func().
2565 * A fixture data structure with setup and teardown function may be provided
2566 * though, similar to g_test_create_case().
2567 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2568 * fteardown() callbacks can expect a @Fixture pointer as first argument in
2569 * a type safe manner.
2573 /* --- macros docs END --- */