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>
31 #include <glib/gstdio.h>
45 #ifdef HAVE_SYS_SELECT_H
46 #include <sys/select.h>
47 #endif /* HAVE_SYS_SELECT_H */
52 #include "gstrfuncs.h"
56 #include "glib-private.h"
62 * @short_description: a test framework
63 * @see_also: <link linkend="gtester">gtester</link>,
64 * <link linkend="gtester-report">gtester-report</link>
66 * GLib provides a framework for writing and maintaining unit tests
67 * in parallel to the code they are testing. The API is designed according
68 * to established concepts found in the other test frameworks (JUnit, NUnit,
69 * RUnit), which in turn is based on smalltalk unit testing concepts.
73 * <term>Test case</term>
74 * <listitem>Tests (test methods) are grouped together with their
75 * fixture into test cases.</listitem>
78 * <term>Fixture</term>
79 * <listitem>A test fixture consists of fixture data and setup and
80 * teardown methods to establish the environment for the test
81 * functions. We use fresh fixtures, i.e. fixtures are newly set
82 * up and torn down around each test invocation to avoid dependencies
83 * between tests.</listitem>
86 * <term>Test suite</term>
87 * <listitem>Test cases can be grouped into test suites, to allow
88 * subsets of the available tests to be run. Test suites can be
89 * grouped into other test suites as well.</listitem>
92 * The API is designed to handle creation and registration of test suites
93 * and test cases implicitly. A simple call like
95 * g_test_add_func ("/misc/assertions", test_assertions);
97 * creates a test suite called "misc" with a single test case named
98 * "assertions", which consists of running the test_assertions function.
100 * In addition to the traditional g_assert(), the test framework provides
101 * an extended set of assertions for string and numerical comparisons:
102 * g_assert_cmpfloat(), g_assert_cmpint(), g_assert_cmpuint(),
103 * g_assert_cmphex(), g_assert_cmpstr(). The advantage of these variants
104 * over plain g_assert() is that the assertion messages can be more
105 * elaborate, and include the values of the compared entities.
107 * GLib ships with two utilities called gtester and gtester-report to
108 * facilitate running tests and producing nicely formatted test reports.
112 * g_test_initialized:
114 * Returns %TRUE if g_test_init() has been called.
116 * Returns: %TRUE if g_test_init() has been called.
124 * Returns %TRUE if tests are run in quick mode.
125 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
126 * there is no "medium speed".
128 * Returns: %TRUE if in quick mode
134 * Returns %TRUE if tests are run in slow mode.
135 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
136 * there is no "medium speed".
138 * Returns: the opposite of g_test_quick()
144 * Returns %TRUE if tests are run in thorough mode, equivalent to
147 * Returns: the same thing as g_test_slow()
153 * Returns %TRUE if tests are run in performance mode.
155 * Returns: %TRUE if in performance mode
161 * Returns %TRUE if tests may provoke assertions and other formally-undefined
162 * behaviour, to verify that appropriate warnings are given. It might, in some
163 * cases, be useful to turn this off if running tests under valgrind.
165 * Returns: %TRUE if tests may provoke programming errors
171 * Returns %TRUE if tests are run in verbose mode.
172 * The default is neither g_test_verbose() nor g_test_quiet().
174 * Returns: %TRUE if in verbose mode
180 * Returns %TRUE if tests are run in quiet mode.
181 * The default is neither g_test_verbose() nor g_test_quiet().
183 * Returns: %TRUE if in quiet mode
187 * g_test_queue_unref:
188 * @gobject: the object to unref
190 * Enqueue an object to be released with g_object_unref() during
191 * the next teardown phase. This is equivalent to calling
192 * g_test_queue_destroy() with a destroy callback of g_object_unref().
199 * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
200 * <filename>/dev/null</filename> so it cannot be observed on the
201 * console during test runs. The actual output is still captured
202 * though to allow later tests with g_test_trap_assert_stdout().
203 * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
204 * <filename>/dev/null</filename> so it cannot be observed on the
205 * console during test runs. The actual output is still captured
206 * though to allow later tests with g_test_trap_assert_stderr().
207 * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
208 * child process is shared with stdin of its parent process.
209 * It is redirected to <filename>/dev/null</filename> otherwise.
211 * Test traps are guards around forked tests.
212 * These flags determine what traps to set.
214 * Deprecated: #GTestTrapFlags is used only with g_test_trap_fork(),
215 * which is deprecated. g_test_trap_subprocess() uses
216 * #GTestTrapSubprocessFlags.
220 * GTestSubprocessFlags:
221 * @G_TEST_SUBPROCESS_INHERIT_STDIN: If this flag is given, the child
222 * process will inherit the parent's stdin. Otherwise, the child's
223 * stdin is redirected to <filename>/dev/null</filename>.
224 * @G_TEST_SUBPROCESS_INHERIT_STDOUT: If this flag is given, the child
225 * process will inherit the parent's stdout. Otherwise, the child's
226 * stdout will not be visible, but it will be captured to allow
227 * later tests with g_test_trap_assert_stdout().
228 * @G_TEST_SUBPROCESS_INHERIT_STDERR: If this flag is given, the child
229 * process will inherit the parent's stderr. Otherwise, the child's
230 * stderr will not be visible, but it will be captured to allow
231 * later tests with g_test_trap_assert_stderr().
233 * Flags to pass to g_test_trap_subprocess() to control input and output.
235 * Note that in contrast with g_test_trap_fork(), the default is to
236 * not show stdout and stderr.
240 * g_test_trap_assert_passed:
242 * Assert that the last test subprocess passed.
243 * See g_test_trap_subprocess().
249 * g_test_trap_assert_failed:
251 * Assert that the last test subprocess failed.
252 * See g_test_trap_subprocess().
254 * This is sometimes used to test situations that are formally considered to
255 * be undefined behaviour, like inputs that fail a g_return_if_fail()
256 * check. In these situations you should skip the entire test, including the
257 * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
258 * to indicate that undefined behaviour may be tested.
264 * g_test_trap_assert_stdout:
265 * @soutpattern: a glob-style
266 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
268 * Assert that the stdout output of the last test subprocess matches
269 * @soutpattern. See g_test_trap_subprocess().
275 * g_test_trap_assert_stdout_unmatched:
276 * @soutpattern: a glob-style
277 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
279 * Assert that the stdout output of the last test subprocess
280 * does not match @soutpattern. See g_test_trap_subprocess().
286 * g_test_trap_assert_stderr:
287 * @serrpattern: a glob-style
288 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
290 * Assert that the stderr output of the last test subprocess
291 * matches @serrpattern. See g_test_trap_subprocess().
293 * This is sometimes used to test situations that are formally
294 * considered to be undefined behaviour, like code that hits a
295 * g_assert() or g_error(). In these situations you should skip the
296 * entire test, including the call to g_test_trap_subprocess(), unless
297 * g_test_undefined() returns %TRUE to indicate that undefined
298 * behaviour may be tested.
304 * g_test_trap_assert_stderr_unmatched:
305 * @serrpattern: a glob-style
306 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
308 * Assert that the stderr output of the last test subprocess
309 * does not match @serrpattern. See g_test_trap_subprocess().
317 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
318 * for details on test case random numbers.
325 * @expr: the expression to check
327 * Debugging macro to terminate the application if the assertion
328 * fails. If the assertion fails (i.e. the expression is not true),
329 * an error message is logged and the application is terminated.
331 * The macro can be turned off in final releases of code by defining
332 * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
336 * g_assert_not_reached:
338 * Debugging macro to terminate the application if it is ever
339 * reached. If it is reached, an error message is logged and the
340 * application is terminated.
342 * The macro can be turned off in final releases of code by defining
343 * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
348 * @s1: a string (may be %NULL)
349 * @cmp: The comparison operator to use.
350 * One of ==, !=, <, >, <=, >=.
351 * @s2: another string (may be %NULL)
353 * Debugging macro to terminate the application with a warning
354 * message if a string comparison fails. The strings are compared
357 * The effect of <literal>g_assert_cmpstr (s1, op, s2)</literal> is
358 * the same as <literal>g_assert (g_strcmp0 (s1, s2) op 0)</literal>.
359 * The advantage of this macro is that it can produce a message that
360 * includes the actual values of @s1 and @s2.
363 * g_assert_cmpstr (mystring, ==, "fubar");
372 * @cmp: The comparison operator to use.
373 * One of ==, !=, <, >, <=, >=.
374 * @n2: another integer
376 * Debugging macro to terminate the application with a warning
377 * message if an integer comparison fails.
379 * The effect of <literal>g_assert_cmpint (n1, op, n2)</literal> is
380 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
381 * of this macro is that it can produce a message that includes the
382 * actual values of @n1 and @n2.
389 * @n1: an unsigned integer
390 * @cmp: The comparison operator to use.
391 * One of ==, !=, <, >, <=, >=.
392 * @n2: another unsigned integer
394 * Debugging macro to terminate the application with a warning
395 * message if an unsigned integer comparison fails.
397 * The effect of <literal>g_assert_cmpuint (n1, op, n2)</literal> is
398 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
399 * of this macro is that it can produce a message that includes the
400 * actual values of @n1 and @n2.
407 * @n1: an unsigned integer
408 * @cmp: The comparison operator to use.
409 * One of ==, !=, <, >, <=, >=.
410 * @n2: another unsigned integer
412 * Debugging macro to terminate the application with a warning
413 * message if an unsigned integer comparison fails.
415 * This is a variant of g_assert_cmpuint() that displays the numbers
416 * in hexadecimal notation in the message.
423 * @n1: an floating point number
424 * @cmp: The comparison operator to use.
425 * One of ==, !=, <, >, <=, >=.
426 * @n2: another floating point number
428 * Debugging macro to terminate the application with a warning
429 * message if a floating point number comparison fails.
431 * The effect of <literal>g_assert_cmpfloat (n1, op, n2)</literal> is
432 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
433 * of this macro is that it can produce a message that includes the
434 * actual values of @n1 and @n2.
441 * @err: a #GError, possibly %NULL
443 * Debugging macro to terminate the application with a warning
444 * message if a method has returned a #GError.
446 * The effect of <literal>g_assert_no_error (err)</literal> is
447 * the same as <literal>g_assert (err == NULL)</literal>. The advantage
448 * of this macro is that it can produce a message that includes
449 * the error message and code.
456 * @err: a #GError, possibly %NULL
457 * @dom: the expected error domain (a #GQuark)
458 * @c: the expected error code
460 * Debugging macro to terminate the application with a warning
461 * message if a method has not returned the correct #GError.
463 * The effect of <literal>g_assert_error (err, dom, c)</literal> is
464 * the same as <literal>g_assert (err != NULL && err->domain
465 * == dom && err->code == c)</literal>. The advantage of this
466 * macro is that it can produce a message that includes the incorrect
467 * error message and code.
469 * This can only be used to test for a specific error. If you want to
470 * test that @err is set, but don't care what it's set to, just use
471 * <literal>g_assert (err != NULL)</literal>
479 * An opaque structure representing a test case.
485 * An opaque structure representing a test suite.
489 /* Global variable for storing assertion messages; this is the counterpart to
490 * glibc's (private) __abort_msg variable, and allows developers and crash
491 * analysis systems like Apport and ABRT to fish out assertion messages from
492 * core dumps, instead of having to catch them on screen output.
494 char *__glib_assert_msg = NULL;
496 /* --- constants --- */
497 #define G_TEST_STATUS_TIMED_OUT 1024
499 /* --- structures --- */
504 void (*fixture_setup) (void*, gconstpointer);
505 void (*fixture_test) (void*, gconstpointer);
506 void (*fixture_teardown) (void*, gconstpointer);
515 typedef struct DestroyEntry DestroyEntry;
519 GDestroyNotify destroy_func;
520 gpointer destroy_data;
523 /* --- prototypes --- */
524 static void test_run_seed (const gchar *rseed);
525 static void test_trap_clear (void);
526 static guint8* g_test_log_dump (GTestLogMsg *msg,
528 static void gtest_default_log_handler (const gchar *log_domain,
529 GLogLevelFlags log_level,
530 const gchar *message,
531 gpointer unused_data);
534 /* --- variables --- */
535 static int test_log_fd = -1;
536 static gboolean test_mode_fatal = TRUE;
537 static gboolean g_test_run_once = TRUE;
538 static gboolean test_run_list = FALSE;
539 static gchar *test_run_seedstr = NULL;
540 static GRand *test_run_rand = NULL;
541 static gchar *test_run_name = "";
542 static guint test_run_forks = 0;
543 static guint test_run_count = 0;
544 static guint test_run_success = FALSE;
545 static guint test_skip_count = 0;
546 static GTimer *test_user_timer = NULL;
547 static double test_user_stamp = 0;
548 static GSList *test_paths = NULL;
549 static GSList *test_paths_skipped = NULL;
550 static GTestSuite *test_suite_root = NULL;
551 static int test_trap_last_status = 0;
552 static GPid test_trap_last_pid = 0;
553 static char *test_trap_last_subprocess = NULL;
554 static char *test_trap_last_stdout = NULL;
555 static char *test_trap_last_stderr = NULL;
556 static char *test_uri_base = NULL;
557 static gboolean test_debug_log = FALSE;
558 static DestroyEntry *test_destroy_queue = NULL;
559 static char *test_argv0 = NULL;
560 static char *test_initial_cwd = NULL;
561 static gboolean test_in_subprocess = FALSE;
562 static GTestConfig mutable_test_config_vars = {
563 FALSE, /* test_initialized */
564 TRUE, /* test_quick */
565 FALSE, /* test_perf */
566 FALSE, /* test_verbose */
567 FALSE, /* test_quiet */
568 TRUE, /* test_undefined */
570 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
572 /* --- functions --- */
574 g_test_log_type_name (GTestLogType log_type)
578 case G_TEST_LOG_NONE: return "none";
579 case G_TEST_LOG_ERROR: return "error";
580 case G_TEST_LOG_START_BINARY: return "binary";
581 case G_TEST_LOG_LIST_CASE: return "list";
582 case G_TEST_LOG_SKIP_CASE: return "skip";
583 case G_TEST_LOG_START_CASE: return "start";
584 case G_TEST_LOG_STOP_CASE: return "stop";
585 case G_TEST_LOG_MIN_RESULT: return "minperf";
586 case G_TEST_LOG_MAX_RESULT: return "maxperf";
587 case G_TEST_LOG_MESSAGE: return "message";
593 g_test_log_send (guint n_bytes,
594 const guint8 *buffer)
596 if (test_log_fd >= 0)
600 r = write (test_log_fd, buffer, n_bytes);
601 while (r < 0 && errno == EINTR);
605 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
608 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
609 msg = g_test_log_buffer_pop (lbuffer);
610 g_warn_if_fail (msg != NULL);
611 g_warn_if_fail (lbuffer->data->len == 0);
612 g_test_log_buffer_free (lbuffer);
614 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
615 for (ui = 0; ui < msg->n_strings; ui++)
616 g_printerr (":{%s}", msg->strings[ui]);
620 for (ui = 0; ui < msg->n_nums; ui++)
622 if ((long double) (long) msg->nums[ui] == msg->nums[ui])
623 g_printerr ("%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
625 g_printerr ("%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
629 g_printerr (":LOG*}\n");
630 g_test_log_msg_free (msg);
635 g_test_log (GTestLogType lbit,
636 const gchar *string1,
637 const gchar *string2,
641 gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
643 gchar *astrings[3] = { NULL, NULL, NULL };
649 case G_TEST_LOG_START_BINARY:
650 if (g_test_verbose())
651 g_print ("GTest: random seed: %s\n", string2);
653 case G_TEST_LOG_STOP_CASE:
654 if (g_test_verbose())
655 g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
656 else if (!g_test_quiet())
657 g_print ("%s\n", fail ? "FAIL" : "OK");
658 if (fail && test_mode_fatal)
661 case G_TEST_LOG_MIN_RESULT:
662 if (g_test_verbose())
663 g_print ("(MINPERF:%s)\n", string1);
665 case G_TEST_LOG_MAX_RESULT:
666 if (g_test_verbose())
667 g_print ("(MAXPERF:%s)\n", string1);
669 case G_TEST_LOG_MESSAGE:
670 case G_TEST_LOG_ERROR:
671 if (g_test_verbose())
672 g_print ("(MSG: %s)\n", string1);
678 msg.n_strings = (string1 != NULL) + (string1 && string2);
679 msg.strings = astrings;
680 astrings[0] = (gchar*) string1;
681 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
684 dbuffer = g_test_log_dump (&msg, &dbufferlen);
685 g_test_log_send (dbufferlen, dbuffer);
690 case G_TEST_LOG_START_CASE:
691 if (g_test_verbose())
692 g_print ("GTest: run: %s\n", string1);
693 else if (!g_test_quiet())
694 g_print ("%s: ", string1);
700 /* We intentionally parse the command line without GOptionContext
701 * because otherwise you would never be able to test it.
704 parse_args (gint *argc_p,
707 guint argc = *argc_p;
708 gchar **argv = *argv_p;
711 test_argv0 = argv[0];
712 test_initial_cwd = g_get_current_dir ();
714 /* parse known args */
715 for (i = 1; i < argc; i++)
717 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
719 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
720 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
721 g_log_set_always_fatal (fatal_mask);
724 else if (strcmp (argv[i], "--keep-going") == 0 ||
725 strcmp (argv[i], "-k") == 0)
727 test_mode_fatal = FALSE;
730 else if (strcmp (argv[i], "--debug-log") == 0)
732 test_debug_log = TRUE;
735 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
737 gchar *equal = argv[i] + 12;
739 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
740 else if (i + 1 < argc)
743 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
747 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
749 gchar *equal = argv[i] + 16;
751 test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
752 else if (i + 1 < argc)
755 test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
759 else if (strcmp ("--GTestSubprocess", argv[i]) == 0)
761 test_in_subprocess = TRUE;
764 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
766 gchar *equal = argv[i] + 2;
768 test_paths = g_slist_prepend (test_paths, equal + 1);
769 else if (i + 1 < argc)
772 test_paths = g_slist_prepend (test_paths, argv[i]);
776 else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
778 gchar *equal = argv[i] + 2;
780 test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
781 else if (i + 1 < argc)
784 test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
788 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
790 gchar *equal = argv[i] + 2;
791 const gchar *mode = "";
794 else if (i + 1 < argc)
799 if (strcmp (mode, "perf") == 0)
800 mutable_test_config_vars.test_perf = TRUE;
801 else if (strcmp (mode, "slow") == 0)
802 mutable_test_config_vars.test_quick = FALSE;
803 else if (strcmp (mode, "thorough") == 0)
804 mutable_test_config_vars.test_quick = FALSE;
805 else if (strcmp (mode, "quick") == 0)
807 mutable_test_config_vars.test_quick = TRUE;
808 mutable_test_config_vars.test_perf = FALSE;
810 else if (strcmp (mode, "undefined") == 0)
811 mutable_test_config_vars.test_undefined = TRUE;
812 else if (strcmp (mode, "no-undefined") == 0)
813 mutable_test_config_vars.test_undefined = FALSE;
815 g_error ("unknown test mode: -m %s", mode);
818 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
820 mutable_test_config_vars.test_quiet = TRUE;
821 mutable_test_config_vars.test_verbose = FALSE;
824 else if (strcmp ("--verbose", argv[i]) == 0)
826 mutable_test_config_vars.test_quiet = FALSE;
827 mutable_test_config_vars.test_verbose = TRUE;
830 else if (strcmp ("-l", argv[i]) == 0)
832 test_run_list = TRUE;
835 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
837 gchar *equal = argv[i] + 6;
839 test_run_seedstr = equal + 1;
840 else if (i + 1 < argc)
843 test_run_seedstr = argv[i];
847 else if (strcmp ("-?", argv[i]) == 0 ||
848 strcmp ("-h", argv[i]) == 0 ||
849 strcmp ("--help", argv[i]) == 0)
852 " %s [OPTION...]\n\n"
854 " -h, --help Show help options\n\n"
856 " --g-fatal-warnings Make all warnings fatal\n"
857 " -l List test cases available in a test executable\n"
858 " -m {perf|slow|thorough|quick} Execute tests according to mode\n"
859 " -m {undefined|no-undefined} Execute tests according to mode\n"
860 " -p TESTPATH Only start test cases matching TESTPATH\n"
861 " -s TESTPATH Skip all tests matching TESTPATH\n"
862 " -seed=SEEDSTRING Start tests with random seed SEEDSTRING\n"
863 " --debug-log debug test logging output\n"
864 " -q, --quiet Run tests quietly\n"
865 " --verbose Run tests verbosely\n",
872 for (i = 1; i < argc; i++)
884 * @argc: Address of the @argc parameter of the main() function.
885 * Changed if any arguments were handled.
886 * @argv: Address of the @argv parameter of main().
887 * Any parameters understood by g_test_init() stripped before return.
888 * @...: Reserved for future extension. Currently, you must pass %NULL.
890 * Initialize the GLib testing framework, e.g. by seeding the
891 * test random number generator, the name for g_get_prgname()
892 * and parsing test related command line args.
893 * So far, the following arguments are understood:
896 * <term><option>-l</option></term>
898 * List test cases available in a test executable.
902 * <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
904 * Provide a random seed to reproduce test runs using random numbers.
908 * <term><option>--verbose</option></term>
909 * <listitem><para>Run tests verbosely.</para></listitem>
912 * <term><option>-q</option>, <option>--quiet</option></term>
913 * <listitem><para>Run tests quietly.</para></listitem>
916 * <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
918 * Execute all tests matching <replaceable>TESTPATH</replaceable>.
919 * This can also be used to force a test to run that would otherwise
920 * be skipped (ie, a test whose name contains "/subprocess").
924 * <term><option>-m {perf|slow|thorough|quick|undefined|no-undefined}</option></term>
926 * Execute tests according to these test modes:
931 * Performance tests, may take long and report results.
935 * <term>slow, thorough</term>
937 * Slow and thorough tests, may take quite long and
944 * Quick tests, should run really quickly and give good coverage.
948 * <term>undefined</term>
950 * Tests for undefined behaviour, may provoke programming errors
951 * under g_test_trap_subprocess() or g_test_expect_messages() to check
952 * that appropriate assertions or warnings are given
956 * <term>no-undefined</term>
958 * Avoid tests for undefined behaviour
965 * <term><option>--debug-log</option></term>
966 * <listitem><para>Debug test logging output.</para></listitem>
973 g_test_init (int *argc,
977 static char seedstr[4 + 4 * 8 + 1];
980 /* make warnings and criticals fatal for all test programs */
981 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
982 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
983 g_log_set_always_fatal (fatal_mask);
984 /* check caller args */
985 g_return_if_fail (argc != NULL);
986 g_return_if_fail (argv != NULL);
987 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
988 mutable_test_config_vars.test_initialized = TRUE;
990 va_start (args, argv);
991 vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
993 g_return_if_fail (vararg1 == NULL);
995 /* setup random seed string */
996 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
997 test_run_seedstr = seedstr;
999 /* parse args, sets up mode, changes seed, etc. */
1000 parse_args (argc, argv);
1001 if (!g_get_prgname())
1002 g_set_prgname ((*argv)[0]);
1004 /* verify GRand reliability, needed for reliable seeds */
1007 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
1008 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
1009 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
1010 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
1011 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
1015 /* check rand seed */
1016 test_run_seed (test_run_seedstr);
1018 /* report program start */
1019 g_log_set_default_handler (gtest_default_log_handler, NULL);
1020 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
1024 test_run_seed (const gchar *rseed)
1026 guint seed_failed = 0;
1028 g_rand_free (test_run_rand);
1029 test_run_rand = NULL;
1030 while (strchr (" \t\v\r\n\f", *rseed))
1032 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
1034 const char *s = rseed + 4;
1035 if (strlen (s) >= 32) /* require 4 * 8 chars */
1037 guint32 seedarray[4];
1038 gchar *p, hexbuf[9] = { 0, };
1039 memcpy (hexbuf, s + 0, 8);
1040 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
1041 seed_failed += p != NULL && *p != 0;
1042 memcpy (hexbuf, s + 8, 8);
1043 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
1044 seed_failed += p != NULL && *p != 0;
1045 memcpy (hexbuf, s + 16, 8);
1046 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
1047 seed_failed += p != NULL && *p != 0;
1048 memcpy (hexbuf, s + 24, 8);
1049 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
1050 seed_failed += p != NULL && *p != 0;
1053 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
1058 g_error ("Unknown or invalid random seed: %s", rseed);
1064 * Get a reproducible random integer number.
1066 * The random numbers generated by the g_test_rand_*() family of functions
1067 * change with every new test program start, unless the --seed option is
1068 * given when starting test programs.
1070 * For individual test cases however, the random number generator is
1071 * reseeded, to avoid dependencies between tests and to make --seed
1072 * effective for all test cases.
1074 * Returns: a random number from the seeded random number generator.
1079 g_test_rand_int (void)
1081 return g_rand_int (test_run_rand);
1085 * g_test_rand_int_range:
1086 * @begin: the minimum value returned by this function
1087 * @end: the smallest value not to be returned by this function
1089 * Get a reproducible random integer number out of a specified range,
1090 * see g_test_rand_int() for details on test case random numbers.
1092 * Returns: a number with @begin <= number < @end.
1097 g_test_rand_int_range (gint32 begin,
1100 return g_rand_int_range (test_run_rand, begin, end);
1104 * g_test_rand_double:
1106 * Get a reproducible random floating point number,
1107 * see g_test_rand_int() for details on test case random numbers.
1109 * Returns: a random number from the seeded random number generator.
1114 g_test_rand_double (void)
1116 return g_rand_double (test_run_rand);
1120 * g_test_rand_double_range:
1121 * @range_start: the minimum value returned by this function
1122 * @range_end: the minimum value not returned by this function
1124 * Get a reproducible random floating pointer number out of a specified range,
1125 * see g_test_rand_int() for details on test case random numbers.
1127 * Returns: a number with @range_start <= number < @range_end.
1132 g_test_rand_double_range (double range_start,
1135 return g_rand_double_range (test_run_rand, range_start, range_end);
1139 * g_test_timer_start:
1141 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1142 * to be done. Call this function again to restart the timer.
1147 g_test_timer_start (void)
1149 if (!test_user_timer)
1150 test_user_timer = g_timer_new();
1151 test_user_stamp = 0;
1152 g_timer_start (test_user_timer);
1156 * g_test_timer_elapsed:
1158 * Get the time since the last start of the timer with g_test_timer_start().
1160 * Returns: the time since the last start of the timer, as a double
1165 g_test_timer_elapsed (void)
1167 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1168 return test_user_stamp;
1172 * g_test_timer_last:
1174 * Report the last result of g_test_timer_elapsed().
1176 * Returns: the last result of g_test_timer_elapsed(), as a double
1181 g_test_timer_last (void)
1183 return test_user_stamp;
1187 * g_test_minimized_result:
1188 * @minimized_quantity: the reported value
1189 * @format: the format string of the report message
1190 * @...: arguments to pass to the printf() function
1192 * Report the result of a performance or measurement test.
1193 * The test should generally strive to minimize the reported
1194 * quantities (smaller values are better than larger ones),
1195 * this and @minimized_quantity can determine sorting
1196 * order for test result reports.
1201 g_test_minimized_result (double minimized_quantity,
1205 long double largs = minimized_quantity;
1209 va_start (args, format);
1210 buffer = g_strdup_vprintf (format, args);
1213 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1218 * g_test_maximized_result:
1219 * @maximized_quantity: the reported value
1220 * @format: the format string of the report message
1221 * @...: arguments to pass to the printf() function
1223 * Report the result of a performance or measurement test.
1224 * The test should generally strive to maximize the reported
1225 * quantities (larger values are better than smaller ones),
1226 * this and @maximized_quantity can determine sorting
1227 * order for test result reports.
1232 g_test_maximized_result (double maximized_quantity,
1236 long double largs = maximized_quantity;
1240 va_start (args, format);
1241 buffer = g_strdup_vprintf (format, args);
1244 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1250 * @format: the format string
1251 * @...: printf-like arguments to @format
1253 * Add a message to the test report.
1258 g_test_message (const char *format,
1264 va_start (args, format);
1265 buffer = g_strdup_vprintf (format, args);
1268 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1274 * @uri_pattern: the base pattern for bug URIs
1276 * Specify the base URI for bug reports.
1278 * The base URI is used to construct bug report messages for
1279 * g_test_message() when g_test_bug() is called.
1280 * Calling this function outside of a test case sets the
1281 * default base URI for all test cases. Calling it from within
1282 * a test case changes the base URI for the scope of the test
1284 * Bug URIs are constructed by appending a bug specific URI
1285 * portion to @uri_pattern, or by replacing the special string
1286 * '\%s' within @uri_pattern if that is present.
1291 g_test_bug_base (const char *uri_pattern)
1293 g_free (test_uri_base);
1294 test_uri_base = g_strdup (uri_pattern);
1299 * @bug_uri_snippet: Bug specific bug tracker URI portion.
1301 * This function adds a message to test reports that
1302 * associates a bug URI with a test case.
1303 * Bug URIs are constructed from a base URI set with g_test_bug_base()
1304 * and @bug_uri_snippet.
1309 g_test_bug (const char *bug_uri_snippet)
1313 g_return_if_fail (test_uri_base != NULL);
1314 g_return_if_fail (bug_uri_snippet != NULL);
1316 c = strstr (test_uri_base, "%s");
1319 char *b = g_strndup (test_uri_base, c - test_uri_base);
1320 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1322 g_test_message ("Bug Reference: %s", s);
1326 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1332 * Get the toplevel test suite for the test path API.
1334 * Returns: the toplevel #GTestSuite
1339 g_test_get_root (void)
1341 if (!test_suite_root)
1343 test_suite_root = g_test_create_suite ("root");
1344 g_free (test_suite_root->name);
1345 test_suite_root->name = g_strdup ("");
1348 return test_suite_root;
1354 * Runs all tests under the toplevel suite which can be retrieved
1355 * with g_test_get_root(). Similar to g_test_run_suite(), the test
1356 * cases to be run are filtered according to
1357 * test path arguments (-p <replaceable>testpath</replaceable>) as
1358 * parsed by g_test_init().
1359 * g_test_run_suite() or g_test_run() may only be called once
1362 * Returns: 0 on success
1369 return g_test_run_suite (g_test_get_root());
1373 * g_test_create_case:
1374 * @test_name: the name for the test case
1375 * @data_size: the size of the fixture data structure
1376 * @test_data: test data argument for the test functions
1377 * @data_setup: the function to set up the fixture data
1378 * @data_test: the actual test function
1379 * @data_teardown: the function to teardown the fixture data
1381 * Create a new #GTestCase, named @test_name, this API is fairly
1382 * low level, calling g_test_add() or g_test_add_func() is preferable.
1383 * When this test is executed, a fixture structure of size @data_size
1384 * will be allocated and filled with 0s. Then @data_setup is called
1385 * to initialize the fixture. After fixture setup, the actual test
1386 * function @data_test is called. Once the test run completed, the
1387 * fixture structure is torn down by calling @data_teardown and
1388 * after that the memory is released.
1390 * Splitting up a test run into fixture setup, test function and
1391 * fixture teardown is most usful if the same fixture is used for
1392 * multiple tests. In this cases, g_test_create_case() will be
1393 * called with the same fixture, but varying @test_name and
1394 * @data_test arguments.
1396 * Returns: a newly allocated #GTestCase.
1401 g_test_create_case (const char *test_name,
1403 gconstpointer test_data,
1404 GTestFixtureFunc data_setup,
1405 GTestFixtureFunc data_test,
1406 GTestFixtureFunc data_teardown)
1410 g_return_val_if_fail (test_name != NULL, NULL);
1411 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1412 g_return_val_if_fail (test_name[0] != 0, NULL);
1413 g_return_val_if_fail (data_test != NULL, NULL);
1415 tc = g_slice_new0 (GTestCase);
1416 tc->name = g_strdup (test_name);
1417 tc->test_data = (gpointer) test_data;
1418 tc->fixture_size = data_size;
1419 tc->fixture_setup = (void*) data_setup;
1420 tc->fixture_test = (void*) data_test;
1421 tc->fixture_teardown = (void*) data_teardown;
1427 find_suite (gconstpointer l, gconstpointer s)
1429 const GTestSuite *suite = l;
1430 const gchar *str = s;
1432 return strcmp (suite->name, str);
1437 * @fixture: the test fixture
1438 * @user_data: the data provided when registering the test
1440 * The type used for functions that operate on test fixtures. This is
1441 * used for the fixture setup and teardown functions as well as for the
1442 * testcases themselves.
1444 * @user_data is a pointer to the data that was given when registering
1447 * @fixture will be a pointer to the area of memory allocated by the
1448 * test framework, of the size requested. If the requested size was
1449 * zero then @fixture will be equal to @user_data.
1454 g_test_add_vtable (const char *testpath,
1456 gconstpointer test_data,
1457 GTestFixtureFunc data_setup,
1458 GTestFixtureFunc fixture_test_func,
1459 GTestFixtureFunc data_teardown)
1465 g_return_if_fail (testpath != NULL);
1466 g_return_if_fail (g_path_is_absolute (testpath));
1467 g_return_if_fail (fixture_test_func != NULL);
1469 if (g_slist_find_custom (test_paths_skipped, testpath, (GCompareFunc)g_strcmp0))
1472 suite = g_test_get_root();
1473 segments = g_strsplit (testpath, "/", -1);
1474 for (ui = 0; segments[ui] != NULL; ui++)
1476 const char *seg = segments[ui];
1477 gboolean islast = segments[ui + 1] == NULL;
1478 if (islast && !seg[0])
1479 g_error ("invalid test case path: %s", testpath);
1481 continue; /* initial or duplicate slash */
1486 l = g_slist_find_custom (suite->suites, seg, find_suite);
1493 csuite = g_test_create_suite (seg);
1494 g_test_suite_add_suite (suite, csuite);
1500 GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1501 g_test_suite_add (suite, tc);
1504 g_strfreev (segments);
1510 * Indicates that a test failed. This function can be called
1511 * multiple times from the same test. You can use this function
1512 * if your test failed in a recoverable way.
1514 * Do not use this function if the failure of a test could cause
1515 * other tests to malfunction.
1517 * Calling this function will not stop the test from running, you
1518 * need to return from the test function yourself. So you can
1519 * produce additional diagnostic messages or even continue running
1522 * If not called from inside a test, this function does nothing.
1529 test_run_success = FALSE;
1535 * The type used for test case functions.
1542 * @testpath: /-separated test case path name for the test.
1543 * @test_func: The test function to invoke for this test.
1545 * Create a new test case, similar to g_test_create_case(). However
1546 * the test is assumed to use no fixture, and test suites are automatically
1547 * created on the fly and added to the root fixture, based on the
1548 * slash-separated portions of @testpath.
1550 * If @testpath includes the component "subprocess" anywhere in it,
1551 * the test will be skipped by default, and only run if explicitly
1552 * required via the <option>-p</option> command-line option or
1553 * g_test_trap_subprocess().
1558 g_test_add_func (const char *testpath,
1559 GTestFunc test_func)
1561 g_return_if_fail (testpath != NULL);
1562 g_return_if_fail (testpath[0] == '/');
1563 g_return_if_fail (test_func != NULL);
1564 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1569 * @user_data: the data provided when registering the test
1571 * The type used for test case functions that take an extra pointer
1578 * g_test_add_data_func:
1579 * @testpath: /-separated test case path name for the test.
1580 * @test_data: Test data argument for the test function.
1581 * @test_func: The test function to invoke for this test.
1583 * Create a new test case, similar to g_test_create_case(). However
1584 * the test is assumed to use no fixture, and test suites are automatically
1585 * created on the fly and added to the root fixture, based on the
1586 * slash-separated portions of @testpath. The @test_data argument
1587 * will be passed as first argument to @test_func.
1589 * If @testpath includes the component "subprocess" anywhere in it,
1590 * the test will be skipped by default, and only run if explicitly
1591 * required via the <option>-p</option> command-line option or
1592 * g_test_trap_subprocess().
1597 g_test_add_data_func (const char *testpath,
1598 gconstpointer test_data,
1599 GTestDataFunc test_func)
1601 g_return_if_fail (testpath != NULL);
1602 g_return_if_fail (testpath[0] == '/');
1603 g_return_if_fail (test_func != NULL);
1605 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1609 * g_test_add_data_func_full:
1610 * @testpath: /-separated test case path name for the test.
1611 * @test_data: Test data argument for the test function.
1612 * @test_func: The test function to invoke for this test.
1613 * @data_free_func: #GDestroyNotify for @test_data.
1615 * Create a new test case, as with g_test_add_data_func(), but freeing
1616 * @test_data after the test run is complete.
1621 g_test_add_data_func_full (const char *testpath,
1623 GTestDataFunc test_func,
1624 GDestroyNotify data_free_func)
1626 g_return_if_fail (testpath != NULL);
1627 g_return_if_fail (testpath[0] == '/');
1628 g_return_if_fail (test_func != NULL);
1630 g_test_add_vtable (testpath, 0, test_data, NULL,
1631 (GTestFixtureFunc) test_func,
1632 (GTestFixtureFunc) data_free_func);
1636 g_test_suite_case_exists (GTestSuite *suite,
1637 const char *test_path)
1644 slash = strchr (test_path, '/');
1648 for (iter = suite->suites; iter; iter = iter->next)
1650 GTestSuite *child_suite = iter->data;
1652 if (!strncmp (child_suite->name, test_path, slash - test_path))
1653 if (g_test_suite_case_exists (child_suite, slash))
1659 for (iter = suite->cases; iter; iter = iter->next)
1662 if (!strcmp (tc->name, test_path))
1671 * g_test_create_suite:
1672 * @suite_name: a name for the suite
1674 * Create a new test suite with the name @suite_name.
1676 * Returns: A newly allocated #GTestSuite instance.
1681 g_test_create_suite (const char *suite_name)
1684 g_return_val_if_fail (suite_name != NULL, NULL);
1685 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1686 g_return_val_if_fail (suite_name[0] != 0, NULL);
1687 ts = g_slice_new0 (GTestSuite);
1688 ts->name = g_strdup (suite_name);
1694 * @suite: a #GTestSuite
1695 * @test_case: a #GTestCase
1697 * Adds @test_case to @suite.
1702 g_test_suite_add (GTestSuite *suite,
1703 GTestCase *test_case)
1705 g_return_if_fail (suite != NULL);
1706 g_return_if_fail (test_case != NULL);
1708 suite->cases = g_slist_prepend (suite->cases, test_case);
1712 * g_test_suite_add_suite:
1713 * @suite: a #GTestSuite
1714 * @nestedsuite: another #GTestSuite
1716 * Adds @nestedsuite to @suite.
1721 g_test_suite_add_suite (GTestSuite *suite,
1722 GTestSuite *nestedsuite)
1724 g_return_if_fail (suite != NULL);
1725 g_return_if_fail (nestedsuite != NULL);
1727 suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1731 * g_test_queue_free:
1732 * @gfree_pointer: the pointer to be stored.
1734 * Enqueue a pointer to be released with g_free() during the next
1735 * teardown phase. This is equivalent to calling g_test_queue_destroy()
1736 * with a destroy callback of g_free().
1741 g_test_queue_free (gpointer gfree_pointer)
1744 g_test_queue_destroy (g_free, gfree_pointer);
1748 * g_test_queue_destroy:
1749 * @destroy_func: Destroy callback for teardown phase.
1750 * @destroy_data: Destroy callback data.
1752 * This function enqueus a callback @destroy_func to be executed
1753 * during the next test case teardown phase. This is most useful
1754 * to auto destruct allocted test resources at the end of a test run.
1755 * Resources are released in reverse queue order, that means enqueueing
1756 * callback A before callback B will cause B() to be called before
1757 * A() during teardown.
1762 g_test_queue_destroy (GDestroyNotify destroy_func,
1763 gpointer destroy_data)
1765 DestroyEntry *dentry;
1767 g_return_if_fail (destroy_func != NULL);
1769 dentry = g_slice_new0 (DestroyEntry);
1770 dentry->destroy_func = destroy_func;
1771 dentry->destroy_data = destroy_data;
1772 dentry->next = test_destroy_queue;
1773 test_destroy_queue = dentry;
1777 test_case_run (GTestCase *tc)
1779 gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1780 gboolean success = TRUE;
1782 test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1783 if (strstr (test_run_name, "/subprocess"))
1786 gboolean found = FALSE;
1788 for (iter = test_paths; iter; iter = iter->next)
1790 if (!strcmp (test_run_name, iter->data))
1799 if (g_test_verbose ())
1800 g_print ("GTest: skipping: %s\n", test_run_name);
1805 if (++test_run_count <= test_skip_count)
1806 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1807 else if (test_run_list)
1809 g_print ("%s\n", test_run_name);
1810 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1814 GTimer *test_run_timer = g_timer_new();
1815 long double largs[3];
1817 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1819 test_run_success = TRUE;
1820 g_test_log_set_fatal_handler (NULL, NULL);
1821 g_timer_start (test_run_timer);
1822 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1823 test_run_seed (test_run_seedstr);
1824 if (tc->fixture_setup)
1825 tc->fixture_setup (fixture, tc->test_data);
1826 tc->fixture_test (fixture, tc->test_data);
1828 while (test_destroy_queue)
1830 DestroyEntry *dentry = test_destroy_queue;
1831 test_destroy_queue = dentry->next;
1832 dentry->destroy_func (dentry->destroy_data);
1833 g_slice_free (DestroyEntry, dentry);
1835 if (tc->fixture_teardown)
1836 tc->fixture_teardown (fixture, tc->test_data);
1837 if (tc->fixture_size)
1839 g_timer_stop (test_run_timer);
1840 success = test_run_success;
1841 test_run_success = FALSE;
1842 largs[0] = success ? 0 : 1; /* OK */
1843 largs[1] = test_run_forks;
1844 largs[2] = g_timer_elapsed (test_run_timer, NULL);
1845 g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1846 g_timer_destroy (test_run_timer);
1850 g_free (test_run_name);
1851 test_run_name = old_name;
1852 g_free (test_uri_base);
1853 test_uri_base = old_base;
1859 g_test_run_suite_internal (GTestSuite *suite,
1863 gchar *rest, *old_name = test_run_name;
1864 GSList *slist, *reversed;
1866 g_return_val_if_fail (suite != NULL, -1);
1868 while (path[0] == '/')
1871 rest = strchr (path, '/');
1872 l = rest ? MIN (l, rest - path) : l;
1873 test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1874 reversed = g_slist_reverse (g_slist_copy (suite->cases));
1875 for (slist = reversed; slist; slist = slist->next)
1877 GTestCase *tc = slist->data;
1878 guint n = l ? strlen (tc->name) : 0;
1879 if (l == n && !rest && strncmp (path, tc->name, n) == 0)
1881 if (!test_case_run (tc))
1885 g_slist_free (reversed);
1886 reversed = g_slist_reverse (g_slist_copy (suite->suites));
1887 for (slist = reversed; slist; slist = slist->next)
1889 GTestSuite *ts = slist->data;
1890 guint n = l ? strlen (ts->name) : 0;
1891 if (l == n && strncmp (path, ts->name, n) == 0)
1892 n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
1894 g_slist_free (reversed);
1895 g_free (test_run_name);
1896 test_run_name = old_name;
1903 * @suite: a #GTestSuite
1905 * Execute the tests within @suite and all nested #GTestSuites.
1906 * The test suites to be executed are filtered according to
1907 * test path arguments (-p <replaceable>testpath</replaceable>)
1908 * as parsed by g_test_init().
1909 * g_test_run_suite() or g_test_run() may only be called once
1912 * Returns: 0 on success
1917 g_test_run_suite (GTestSuite *suite)
1919 GSList *my_test_paths;
1922 g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1923 g_return_val_if_fail (g_test_run_once == TRUE, -1);
1925 g_test_run_once = FALSE;
1928 my_test_paths = g_slist_copy (test_paths);
1930 my_test_paths = g_slist_prepend (NULL, "");
1932 while (my_test_paths)
1934 const char *rest, *path = my_test_paths->data;
1935 guint l, n = strlen (suite->name);
1936 my_test_paths = g_slist_delete_link (my_test_paths, my_test_paths);
1937 while (path[0] == '/')
1939 if (!n) /* root suite, run unconditionally */
1941 n_bad += g_test_run_suite_internal (suite, path);
1944 /* regular suite, match path */
1945 rest = strchr (path, '/');
1947 l = rest ? MIN (l, rest - path) : l;
1948 if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1949 n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
1956 gtest_default_log_handler (const gchar *log_domain,
1957 GLogLevelFlags log_level,
1958 const gchar *message,
1959 gpointer unused_data)
1961 const gchar *strv[16];
1962 gboolean fatal = FALSE;
1968 strv[i++] = log_domain;
1971 if (log_level & G_LOG_FLAG_FATAL)
1973 strv[i++] = "FATAL-";
1976 if (log_level & G_LOG_FLAG_RECURSION)
1977 strv[i++] = "RECURSIVE-";
1978 if (log_level & G_LOG_LEVEL_ERROR)
1979 strv[i++] = "ERROR";
1980 if (log_level & G_LOG_LEVEL_CRITICAL)
1981 strv[i++] = "CRITICAL";
1982 if (log_level & G_LOG_LEVEL_WARNING)
1983 strv[i++] = "WARNING";
1984 if (log_level & G_LOG_LEVEL_MESSAGE)
1985 strv[i++] = "MESSAGE";
1986 if (log_level & G_LOG_LEVEL_INFO)
1988 if (log_level & G_LOG_LEVEL_DEBUG)
1989 strv[i++] = "DEBUG";
1991 strv[i++] = message;
1994 msg = g_strjoinv ("", (gchar**) strv);
1995 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
1996 g_log_default_handler (log_domain, log_level, message, unused_data);
2002 g_assertion_message (const char *domain,
2006 const char *message)
2012 message = "code should not be reached";
2013 g_snprintf (lstr, 32, "%d", line);
2014 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
2015 "ERROR:", file, ":", lstr, ":",
2016 func, func[0] ? ":" : "",
2017 " ", message, NULL);
2018 g_printerr ("**\n%s\n", s);
2020 /* store assertion message in global variable, so that it can be found in a
2022 if (__glib_assert_msg != NULL)
2023 /* free the old one */
2024 free (__glib_assert_msg);
2025 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
2026 strcpy (__glib_assert_msg, s);
2028 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
2034 g_assertion_message_expr (const char *domain,
2040 char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
2041 g_assertion_message (domain, file, line, func, s);
2046 g_assertion_message_cmpnum (const char *domain,
2060 case 'i': s = g_strdup_printf ("assertion failed (%s): (%" G_GINT64_MODIFIER "i %s %" G_GINT64_MODIFIER "i)", expr, (gint64) arg1, cmp, (gint64) arg2); break;
2061 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;
2062 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr, (double) arg1, cmp, (double) arg2); break;
2063 /* ideally use: floats=%.7g double=%.17g */
2065 g_assertion_message (domain, file, line, func, s);
2070 g_assertion_message_cmpstr (const char *domain,
2079 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
2080 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
2081 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
2084 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
2087 g_assertion_message (domain, file, line, func, s);
2092 g_assertion_message_error (const char *domain,
2097 const GError *error,
2098 GQuark error_domain,
2103 /* This is used by both g_assert_error() and g_assert_no_error(), so there
2104 * are three cases: expected an error but got the wrong error, expected
2105 * an error but got no error, and expected no error but got an error.
2108 gstring = g_string_new ("assertion failed ");
2110 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
2111 g_quark_to_string (error_domain), error_code);
2113 g_string_append_printf (gstring, "(%s == NULL): ", expr);
2116 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
2117 g_quark_to_string (error->domain), error->code);
2119 g_string_append_printf (gstring, "%s is NULL", expr);
2121 g_assertion_message (domain, file, line, func, gstring->str);
2122 g_string_free (gstring, TRUE);
2127 * @str1: (allow-none): a C string or %NULL
2128 * @str2: (allow-none): another C string or %NULL
2130 * Compares @str1 and @str2 like strcmp(). Handles %NULL
2131 * gracefully by sorting it before non-%NULL strings.
2132 * Comparing two %NULL pointers returns 0.
2134 * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
2139 g_strcmp0 (const char *str1,
2143 return -(str1 != str2);
2145 return str1 != str2;
2146 return strcmp (str1, str2);
2150 test_trap_clear (void)
2152 test_trap_last_status = 0;
2153 test_trap_last_pid = 0;
2154 g_free (test_trap_last_subprocess);
2155 test_trap_last_subprocess = NULL;
2156 g_free (test_trap_last_stdout);
2157 test_trap_last_stdout = NULL;
2158 g_free (test_trap_last_stderr);
2159 test_trap_last_stderr = NULL;
2170 ret = dup2 (fd1, fd2);
2171 while (ret < 0 && errno == EINTR);
2182 GIOChannel *stdout_io;
2183 gboolean echo_stdout;
2184 GString *stdout_str;
2186 GIOChannel *stderr_io;
2187 gboolean echo_stderr;
2188 GString *stderr_str;
2192 check_complete (WaitForChildData *data)
2194 if (data->child_status != -1 && data->stdout_io == NULL && data->stderr_io == NULL)
2195 g_main_loop_quit (data->loop);
2199 child_exited (GPid pid,
2203 WaitForChildData *data = user_data;
2206 if (WIFEXITED (status)) /* normal exit */
2207 data->child_status = WEXITSTATUS (status); /* 0..255 */
2208 else if (WIFSIGNALED (status) && WTERMSIG (status) == SIGALRM)
2209 data->child_status = G_TEST_STATUS_TIMED_OUT;
2210 else if (WIFSIGNALED (status))
2211 data->child_status = (WTERMSIG (status) << 12); /* signalled */
2212 else /* WCOREDUMP (status) */
2213 data->child_status = 512; /* coredump */
2215 data->child_status = status;
2218 check_complete (data);
2222 child_timeout (gpointer user_data)
2224 WaitForChildData *data = user_data;
2227 TerminateProcess (data->pid, G_TEST_STATUS_TIMED_OUT);
2229 kill (data->pid, SIGALRM);
2236 child_read (GIOChannel *io, GIOCondition cond, gpointer user_data)
2238 WaitForChildData *data = user_data;
2240 gsize nread, nwrote, total;
2244 status = g_io_channel_read_chars (io, buf, sizeof (buf), &nread, NULL);
2245 if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF)
2247 // FIXME data->error = (status == G_IO_STATUS_ERROR);
2248 if (io == data->stdout_io)
2249 g_clear_pointer (&data->stdout_io, g_io_channel_unref);
2251 g_clear_pointer (&data->stderr_io, g_io_channel_unref);
2253 check_complete (data);
2256 else if (status == G_IO_STATUS_AGAIN)
2259 if (io == data->stdout_io)
2261 g_string_append_len (data->stdout_str, buf, nread);
2262 if (data->echo_stdout)
2263 echo_fd = STDOUT_FILENO;
2267 g_string_append_len (data->stderr_str, buf, nread);
2268 if (data->echo_stderr)
2269 echo_fd = STDERR_FILENO;
2274 for (total = 0; total < nread; total += nwrote)
2277 nwrote = write (echo_fd, buf + total, nread - total);
2278 while (nwrote == -1 && errno == EINTR);
2280 g_error ("write failed: %s", g_strerror (errno));
2289 wait_for_child (GPid pid,
2290 int stdout_fd, gboolean echo_stdout,
2291 int stderr_fd, gboolean echo_stderr,
2294 WaitForChildData data;
2295 GMainContext *context;
2299 data.child_status = -1;
2301 context = g_main_context_new ();
2302 data.loop = g_main_loop_new (context, FALSE);
2304 source = g_child_watch_source_new (pid);
2305 g_source_set_callback (source, (GSourceFunc) child_exited, &data, NULL);
2306 g_source_attach (source, context);
2307 g_source_unref (source);
2309 data.echo_stdout = echo_stdout;
2310 data.stdout_str = g_string_new (NULL);
2311 data.stdout_io = g_io_channel_unix_new (stdout_fd);
2312 g_io_channel_set_close_on_unref (data.stdout_io, TRUE);
2313 g_io_channel_set_encoding (data.stdout_io, NULL, NULL);
2314 g_io_channel_set_buffered (data.stdout_io, FALSE);
2315 source = g_io_create_watch (data.stdout_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2316 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2317 g_source_attach (source, context);
2318 g_source_unref (source);
2320 data.echo_stderr = echo_stderr;
2321 data.stderr_str = g_string_new (NULL);
2322 data.stderr_io = g_io_channel_unix_new (stderr_fd);
2323 g_io_channel_set_close_on_unref (data.stderr_io, TRUE);
2324 g_io_channel_set_encoding (data.stderr_io, NULL, NULL);
2325 g_io_channel_set_buffered (data.stderr_io, FALSE);
2326 source = g_io_create_watch (data.stderr_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2327 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2328 g_source_attach (source, context);
2329 g_source_unref (source);
2333 source = g_timeout_source_new (0);
2334 g_source_set_ready_time (source, g_get_monotonic_time () + timeout);
2335 g_source_set_callback (source, (GSourceFunc) child_timeout, &data, NULL);
2336 g_source_attach (source, context);
2337 g_source_unref (source);
2340 g_main_loop_run (data.loop);
2341 g_main_loop_unref (data.loop);
2342 g_main_context_unref (context);
2344 test_trap_last_pid = pid;
2345 test_trap_last_status = data.child_status;
2346 test_trap_last_stdout = g_string_free (data.stdout_str, FALSE);
2347 test_trap_last_stderr = g_string_free (data.stderr_str, FALSE);
2349 g_clear_pointer (&data.stdout_io, g_io_channel_unref);
2350 g_clear_pointer (&data.stderr_io, g_io_channel_unref);
2355 * @usec_timeout: Timeout for the forked test in micro seconds.
2356 * @test_trap_flags: Flags to modify forking behaviour.
2358 * Fork the current test program to execute a test case that might
2359 * not return or that might abort.
2361 * If @usec_timeout is non-0, the forked test case is aborted and
2362 * considered failing if its run time exceeds it.
2364 * The forking behavior can be configured with the #GTestTrapFlags flags.
2366 * In the following example, the test code forks, the forked child
2367 * process produces some sample output and exits successfully.
2368 * The forking parent process then asserts successful child program
2369 * termination and validates child program outputs.
2373 * test_fork_patterns (void)
2375 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2377 * g_print ("some stdout text: somagic17\n");
2378 * g_printerr ("some stderr text: semagic43\n");
2379 * exit (0); /* successful test run */
2381 * g_test_trap_assert_passed ();
2382 * g_test_trap_assert_stdout ("*somagic17*");
2383 * g_test_trap_assert_stderr ("*semagic43*");
2387 * This function is implemented only on Unix platforms.
2389 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2394 g_test_trap_fork (guint64 usec_timeout,
2395 GTestTrapFlags test_trap_flags)
2398 int stdout_pipe[2] = { -1, -1 };
2399 int stderr_pipe[2] = { -1, -1 };
2402 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0)
2403 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
2404 test_trap_last_pid = fork ();
2405 if (test_trap_last_pid < 0)
2406 g_error ("failed to fork test program: %s", g_strerror (errno));
2407 if (test_trap_last_pid == 0) /* child */
2410 close (stdout_pipe[0]);
2411 close (stderr_pipe[0]);
2412 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2413 fd0 = g_open ("/dev/null", O_RDONLY, 0);
2414 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2415 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
2418 if (stdout_pipe[1] >= 3)
2419 close (stdout_pipe[1]);
2420 if (stderr_pipe[1] >= 3)
2421 close (stderr_pipe[1]);
2427 close (stdout_pipe[1]);
2428 close (stderr_pipe[1]);
2430 wait_for_child (test_trap_last_pid,
2431 stdout_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT),
2432 stderr_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR),
2437 g_message ("Not implemented: g_test_trap_fork");
2444 * g_test_trap_subprocess:
2445 * @test_name: Test to run in a subprocess
2446 * @usec_timeout: Timeout for the subprocess test in micro seconds.
2447 * @test_flags: Flags to modify subprocess behaviour.
2449 * Respawns the test program to run only @test_name in a subprocess.
2450 * This can be used for a test case that might not return, or that
2451 * might abort. @test_name will normally be the name of the parent
2452 * test, followed by "<literal>/subprocess/</literal>" and then a name
2453 * for the specific subtest (or just ending with
2454 * "<literal>/subprocess</literal>" if the test only has one child
2455 * test); tests with names of this form will automatically be skipped
2456 * in the parent process.
2458 * If @usec_timeout is non-0, the test subprocess is aborted and
2459 * considered failing if its run time exceeds it.
2461 * The subprocess behavior can be configured with the
2462 * #GTestSubprocessFlags flags.
2464 * You can use methods such as g_test_trap_assert_passed(),
2465 * g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to
2466 * check the results of the subprocess. (But note that
2467 * g_test_trap_assert_stdout() and g_test_trap_assert_stderr()
2468 * cannot be used if @test_flags specifies that the child should
2469 * inherit the parent stdout/stderr.)
2471 * If your <literal>main ()</literal> needs to behave differently in
2472 * the subprocess, you can call g_test_subprocess() (after calling
2473 * g_test_init()) to see whether you are in a subprocess.
2475 * The following example tests that calling
2476 * <literal>my_object_new(1000000)</literal> will abort with an error
2481 * test_create_large_object_subprocess (void)
2483 * my_object_new (1000000);
2487 * test_create_large_object (void)
2489 * g_test_trap_subprocess ("/myobject/create_large_object/subprocess", 0, 0);
2490 * g_test_trap_assert_failed ();
2491 * g_test_trap_assert_stderr ("*ERROR*too large*");
2495 * main (int argc, char **argv)
2497 * g_test_init (&argc, &argv, NULL);
2499 * g_test_add_func ("/myobject/create_large_object",
2500 * test_create_large_object);
2501 * /* Because of the '/subprocess' in the name, this test will
2502 * * not be run by the g_test_run () call below.
2504 * g_test_add_func ("/myobject/create_large_object/subprocess",
2505 * test_create_large_object_subprocess);
2507 * return g_test_run ();
2514 g_test_trap_subprocess (const char *test_path,
2515 guint64 usec_timeout,
2516 GTestSubprocessFlags test_flags)
2518 GError *error = NULL;
2521 int stdout_fd, stderr_fd;
2524 /* Sanity check that they used GTestSubprocessFlags, not GTestTrapFlags */
2525 g_assert ((test_flags & (G_TEST_TRAP_INHERIT_STDIN | G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR)) == 0);
2527 if (!g_test_suite_case_exists (g_test_get_root (), test_path))
2528 g_error ("g_test_trap_subprocess: test does not exist: %s", test_path);
2530 if (g_test_verbose ())
2531 g_print ("GTest: subprocess: %s\n", test_path);
2534 test_trap_last_subprocess = g_strdup (test_path);
2536 argv = g_ptr_array_new ();
2537 g_ptr_array_add (argv, test_argv0);
2538 g_ptr_array_add (argv, "-q");
2539 g_ptr_array_add (argv, "-p");
2540 g_ptr_array_add (argv, (char *)test_path);
2541 g_ptr_array_add (argv, "--GTestSubprocess");
2542 if (test_log_fd != -1)
2544 char log_fd_buf[128];
2546 g_ptr_array_add (argv, "--GTestLogFD");
2547 g_snprintf (log_fd_buf, sizeof (log_fd_buf), "%d", test_log_fd);
2548 g_ptr_array_add (argv, log_fd_buf);
2550 g_ptr_array_add (argv, NULL);
2552 flags = G_SPAWN_DO_NOT_REAP_CHILD;
2553 if (test_flags & G_TEST_TRAP_INHERIT_STDIN)
2554 flags |= G_SPAWN_CHILD_INHERITS_STDIN;
2556 if (!g_spawn_async_with_pipes (test_initial_cwd,
2557 (char **)argv->pdata,
2560 &pid, NULL, &stdout_fd, &stderr_fd,
2563 g_error ("g_test_trap_subprocess() failed: %s\n",
2566 g_ptr_array_free (argv, TRUE);
2568 wait_for_child (pid,
2569 stdout_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDOUT),
2570 stderr_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDERR),
2575 * g_test_subprocess:
2577 * Returns %TRUE (after g_test_init() has been called) if the test
2578 * program is running under g_test_trap_subprocess().
2580 * Returns: %TRUE if the test program is running under
2581 * g_test_trap_subprocess().
2586 g_test_subprocess (void)
2588 return test_in_subprocess;
2592 * g_test_trap_has_passed:
2594 * Check the result of the last g_test_trap_subprocess() call.
2596 * Returns: %TRUE if the last test subprocess terminated successfully.
2601 g_test_trap_has_passed (void)
2603 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
2607 * g_test_trap_reached_timeout:
2609 * Check the result of the last g_test_trap_subprocess() call.
2611 * Returns: %TRUE if the last test subprocess got killed due to a timeout.
2616 g_test_trap_reached_timeout (void)
2618 return test_trap_last_status != G_TEST_STATUS_TIMED_OUT;
2622 g_test_trap_assertions (const char *domain,
2626 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
2627 const char *pattern)
2629 gboolean must_pass = assertion_flags == 0;
2630 gboolean must_fail = assertion_flags == 1;
2631 gboolean match_result = 0 == (assertion_flags & 1);
2632 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
2633 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
2634 const char *match_error = match_result ? "failed to match" : "contains invalid match";
2638 if (test_trap_last_subprocess != NULL)
2640 process_id = g_strdup_printf ("%s [%d]", test_trap_last_subprocess,
2641 test_trap_last_pid);
2643 else if (test_trap_last_pid != 0)
2644 process_id = g_strdup_printf ("%d", test_trap_last_pid);
2646 if (test_trap_last_subprocess != NULL)
2647 process_id = g_strdup (test_trap_last_subprocess);
2650 g_error ("g_test_trap_ assertion with no trapped test");
2652 if (must_pass && !g_test_trap_has_passed())
2654 char *msg = g_strdup_printf ("child process (%s) failed unexpectedly", process_id);
2655 g_assertion_message (domain, file, line, func, msg);
2658 if (must_fail && g_test_trap_has_passed())
2660 char *msg = g_strdup_printf ("child process (%s) did not fail as expected", process_id);
2661 g_assertion_message (domain, file, line, func, msg);
2664 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
2666 char *msg = g_strdup_printf ("stdout of child process (%s) %s: %s", process_id, match_error, stdout_pattern);
2667 g_assertion_message (domain, file, line, func, msg);
2670 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
2672 char *msg = g_strdup_printf ("stderr of child process (%s) %s: %s", process_id, match_error, stderr_pattern);
2673 g_assertion_message (domain, file, line, func, msg);
2679 gstring_overwrite_int (GString *gstring,
2683 vuint = g_htonl (vuint);
2684 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
2688 gstring_append_int (GString *gstring,
2691 vuint = g_htonl (vuint);
2692 g_string_append_len (gstring, (const gchar*) &vuint, 4);
2696 gstring_append_double (GString *gstring,
2699 union { double vdouble; guint64 vuint64; } u;
2700 u.vdouble = vdouble;
2701 u.vuint64 = GUINT64_TO_BE (u.vuint64);
2702 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
2706 g_test_log_dump (GTestLogMsg *msg,
2709 GString *gstring = g_string_sized_new (1024);
2711 gstring_append_int (gstring, 0); /* message length */
2712 gstring_append_int (gstring, msg->log_type);
2713 gstring_append_int (gstring, msg->n_strings);
2714 gstring_append_int (gstring, msg->n_nums);
2715 gstring_append_int (gstring, 0); /* reserved */
2716 for (ui = 0; ui < msg->n_strings; ui++)
2718 guint l = strlen (msg->strings[ui]);
2719 gstring_append_int (gstring, l);
2720 g_string_append_len (gstring, msg->strings[ui], l);
2722 for (ui = 0; ui < msg->n_nums; ui++)
2723 gstring_append_double (gstring, msg->nums[ui]);
2724 *len = gstring->len;
2725 gstring_overwrite_int (gstring, 0, *len); /* message length */
2726 return (guint8*) g_string_free (gstring, FALSE);
2729 static inline long double
2730 net_double (const gchar **ipointer)
2732 union { guint64 vuint64; double vdouble; } u;
2733 guint64 aligned_int64;
2734 memcpy (&aligned_int64, *ipointer, 8);
2736 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
2740 static inline guint32
2741 net_int (const gchar **ipointer)
2743 guint32 aligned_int;
2744 memcpy (&aligned_int, *ipointer, 4);
2746 return g_ntohl (aligned_int);
2750 g_test_log_extract (GTestLogBuffer *tbuffer)
2752 const gchar *p = tbuffer->data->str;
2755 if (tbuffer->data->len < 4 * 5)
2757 mlength = net_int (&p);
2758 if (tbuffer->data->len < mlength)
2760 msg.log_type = net_int (&p);
2761 msg.n_strings = net_int (&p);
2762 msg.n_nums = net_int (&p);
2763 if (net_int (&p) == 0)
2766 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
2767 msg.nums = g_new0 (long double, msg.n_nums);
2768 for (ui = 0; ui < msg.n_strings; ui++)
2770 guint sl = net_int (&p);
2771 msg.strings[ui] = g_strndup (p, sl);
2774 for (ui = 0; ui < msg.n_nums; ui++)
2775 msg.nums[ui] = net_double (&p);
2776 if (p <= tbuffer->data->str + mlength)
2778 g_string_erase (tbuffer->data, 0, mlength);
2779 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
2784 g_strfreev (msg.strings);
2785 g_error ("corrupt log stream from test program");
2790 * g_test_log_buffer_new:
2792 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2795 g_test_log_buffer_new (void)
2797 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
2798 tb->data = g_string_sized_new (1024);
2803 * g_test_log_buffer_free:
2805 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2808 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
2810 g_return_if_fail (tbuffer != NULL);
2811 while (tbuffer->msgs)
2812 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
2813 g_string_free (tbuffer->data, TRUE);
2818 * g_test_log_buffer_push:
2820 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2823 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
2825 const guint8 *bytes)
2827 g_return_if_fail (tbuffer != NULL);
2830 gboolean more_messages;
2831 g_return_if_fail (bytes != NULL);
2832 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
2834 more_messages = g_test_log_extract (tbuffer);
2835 while (more_messages);
2840 * g_test_log_buffer_pop:
2842 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
2845 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
2847 GTestLogMsg *msg = NULL;
2848 g_return_val_if_fail (tbuffer != NULL, NULL);
2851 GSList *slist = g_slist_last (tbuffer->msgs);
2853 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
2859 * g_test_log_msg_free:
2861 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2864 g_test_log_msg_free (GTestLogMsg *tmsg)
2866 g_return_if_fail (tmsg != NULL);
2867 g_strfreev (tmsg->strings);
2868 g_free (tmsg->nums);
2872 /* --- macros docs START --- */
2875 * @testpath: The test path for a new test case.
2876 * @Fixture: The type of a fixture data structure.
2877 * @tdata: Data argument for the test functions.
2878 * @fsetup: The function to set up the fixture data.
2879 * @ftest: The actual test function.
2880 * @fteardown: The function to tear down the fixture data.
2882 * Hook up a new test case at @testpath, similar to g_test_add_func().
2883 * A fixture data structure with setup and teardown function may be provided
2884 * though, similar to g_test_create_case().
2885 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2886 * fteardown() callbacks can expect a @Fixture pointer as first argument in
2887 * a type safe manner.
2891 /* --- macros docs END --- */