1 /* GLib testing utilities
2 * Copyright (C) 2007 Imendio AB
3 * Authors: Tim Janik, Sven Herzberg
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
23 #include "gtestutils.h"
25 #include <sys/types.h>
42 #ifdef HAVE_SYS_SELECT_H
43 #include <sys/select.h>
44 #endif /* HAVE_SYS_SELECT_H */
49 #include "gstrfuncs.h"
57 * @short_description: a test framework
58 * @see_also: <link linkend="gtester">gtester</link>,
59 * <link linkend="gtester-report">gtester-report</link>
61 * GLib provides a framework for writing and maintaining unit tests
62 * in parallel to the code they are testing. The API is designed according
63 * to established concepts found in the other test frameworks (JUnit, NUnit,
64 * RUnit), which in turn is based on smalltalk unit testing concepts.
68 * <term>Test case</term>
69 * <listitem>Tests (test methods) are grouped together with their
70 * fixture into test cases.</listitem>
73 * <term>Fixture</term>
74 * <listitem>A test fixture consists of fixture data and setup and
75 * teardown methods to establish the environment for the test
76 * functions. We use fresh fixtures, i.e. fixtures are newly set
77 * up and torn down around each test invocation to avoid dependencies
78 * between tests.</listitem>
81 * <term>Test suite</term>
82 * <listitem>Test cases can be grouped into test suites, to allow
83 * subsets of the available tests to be run. Test suites can be
84 * grouped into other test suites as well.</listitem>
87 * The API is designed to handle creation and registration of test suites
88 * and test cases implicitly. A simple call like
90 * g_test_add_func ("/misc/assertions", test_assertions);
92 * creates a test suite called "misc" with a single test case named
93 * "assertions", which consists of running the test_assertions function.
95 * In addition to the traditional g_assert(), the test framework provides
96 * an extended set of assertions for string and numerical comparisons:
97 * g_assert_cmpfloat(), g_assert_cmpint(), g_assert_cmpuint(),
98 * g_assert_cmphex(), g_assert_cmpstr(). The advantage of these variants
99 * over plain g_assert() is that the assertion messages can be more
100 * elaborate, and include the values of the compared entities.
102 * GLib ships with two utilities called gtester and gtester-report to
103 * facilitate running tests and producing nicely formatted test reports.
109 * Returns %TRUE if tests are run in quick mode.
111 * Returns: %TRUE if in quick mode
117 * Returns %TRUE if tests are run in slow mode.
119 * Returns: %TRUE if in slow mode
125 * Returns %TRUE if tests are run in thorough mode.
127 * Returns: %TRUE if in thorough mode
133 * Returns %TRUE if tests are run in performance mode.
135 * Returns: %TRUE if in performance mode
141 * Returns %TRUE if tests are run in verbose mode.
143 * Returns: %TRUE if in verbose mode
149 * Returns %TRUE if tests are run in quiet mode.
151 * Returns: %TRUE if in quied mode
155 * g_test_queue_unref:
156 * @gobject: the object to unref
158 * Enqueue an object to be released with g_object_unref() during
159 * the next teardown phase. This is equivalent to calling
160 * g_test_queue_destroy() with a destroy callback of g_object_unref().
167 * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
168 * <filename>/dev/null</filename> so it cannot be observed on the
169 * console during test runs. The actual output is still captured
170 * though to allow later tests with g_test_trap_assert_stdout().
171 * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
172 * <filename>/dev/null</filename> so it cannot be observed on the
173 * console during test runs. The actual output is still captured
174 * though to allow later tests with g_test_trap_assert_stderr().
175 * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
176 * forked child process is shared with stdin of its parent process.
177 * It is redirected to <filename>/dev/null</filename> otherwise.
179 * Test traps are guards around forked tests.
180 * These flags determine what traps to set.
184 * g_test_trap_assert_passed:
186 * Assert that the last forked test passed.
187 * See g_test_trap_fork().
193 * g_test_trap_assert_failed:
195 * Assert that the last forked test failed.
196 * See g_test_trap_fork().
202 * g_test_trap_assert_stdout:
203 * @soutpattern: a glob-style
204 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
206 * Assert that the stdout output of the last forked test matches
207 * @soutpattern. See g_test_trap_fork().
213 * g_test_trap_assert_stdout_unmatched:
214 * @soutpattern: a glob-style
215 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
217 * Assert that the stdout output of the last forked test
218 * does not match @soutpattern. See g_test_trap_fork().
224 * g_test_trap_assert_stderr:
225 * @serrpattern: a glob-style
226 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
228 * Assert that the stderr output of the last forked test
229 * matches @serrpattern. See g_test_trap_fork().
235 * g_test_trap_assert_stderr_unmatched:
236 * @serrpattern: a glob-style
237 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
239 * Assert that the stderr output of the last forked test
240 * does not match @serrpattern. See g_test_trap_fork().
248 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
249 * for details on test case random numbers.
256 * @expr: the expression to check
258 * Debugging macro to terminate the application if the assertion
259 * fails. If the assertion fails (i.e. the expression is not true),
260 * an error message is logged and the application is terminated.
262 * The macro can be turned off in final releases of code by defining
263 * #G_DISABLE_ASSERT when compiling the application.
267 * g_assert_not_reached:
269 * Debugging macro to terminate the application if it is ever
270 * reached. If it is reached, an error message is logged and the
271 * application is terminated.
273 * The macro can be turned off in final releases of code by defining
274 * #G_DISABLE_ASSERT when compiling the application.
279 * @s1: a string (may be %NULL)
280 * @cmp: The comparison operator to use.
281 * One of ==, !=, <, >, <=, >=.
282 * @s2: another string (may be %NULL)
284 * Debugging macro to terminate the application with a warning
285 * message if a string comparison fails. The strings are compared
288 * The effect of <literal>g_assert_cmpstr (s1, op, s2)</literal> is
289 * the same as <literal>g_assert (g_strcmp0 (s1, s2) op 0)</literal>.
290 * The advantage of this macro is that it can produce a message that
291 * includes the actual values of @s1 and @s2.
294 * g_assert_cmpstr (mystring, ==, "fubar");
303 * @cmp: The comparison operator to use.
304 * One of ==, !=, <, >, <=, >=.
305 * @n2: another integer
307 * Debugging macro to terminate the application with a warning
308 * message if an integer comparison fails.
310 * The effect of <literal>g_assert_cmpint (n1, op, n2)</literal> is
311 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
312 * of this macro is that it can produce a message that includes the
313 * actual values of @n1 and @n2.
320 * @n1: an unsigned integer
321 * @cmp: The comparison operator to use.
322 * One of ==, !=, <, >, <=, >=.
323 * @n2: another unsigned integer
325 * Debugging macro to terminate the application with a warning
326 * message if an unsigned integer comparison fails.
328 * The effect of <literal>g_assert_cmpuint (n1, op, n2)</literal> is
329 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
330 * of this macro is that it can produce a message that includes the
331 * actual values of @n1 and @n2.
338 * @n1: an unsigned integer
339 * @cmp: The comparison operator to use.
340 * One of ==, !=, <, >, <=, >=.
341 * @n2: another unsigned integer
343 * Debugging macro to terminate the application with a warning
344 * message if an unsigned integer comparison fails.
346 * This is a variant of g_assert_cmpuint() that displays the numbers
347 * in hexadecimal notation in the message.
354 * @n1: an floating point number
355 * @cmp: The comparison operator to use.
356 * One of ==, !=, <, >, <=, >=.
357 * @n2: another floating point number
359 * Debugging macro to terminate the application with a warning
360 * message if a floating point number comparison fails.
362 * The effect of <literal>g_assert_cmpfloat (n1, op, n2)</literal> is
363 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
364 * of this macro is that it can produce a message that includes the
365 * actual values of @n1 and @n2.
372 * @err: a #GError, possibly %NULL
374 * Debugging macro to terminate the application with a warning
375 * message if a method has returned a #GError.
377 * The effect of <literal>g_assert_no_error (err)</literal> is
378 * the same as <literal>g_assert (err == NULL)</literal>. The advantage
379 * of this macro is that it can produce a message that includes
380 * the error message and code.
387 * @err: a #GError, possibly %NULL
388 * @dom: the expected error domain (a #GQuark)
389 * @c: the expected error code
391 * Debugging macro to terminate the application with a warning
392 * message if a method has not returned the correct #GError.
394 * The effect of <literal>g_assert_error (err, dom, c)</literal> is
395 * the same as <literal>g_assert (err != NULL && err->domain
396 * == dom && err->code == c)</literal>. The advantage of this
397 * macro is that it can produce a message that includes the incorrect
398 * error message and code.
400 * This can only be used to test for a specific error. If you want to
401 * test that @err is set, but don't care what it's set to, just use
402 * <literal>g_assert (err != NULL)</literal>
410 * An opaque structure representing a test case.
416 * An opaque structure representing a test suite.
420 /* Global variable for storing assertion messages; this is the counterpart to
421 * glibc's (private) __abort_msg variable, and allows developers and crash
422 * analysis systems like Apport and ABRT to fish out assertion messages from
423 * core dumps, instead of having to catch them on screen output.
425 char *__glib_assert_msg = NULL;
427 /* --- structures --- */
432 void (*fixture_setup) (void*, gconstpointer);
433 void (*fixture_test) (void*, gconstpointer);
434 void (*fixture_teardown) (void*, gconstpointer);
443 typedef struct DestroyEntry DestroyEntry;
447 GDestroyNotify destroy_func;
448 gpointer destroy_data;
451 /* --- prototypes --- */
452 static void test_run_seed (const gchar *rseed);
453 static void test_trap_clear (void);
454 static guint8* g_test_log_dump (GTestLogMsg *msg,
456 static void gtest_default_log_handler (const gchar *log_domain,
457 GLogLevelFlags log_level,
458 const gchar *message,
459 gpointer unused_data);
462 /* --- variables --- */
463 static int test_log_fd = -1;
464 static gboolean test_mode_fatal = TRUE;
465 static gboolean g_test_run_once = TRUE;
466 static gboolean test_run_list = FALSE;
467 static gchar *test_run_seedstr = NULL;
468 static GRand *test_run_rand = NULL;
469 static gchar *test_run_name = "";
470 static guint test_run_forks = 0;
471 static guint test_run_count = 0;
472 static guint test_run_success = FALSE;
473 static guint test_skip_count = 0;
474 static GTimer *test_user_timer = NULL;
475 static double test_user_stamp = 0;
476 static GSList *test_paths = NULL;
477 static GTestSuite *test_suite_root = NULL;
478 static int test_trap_last_status = 0;
479 static int test_trap_last_pid = 0;
480 static char *test_trap_last_stdout = NULL;
481 static char *test_trap_last_stderr = NULL;
482 static char *test_uri_base = NULL;
483 static gboolean test_debug_log = FALSE;
484 static DestroyEntry *test_destroy_queue = NULL;
485 static GTestConfig mutable_test_config_vars = {
486 FALSE, /* test_initialized */
487 TRUE, /* test_quick */
488 FALSE, /* test_perf */
489 FALSE, /* test_verbose */
490 FALSE, /* test_quiet */
492 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
494 /* --- functions --- */
496 g_test_log_type_name (GTestLogType log_type)
500 case G_TEST_LOG_NONE: return "none";
501 case G_TEST_LOG_ERROR: return "error";
502 case G_TEST_LOG_START_BINARY: return "binary";
503 case G_TEST_LOG_LIST_CASE: return "list";
504 case G_TEST_LOG_SKIP_CASE: return "skip";
505 case G_TEST_LOG_START_CASE: return "start";
506 case G_TEST_LOG_STOP_CASE: return "stop";
507 case G_TEST_LOG_MIN_RESULT: return "minperf";
508 case G_TEST_LOG_MAX_RESULT: return "maxperf";
509 case G_TEST_LOG_MESSAGE: return "message";
515 g_test_log_send (guint n_bytes,
516 const guint8 *buffer)
518 if (test_log_fd >= 0)
522 r = write (test_log_fd, buffer, n_bytes);
523 while (r < 0 && errno == EINTR);
527 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
530 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
531 msg = g_test_log_buffer_pop (lbuffer);
532 g_warn_if_fail (msg != NULL);
533 g_warn_if_fail (lbuffer->data->len == 0);
534 g_test_log_buffer_free (lbuffer);
536 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
537 for (ui = 0; ui < msg->n_strings; ui++)
538 g_printerr (":{%s}", msg->strings[ui]);
542 for (ui = 0; ui < msg->n_nums; ui++)
543 g_printerr ("%s%.16Lg", ui ? ";" : "", msg->nums[ui]);
546 g_printerr (":LOG*}\n");
547 g_test_log_msg_free (msg);
552 g_test_log (GTestLogType lbit,
553 const gchar *string1,
554 const gchar *string2,
558 gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
560 gchar *astrings[3] = { NULL, NULL, NULL };
566 case G_TEST_LOG_START_BINARY:
567 if (g_test_verbose())
568 g_print ("GTest: random seed: %s\n", string2);
570 case G_TEST_LOG_STOP_CASE:
571 if (g_test_verbose())
572 g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
573 else if (!g_test_quiet())
574 g_print ("%s\n", fail ? "FAIL" : "OK");
575 if (fail && test_mode_fatal)
578 case G_TEST_LOG_MIN_RESULT:
579 if (g_test_verbose())
580 g_print ("(MINPERF:%s)\n", string1);
582 case G_TEST_LOG_MAX_RESULT:
583 if (g_test_verbose())
584 g_print ("(MAXPERF:%s)\n", string1);
586 case G_TEST_LOG_MESSAGE:
587 if (g_test_verbose())
588 g_print ("(MSG: %s)\n", string1);
594 msg.n_strings = (string1 != NULL) + (string1 && string2);
595 msg.strings = astrings;
596 astrings[0] = (gchar*) string1;
597 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
600 dbuffer = g_test_log_dump (&msg, &dbufferlen);
601 g_test_log_send (dbufferlen, dbuffer);
606 case G_TEST_LOG_START_CASE:
607 if (g_test_verbose())
608 g_print ("GTest: run: %s\n", string1);
609 else if (!g_test_quiet())
610 g_print ("%s: ", string1);
616 /* We intentionally parse the command line without GOptionContext
617 * because otherwise you would never be able to test it.
620 parse_args (gint *argc_p,
623 guint argc = *argc_p;
624 gchar **argv = *argv_p;
626 /* parse known args */
627 for (i = 1; i < argc; i++)
629 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
631 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
632 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
633 g_log_set_always_fatal (fatal_mask);
636 else if (strcmp (argv[i], "--keep-going") == 0 ||
637 strcmp (argv[i], "-k") == 0)
639 test_mode_fatal = FALSE;
642 else if (strcmp (argv[i], "--debug-log") == 0)
644 test_debug_log = TRUE;
647 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
649 gchar *equal = argv[i] + 12;
651 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
652 else if (i + 1 < argc)
655 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
659 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
661 gchar *equal = argv[i] + 16;
663 test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
664 else if (i + 1 < argc)
667 test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
671 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
673 gchar *equal = argv[i] + 2;
675 test_paths = g_slist_prepend (test_paths, equal + 1);
676 else if (i + 1 < argc)
679 test_paths = g_slist_prepend (test_paths, argv[i]);
683 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
685 gchar *equal = argv[i] + 2;
686 const gchar *mode = "";
689 else if (i + 1 < argc)
694 if (strcmp (mode, "perf") == 0)
695 mutable_test_config_vars.test_perf = TRUE;
696 else if (strcmp (mode, "slow") == 0)
697 mutable_test_config_vars.test_quick = FALSE;
698 else if (strcmp (mode, "thorough") == 0)
699 mutable_test_config_vars.test_quick = FALSE;
700 else if (strcmp (mode, "quick") == 0)
702 mutable_test_config_vars.test_quick = TRUE;
703 mutable_test_config_vars.test_perf = FALSE;
706 g_error ("unknown test mode: -m %s", mode);
709 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
711 mutable_test_config_vars.test_quiet = TRUE;
712 mutable_test_config_vars.test_verbose = FALSE;
715 else if (strcmp ("--verbose", argv[i]) == 0)
717 mutable_test_config_vars.test_quiet = FALSE;
718 mutable_test_config_vars.test_verbose = TRUE;
721 else if (strcmp ("-l", argv[i]) == 0)
723 test_run_list = TRUE;
726 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
728 gchar *equal = argv[i] + 6;
730 test_run_seedstr = equal + 1;
731 else if (i + 1 < argc)
734 test_run_seedstr = argv[i];
738 else if (strcmp ("-?", argv[i]) == 0 || strcmp ("--help", argv[i]) == 0)
741 " %s [OPTION...]\n\n"
743 " -?, --help Show help options\n"
745 " -l List test cases available in a test executable\n"
746 " -seed=RANDOMSEED Provide a random seed to reproduce test\n"
747 " runs using random numbers\n"
748 " --verbose Run tests verbosely\n"
749 " -q, --quiet Run tests quietly\n"
750 " -p TESTPATH execute all tests matching TESTPATH\n"
751 " -m {perf|slow|thorough|quick} Execute tests according modes\n"
752 " --debug-log debug test logging output\n"
753 " -k, --keep-going gtester-specific argument\n"
754 " --GTestLogFD=N gtester-specific argument\n"
755 " --GTestSkipCount=N gtester-specific argument\n",
762 for (i = 1; i < argc; i++)
774 * @argc: Address of the @argc parameter of the main() function.
775 * Changed if any arguments were handled.
776 * @argv: Address of the @argv parameter of main().
777 * Any parameters understood by g_test_init() stripped before return.
778 * @...: Reserved for future extension. Currently, you must pass %NULL.
780 * Initialize the GLib testing framework, e.g. by seeding the
781 * test random number generator, the name for g_get_prgname()
782 * and parsing test related command line args.
783 * So far, the following arguments are understood:
786 * <term><option>-l</option></term>
788 * list test cases available in a test executable.
792 * <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
794 * provide a random seed to reproduce test runs using random numbers.
798 * <term><option>--verbose</option></term>
799 * <listitem><para>run tests verbosely.</para></listitem>
802 * <term><option>-q</option>, <option>--quiet</option></term>
803 * <listitem><para>run tests quietly.</para></listitem>
806 * <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
808 * execute all tests matching <replaceable>TESTPATH</replaceable>.
812 * <term><option>-m {perf|slow|thorough|quick}</option></term>
814 * execute tests according to these test modes:
819 * performance tests, may take long and report results.
823 * <term>slow, thorough</term>
825 * slow and thorough tests, may take quite long and
832 * quick tests, should run really quickly and give good coverage.
839 * <term><option>--debug-log</option></term>
840 * <listitem><para>debug test logging output.</para></listitem>
843 * <term><option>-k</option>, <option>--keep-going</option></term>
844 * <listitem><para>gtester-specific argument.</para></listitem>
847 * <term><option>--GTestLogFD <replaceable>N</replaceable></option></term>
848 * <listitem><para>gtester-specific argument.</para></listitem>
851 * <term><option>--GTestSkipCount <replaceable>N</replaceable></option></term>
852 * <listitem><para>gtester-specific argument.</para></listitem>
859 g_test_init (int *argc,
863 static char seedstr[4 + 4 * 8 + 1];
866 /* make warnings and criticals fatal for all test programs */
867 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
868 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
869 g_log_set_always_fatal (fatal_mask);
870 /* check caller args */
871 g_return_if_fail (argc != NULL);
872 g_return_if_fail (argv != NULL);
873 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
874 mutable_test_config_vars.test_initialized = TRUE;
876 va_start (args, argv);
877 vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
879 g_return_if_fail (vararg1 == NULL);
881 /* setup random seed string */
882 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
883 test_run_seedstr = seedstr;
885 /* parse args, sets up mode, changes seed, etc. */
886 parse_args (argc, argv);
887 if (!g_get_prgname())
888 g_set_prgname ((*argv)[0]);
890 /* verify GRand reliability, needed for reliable seeds */
893 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
894 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
895 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
896 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
897 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
901 /* check rand seed */
902 test_run_seed (test_run_seedstr);
904 /* report program start */
905 g_log_set_default_handler (gtest_default_log_handler, NULL);
906 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
910 test_run_seed (const gchar *rseed)
912 guint seed_failed = 0;
914 g_rand_free (test_run_rand);
915 test_run_rand = NULL;
916 while (strchr (" \t\v\r\n\f", *rseed))
918 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
920 const char *s = rseed + 4;
921 if (strlen (s) >= 32) /* require 4 * 8 chars */
923 guint32 seedarray[4];
924 gchar *p, hexbuf[9] = { 0, };
925 memcpy (hexbuf, s + 0, 8);
926 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
927 seed_failed += p != NULL && *p != 0;
928 memcpy (hexbuf, s + 8, 8);
929 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
930 seed_failed += p != NULL && *p != 0;
931 memcpy (hexbuf, s + 16, 8);
932 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
933 seed_failed += p != NULL && *p != 0;
934 memcpy (hexbuf, s + 24, 8);
935 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
936 seed_failed += p != NULL && *p != 0;
939 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
944 g_error ("Unknown or invalid random seed: %s", rseed);
950 * Get a reproducible random integer number.
952 * The random numbers generated by the g_test_rand_*() family of functions
953 * change with every new test program start, unless the --seed option is
954 * given when starting test programs.
956 * For individual test cases however, the random number generator is
957 * reseeded, to avoid dependencies between tests and to make --seed
958 * effective for all test cases.
960 * Returns: a random number from the seeded random number generator.
965 g_test_rand_int (void)
967 return g_rand_int (test_run_rand);
971 * g_test_rand_int_range:
972 * @begin: the minimum value returned by this function
973 * @end: the smallest value not to be returned by this function
975 * Get a reproducible random integer number out of a specified range,
976 * see g_test_rand_int() for details on test case random numbers.
978 * Returns: a number with @begin <= number < @end.
983 g_test_rand_int_range (gint32 begin,
986 return g_rand_int_range (test_run_rand, begin, end);
990 * g_test_rand_double:
992 * Get a reproducible random floating point number,
993 * see g_test_rand_int() for details on test case random numbers.
995 * Returns: a random number from the seeded random number generator.
1000 g_test_rand_double (void)
1002 return g_rand_double (test_run_rand);
1006 * g_test_rand_double_range:
1007 * @range_start: the minimum value returned by this function
1008 * @range_end: the minimum value not returned by this function
1010 * Get a reproducible random floating pointer number out of a specified range,
1011 * see g_test_rand_int() for details on test case random numbers.
1013 * Returns: a number with @range_start <= number < @range_end.
1018 g_test_rand_double_range (double range_start,
1021 return g_rand_double_range (test_run_rand, range_start, range_end);
1025 * g_test_timer_start:
1027 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1028 * to be done. Call this function again to restart the timer.
1033 g_test_timer_start (void)
1035 if (!test_user_timer)
1036 test_user_timer = g_timer_new();
1037 test_user_stamp = 0;
1038 g_timer_start (test_user_timer);
1042 * g_test_timer_elapsed:
1044 * Get the time since the last start of the timer with g_test_timer_start().
1046 * Returns: the time since the last start of the timer, as a double
1051 g_test_timer_elapsed (void)
1053 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1054 return test_user_stamp;
1058 * g_test_timer_last:
1060 * Report the last result of g_test_timer_elapsed().
1062 * Returns: the last result of g_test_timer_elapsed(), as a double
1067 g_test_timer_last (void)
1069 return test_user_stamp;
1073 * g_test_minimized_result:
1074 * @minimized_quantity: the reported value
1075 * @format: the format string of the report message
1076 * @...: arguments to pass to the printf() function
1078 * Report the result of a performance or measurement test.
1079 * The test should generally strive to minimize the reported
1080 * quantities (smaller values are better than larger ones),
1081 * this and @minimized_quantity can determine sorting
1082 * order for test result reports.
1087 g_test_minimized_result (double minimized_quantity,
1091 long double largs = minimized_quantity;
1095 va_start (args, format);
1096 buffer = g_strdup_vprintf (format, args);
1099 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1104 * g_test_maximized_result:
1105 * @maximized_quantity: the reported value
1106 * @format: the format string of the report message
1107 * @...: arguments to pass to the printf() function
1109 * Report the result of a performance or measurement test.
1110 * The test should generally strive to maximize the reported
1111 * quantities (larger values are better than smaller ones),
1112 * this and @maximized_quantity can determine sorting
1113 * order for test result reports.
1118 g_test_maximized_result (double maximized_quantity,
1122 long double largs = maximized_quantity;
1126 va_start (args, format);
1127 buffer = g_strdup_vprintf (format, args);
1130 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1136 * @format: the format string
1137 * @...: printf-like arguments to @format
1139 * Add a message to the test report.
1144 g_test_message (const char *format,
1150 va_start (args, format);
1151 buffer = g_strdup_vprintf (format, args);
1154 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1160 * @uri_pattern: the base pattern for bug URIs
1162 * Specify the base URI for bug reports.
1164 * The base URI is used to construct bug report messages for
1165 * g_test_message() when g_test_bug() is called.
1166 * Calling this function outside of a test case sets the
1167 * default base URI for all test cases. Calling it from within
1168 * a test case changes the base URI for the scope of the test
1170 * Bug URIs are constructed by appending a bug specific URI
1171 * portion to @uri_pattern, or by replacing the special string
1172 * '\%s' within @uri_pattern if that is present.
1177 g_test_bug_base (const char *uri_pattern)
1179 g_free (test_uri_base);
1180 test_uri_base = g_strdup (uri_pattern);
1185 * @bug_uri_snippet: Bug specific bug tracker URI portion.
1187 * This function adds a message to test reports that
1188 * associates a bug URI with a test case.
1189 * Bug URIs are constructed from a base URI set with g_test_bug_base()
1190 * and @bug_uri_snippet.
1195 g_test_bug (const char *bug_uri_snippet)
1199 g_return_if_fail (test_uri_base != NULL);
1200 g_return_if_fail (bug_uri_snippet != NULL);
1202 c = strstr (test_uri_base, "%s");
1205 char *b = g_strndup (test_uri_base, c - test_uri_base);
1206 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1208 g_test_message ("Bug Reference: %s", s);
1212 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1218 * Get the toplevel test suite for the test path API.
1220 * Returns: the toplevel #GTestSuite
1225 g_test_get_root (void)
1227 if (!test_suite_root)
1229 test_suite_root = g_test_create_suite ("root");
1230 g_free (test_suite_root->name);
1231 test_suite_root->name = g_strdup ("");
1234 return test_suite_root;
1240 * Runs all tests under the toplevel suite which can be retrieved
1241 * with g_test_get_root(). Similar to g_test_run_suite(), the test
1242 * cases to be run are filtered according to
1243 * test path arguments (-p <replaceable>testpath</replaceable>) as
1244 * parsed by g_test_init().
1245 * g_test_run_suite() or g_test_run() may only be called once
1248 * Returns: 0 on success
1255 return g_test_run_suite (g_test_get_root());
1259 * g_test_create_case:
1260 * @test_name: the name for the test case
1261 * @data_size: the size of the fixture data structure
1262 * @test_data: test data argument for the test functions
1263 * @data_setup: the function to set up the fixture data
1264 * @data_test: the actual test function
1265 * @data_teardown: the function to teardown the fixture data
1267 * Create a new #GTestCase, named @test_name, this API is fairly
1268 * low level, calling g_test_add() or g_test_add_func() is preferable.
1269 * When this test is executed, a fixture structure of size @data_size
1270 * will be allocated and filled with 0s. Then data_setup() is called
1271 * to initialize the fixture. After fixture setup, the actual test
1272 * function data_test() is called. Once the test run completed, the
1273 * fixture structure is torn down by calling data_teardown() and
1274 * after that the memory is released.
1276 * Splitting up a test run into fixture setup, test function and
1277 * fixture teardown is most usful if the same fixture is used for
1278 * multiple tests. In this cases, g_test_create_case() will be
1279 * called with the same fixture, but varying @test_name and
1280 * @data_test arguments.
1282 * Returns: a newly allocated #GTestCase.
1287 g_test_create_case (const char *test_name,
1289 gconstpointer test_data,
1290 GTestFixtureFunc data_setup,
1291 GTestFixtureFunc data_test,
1292 GTestFixtureFunc data_teardown)
1296 g_return_val_if_fail (test_name != NULL, NULL);
1297 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1298 g_return_val_if_fail (test_name[0] != 0, NULL);
1299 g_return_val_if_fail (data_test != NULL, NULL);
1301 tc = g_slice_new0 (GTestCase);
1302 tc->name = g_strdup (test_name);
1303 tc->test_data = (gpointer) test_data;
1304 tc->fixture_size = data_size;
1305 tc->fixture_setup = (void*) data_setup;
1306 tc->fixture_test = (void*) data_test;
1307 tc->fixture_teardown = (void*) data_teardown;
1314 * @fixture: the test fixture
1315 * @user_data: the data provided when registering the test
1317 * The type used for functions that operate on test fixtures. This is
1318 * used for the fixture setup and teardown functions as well as for the
1319 * testcases themselves.
1321 * @user_data is a pointer to the data that was given when registering
1324 * @fixture will be a pointer to the area of memory allocated by the
1325 * test framework, of the size requested. If the requested size was
1326 * zero then @fixture will be equal to @user_data.
1331 g_test_add_vtable (const char *testpath,
1333 gconstpointer test_data,
1334 GTestFixtureFunc data_setup,
1335 GTestFixtureFunc fixture_test_func,
1336 GTestFixtureFunc data_teardown)
1342 g_return_if_fail (testpath != NULL);
1343 g_return_if_fail (testpath[0] == '/');
1344 g_return_if_fail (fixture_test_func != NULL);
1346 suite = g_test_get_root();
1347 segments = g_strsplit (testpath, "/", -1);
1348 for (ui = 0; segments[ui] != NULL; ui++)
1350 const char *seg = segments[ui];
1351 gboolean islast = segments[ui + 1] == NULL;
1352 if (islast && !seg[0])
1353 g_error ("invalid test case path: %s", testpath);
1355 continue; /* initial or duplicate slash */
1358 GTestSuite *csuite = g_test_create_suite (seg);
1359 g_test_suite_add_suite (suite, csuite);
1364 GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1365 g_test_suite_add (suite, tc);
1368 g_strfreev (segments);
1374 * Indicates that a test failed. This function can be called
1375 * multiple times from the same test. You can use this function
1376 * if your test failed in a recoverable way.
1378 * Do not use this function if the failure of a test could cause
1379 * other tests to malfunction.
1381 * Calling this function will not stop the test from running, you
1382 * need to return from the test function yourself. So you can
1383 * produce additional diagnostic messages or even continue running
1386 * If not called from inside a test, this function does nothing.
1393 test_run_success = FALSE;
1399 * The type used for test case functions.
1406 * @testpath: Slash-separated test case path name for the test.
1407 * @test_func: The test function to invoke for this test.
1409 * Create a new test case, similar to g_test_create_case(). However
1410 * the test is assumed to use no fixture, and test suites are automatically
1411 * created on the fly and added to the root fixture, based on the
1412 * slash-separated portions of @testpath.
1417 g_test_add_func (const char *testpath,
1418 GTestFunc test_func)
1420 g_return_if_fail (testpath != NULL);
1421 g_return_if_fail (testpath[0] == '/');
1422 g_return_if_fail (test_func != NULL);
1423 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1428 * @user_data: the data provided when registering the test
1430 * The type used for test case functions that take an extra pointer
1437 * g_test_add_data_func:
1438 * @testpath: Slash-separated test case path name for the test.
1439 * @test_data: Test data argument for the test function.
1440 * @test_func: The test function to invoke for this test.
1442 * Create a new test case, similar to g_test_create_case(). However
1443 * the test is assumed to use no fixture, and test suites are automatically
1444 * created on the fly and added to the root fixture, based on the
1445 * slash-separated portions of @testpath. The @test_data argument
1446 * will be passed as first argument to @test_func.
1451 g_test_add_data_func (const char *testpath,
1452 gconstpointer test_data,
1453 GTestDataFunc test_func)
1455 g_return_if_fail (testpath != NULL);
1456 g_return_if_fail (testpath[0] == '/');
1457 g_return_if_fail (test_func != NULL);
1458 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1462 * g_test_create_suite:
1463 * @suite_name: a name for the suite
1465 * Create a new test suite with the name @suite_name.
1467 * Returns: A newly allocated #GTestSuite instance.
1472 g_test_create_suite (const char *suite_name)
1475 g_return_val_if_fail (suite_name != NULL, NULL);
1476 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1477 g_return_val_if_fail (suite_name[0] != 0, NULL);
1478 ts = g_slice_new0 (GTestSuite);
1479 ts->name = g_strdup (suite_name);
1485 * @suite: a #GTestSuite
1486 * @test_case: a #GTestCase
1488 * Adds @test_case to @suite.
1493 g_test_suite_add (GTestSuite *suite,
1494 GTestCase *test_case)
1496 g_return_if_fail (suite != NULL);
1497 g_return_if_fail (test_case != NULL);
1499 suite->cases = g_slist_prepend (suite->cases, test_case);
1503 * g_test_suite_add_suite:
1504 * @suite: a #GTestSuite
1505 * @nestedsuite: another #GTestSuite
1507 * Adds @nestedsuite to @suite.
1512 g_test_suite_add_suite (GTestSuite *suite,
1513 GTestSuite *nestedsuite)
1515 g_return_if_fail (suite != NULL);
1516 g_return_if_fail (nestedsuite != NULL);
1518 suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1522 * g_test_queue_free:
1523 * @gfree_pointer: the pointer to be stored.
1525 * Enqueue a pointer to be released with g_free() during the next
1526 * teardown phase. This is equivalent to calling g_test_queue_destroy()
1527 * with a destroy callback of g_free().
1532 g_test_queue_free (gpointer gfree_pointer)
1535 g_test_queue_destroy (g_free, gfree_pointer);
1539 * g_test_queue_destroy:
1540 * @destroy_func: Destroy callback for teardown phase.
1541 * @destroy_data: Destroy callback data.
1543 * This function enqueus a callback @destroy_func() to be executed
1544 * during the next test case teardown phase. This is most useful
1545 * to auto destruct allocted test resources at the end of a test run.
1546 * Resources are released in reverse queue order, that means enqueueing
1547 * callback A before callback B will cause B() to be called before
1548 * A() during teardown.
1553 g_test_queue_destroy (GDestroyNotify destroy_func,
1554 gpointer destroy_data)
1556 DestroyEntry *dentry;
1558 g_return_if_fail (destroy_func != NULL);
1560 dentry = g_slice_new0 (DestroyEntry);
1561 dentry->destroy_func = destroy_func;
1562 dentry->destroy_data = destroy_data;
1563 dentry->next = test_destroy_queue;
1564 test_destroy_queue = dentry;
1568 test_case_run (GTestCase *tc)
1570 gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1571 gboolean success = TRUE;
1573 test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1574 if (++test_run_count <= test_skip_count)
1575 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1576 else if (test_run_list)
1578 g_print ("%s\n", test_run_name);
1579 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1583 GTimer *test_run_timer = g_timer_new();
1584 long double largs[3];
1586 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1588 test_run_success = TRUE;
1589 g_test_log_set_fatal_handler (NULL, NULL);
1590 g_timer_start (test_run_timer);
1591 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1592 test_run_seed (test_run_seedstr);
1593 if (tc->fixture_setup)
1594 tc->fixture_setup (fixture, tc->test_data);
1595 tc->fixture_test (fixture, tc->test_data);
1597 while (test_destroy_queue)
1599 DestroyEntry *dentry = test_destroy_queue;
1600 test_destroy_queue = dentry->next;
1601 dentry->destroy_func (dentry->destroy_data);
1602 g_slice_free (DestroyEntry, dentry);
1604 if (tc->fixture_teardown)
1605 tc->fixture_teardown (fixture, tc->test_data);
1606 if (tc->fixture_size)
1608 g_timer_stop (test_run_timer);
1609 success = test_run_success;
1610 test_run_success = FALSE;
1611 largs[0] = success ? 0 : 1; /* OK */
1612 largs[1] = test_run_forks;
1613 largs[2] = g_timer_elapsed (test_run_timer, NULL);
1614 g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1615 g_timer_destroy (test_run_timer);
1617 g_free (test_run_name);
1618 test_run_name = old_name;
1619 g_free (test_uri_base);
1620 test_uri_base = old_base;
1626 g_test_run_suite_internal (GTestSuite *suite,
1630 gchar *rest, *old_name = test_run_name;
1631 GSList *slist, *reversed;
1633 g_return_val_if_fail (suite != NULL, -1);
1635 while (path[0] == '/')
1638 rest = strchr (path, '/');
1639 l = rest ? MIN (l, rest - path) : l;
1640 test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1641 reversed = g_slist_reverse (g_slist_copy (suite->cases));
1642 for (slist = reversed; slist; slist = slist->next)
1644 GTestCase *tc = slist->data;
1645 guint n = l ? strlen (tc->name) : 0;
1646 if (l == n && strncmp (path, tc->name, n) == 0)
1648 if (!test_case_run (tc))
1652 g_slist_free (reversed);
1653 reversed = g_slist_reverse (g_slist_copy (suite->suites));
1654 for (slist = reversed; slist; slist = slist->next)
1656 GTestSuite *ts = slist->data;
1657 guint n = l ? strlen (ts->name) : 0;
1658 if (l == n && strncmp (path, ts->name, n) == 0)
1659 n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
1661 g_slist_free (reversed);
1662 g_free (test_run_name);
1663 test_run_name = old_name;
1670 * @suite: a #GTestSuite
1672 * Execute the tests within @suite and all nested #GTestSuites.
1673 * The test suites to be executed are filtered according to
1674 * test path arguments (-p <replaceable>testpath</replaceable>)
1675 * as parsed by g_test_init().
1676 * g_test_run_suite() or g_test_run() may only be called once
1679 * Returns: 0 on success
1684 g_test_run_suite (GTestSuite *suite)
1688 g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1689 g_return_val_if_fail (g_test_run_once == TRUE, -1);
1691 g_test_run_once = FALSE;
1694 test_paths = g_slist_prepend (test_paths, "");
1697 const char *rest, *path = test_paths->data;
1698 guint l, n = strlen (suite->name);
1699 test_paths = g_slist_delete_link (test_paths, test_paths);
1700 while (path[0] == '/')
1702 if (!n) /* root suite, run unconditionally */
1704 n_bad += g_test_run_suite_internal (suite, path);
1707 /* regular suite, match path */
1708 rest = strchr (path, '/');
1710 l = rest ? MIN (l, rest - path) : l;
1711 if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1712 n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
1719 gtest_default_log_handler (const gchar *log_domain,
1720 GLogLevelFlags log_level,
1721 const gchar *message,
1722 gpointer unused_data)
1724 const gchar *strv[16];
1725 gboolean fatal = FALSE;
1731 strv[i++] = log_domain;
1734 if (log_level & G_LOG_FLAG_FATAL)
1736 strv[i++] = "FATAL-";
1739 if (log_level & G_LOG_FLAG_RECURSION)
1740 strv[i++] = "RECURSIVE-";
1741 if (log_level & G_LOG_LEVEL_ERROR)
1742 strv[i++] = "ERROR";
1743 if (log_level & G_LOG_LEVEL_CRITICAL)
1744 strv[i++] = "CRITICAL";
1745 if (log_level & G_LOG_LEVEL_WARNING)
1746 strv[i++] = "WARNING";
1747 if (log_level & G_LOG_LEVEL_MESSAGE)
1748 strv[i++] = "MESSAGE";
1749 if (log_level & G_LOG_LEVEL_INFO)
1751 if (log_level & G_LOG_LEVEL_DEBUG)
1752 strv[i++] = "DEBUG";
1754 strv[i++] = message;
1757 msg = g_strjoinv ("", (gchar**) strv);
1758 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
1759 g_log_default_handler (log_domain, log_level, message, unused_data);
1765 g_assertion_message (const char *domain,
1769 const char *message)
1775 message = "code should not be reached";
1776 g_snprintf (lstr, 32, "%d", line);
1777 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1778 "ERROR:", file, ":", lstr, ":",
1779 func, func[0] ? ":" : "",
1780 " ", message, NULL);
1781 g_printerr ("**\n%s\n", s);
1783 /* store assertion message in global variable, so that it can be found in a
1785 if (__glib_assert_msg != NULL)
1786 /* free the old one */
1787 free (__glib_assert_msg);
1788 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
1789 strcpy (__glib_assert_msg, s);
1791 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
1797 g_assertion_message_expr (const char *domain,
1803 char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1804 g_assertion_message (domain, file, line, func, s);
1809 g_assertion_message_cmpnum (const char *domain,
1822 case 'i': s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
1823 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;
1824 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
1825 /* ideally use: floats=%.7g double=%.17g */
1827 g_assertion_message (domain, file, line, func, s);
1832 g_assertion_message_cmpstr (const char *domain,
1841 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1842 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1843 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1846 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1849 g_assertion_message (domain, file, line, func, s);
1854 g_assertion_message_error (const char *domain,
1859 const GError *error,
1860 GQuark error_domain,
1865 /* This is used by both g_assert_error() and g_assert_no_error(), so there
1866 * are three cases: expected an error but got the wrong error, expected
1867 * an error but got no error, and expected no error but got an error.
1870 gstring = g_string_new ("assertion failed ");
1872 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
1873 g_quark_to_string (error_domain), error_code);
1875 g_string_append_printf (gstring, "(%s == NULL): ", expr);
1878 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
1879 g_quark_to_string (error->domain), error->code);
1881 g_string_append_printf (gstring, "%s is NULL", expr);
1883 g_assertion_message (domain, file, line, func, gstring->str);
1884 g_string_free (gstring, TRUE);
1889 * @str1: a C string or %NULL
1890 * @str2: another C string or %NULL
1892 * Compares @str1 and @str2 like strcmp(). Handles %NULL
1893 * gracefully by sorting it before non-%NULL strings.
1894 * Comparing two %NULL pointers returns 0.
1896 * Returns: -1, 0 or 1, if @str1 is <, == or > than @str2.
1901 g_strcmp0 (const char *str1,
1905 return -(str1 != str2);
1907 return str1 != str2;
1908 return strcmp (str1, str2);
1912 static int /* 0 on success */
1913 kill_child (int pid,
1918 if (patience >= 3) /* try graceful reap */
1920 if (waitpid (pid, status, WNOHANG) > 0)
1923 if (patience >= 2) /* try SIGHUP */
1926 if (waitpid (pid, status, WNOHANG) > 0)
1928 g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1929 if (waitpid (pid, status, WNOHANG) > 0)
1931 g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
1932 if (waitpid (pid, status, WNOHANG) > 0)
1934 g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
1935 if (waitpid (pid, status, WNOHANG) > 0)
1938 if (patience >= 1) /* try SIGTERM */
1940 kill (pid, SIGTERM);
1941 if (waitpid (pid, status, WNOHANG) > 0)
1943 g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
1944 if (waitpid (pid, status, WNOHANG) > 0)
1946 g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
1947 if (waitpid (pid, status, WNOHANG) > 0)
1951 kill (pid, SIGKILL);
1953 wr = waitpid (pid, status, 0);
1954 while (wr < 0 && errno == EINTR);
1960 g_string_must_read (GString *gstring,
1963 #define STRING_BUFFER_SIZE 4096
1964 char buf[STRING_BUFFER_SIZE];
1967 bytes = read (fd, buf, sizeof (buf));
1969 return 0; /* EOF, calling this function assumes data is available */
1972 g_string_append_len (gstring, buf, bytes);
1975 else if (bytes < 0 && errno == EINTR)
1977 else /* bytes < 0 */
1979 g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1980 return 1; /* ignore error after warning */
1985 g_string_write_out (GString *gstring,
1989 if (*stringpos < gstring->len)
1993 r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
1994 while (r < 0 && errno == EINTR);
1995 *stringpos += MAX (r, 0);
2000 test_trap_clear (void)
2002 test_trap_last_status = 0;
2003 test_trap_last_pid = 0;
2004 g_free (test_trap_last_stdout);
2005 test_trap_last_stdout = NULL;
2006 g_free (test_trap_last_stderr);
2007 test_trap_last_stderr = NULL;
2018 ret = dup2 (fd1, fd2);
2019 while (ret < 0 && errno == EINTR);
2024 test_time_stamp (void)
2028 g_get_current_time (&tv);
2030 stamp = stamp * 1000000 + tv.tv_usec;
2038 * @usec_timeout: Timeout for the forked test in micro seconds.
2039 * @test_trap_flags: Flags to modify forking behaviour.
2041 * Fork the current test program to execute a test case that might
2042 * not return or that might abort. The forked test case is aborted
2043 * and considered failing if its run time exceeds @usec_timeout.
2045 * The forking behavior can be configured with the #GTestTrapFlags flags.
2047 * In the following example, the test code forks, the forked child
2048 * process produces some sample output and exits successfully.
2049 * The forking parent process then asserts successful child program
2050 * termination and validates child program outputs.
2054 * test_fork_patterns (void)
2056 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2058 * g_print ("some stdout text: somagic17\n");
2059 * g_printerr ("some stderr text: semagic43\n");
2060 * exit (0); /* successful test run */
2062 * g_test_trap_assert_passed();
2063 * g_test_trap_assert_stdout ("*somagic17*");
2064 * g_test_trap_assert_stderr ("*semagic43*");
2068 * This function is implemented only on Unix platforms.
2070 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2075 g_test_trap_fork (guint64 usec_timeout,
2076 GTestTrapFlags test_trap_flags)
2079 gboolean pass_on_forked_log = FALSE;
2080 int stdout_pipe[2] = { -1, -1 };
2081 int stderr_pipe[2] = { -1, -1 };
2082 int stdtst_pipe[2] = { -1, -1 };
2084 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
2085 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
2086 signal (SIGCHLD, SIG_DFL);
2087 test_trap_last_pid = fork ();
2088 if (test_trap_last_pid < 0)
2089 g_error ("failed to fork test program: %s", g_strerror (errno));
2090 if (test_trap_last_pid == 0) /* child */
2093 close (stdout_pipe[0]);
2094 close (stderr_pipe[0]);
2095 close (stdtst_pipe[0]);
2096 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2097 fd0 = open ("/dev/null", O_RDONLY);
2098 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2099 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
2102 if (stdout_pipe[1] >= 3)
2103 close (stdout_pipe[1]);
2104 if (stderr_pipe[1] >= 3)
2105 close (stderr_pipe[1]);
2106 test_log_fd = stdtst_pipe[1];
2111 GString *sout = g_string_new (NULL);
2112 GString *serr = g_string_new (NULL);
2114 int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
2116 close (stdout_pipe[1]);
2117 close (stderr_pipe[1]);
2118 close (stdtst_pipe[1]);
2119 sstamp = test_time_stamp();
2120 /* read data until we get EOF on all pipes */
2121 while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
2127 if (stdout_pipe[0] >= 0)
2128 FD_SET (stdout_pipe[0], &fds);
2129 if (stderr_pipe[0] >= 0)
2130 FD_SET (stderr_pipe[0], &fds);
2131 if (stdtst_pipe[0] >= 0)
2132 FD_SET (stdtst_pipe[0], &fds);
2134 tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
2135 ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
2136 if (ret < 0 && errno != EINTR)
2138 g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2141 if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
2142 g_string_must_read (sout, stdout_pipe[0]) == 0)
2144 close (stdout_pipe[0]);
2145 stdout_pipe[0] = -1;
2147 if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
2148 g_string_must_read (serr, stderr_pipe[0]) == 0)
2150 close (stderr_pipe[0]);
2151 stderr_pipe[0] = -1;
2153 if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
2155 guint8 buffer[4096];
2156 gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
2157 if (r > 0 && test_log_fd > 0)
2159 l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
2160 while (l < 0 && errno == EINTR);
2161 if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
2163 close (stdtst_pipe[0]);
2164 stdtst_pipe[0] = -1;
2167 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
2168 g_string_write_out (sout, 1, &soutpos);
2169 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
2170 g_string_write_out (serr, 2, &serrpos);
2173 guint64 nstamp = test_time_stamp();
2175 sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
2176 if (usec_timeout < nstamp - sstamp)
2178 /* timeout reached, need to abort the child now */
2179 kill_child (test_trap_last_pid, &status, 3);
2180 test_trap_last_status = 1024; /* timeout */
2181 if (0 && WIFSIGNALED (status))
2182 g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
2188 if (stdout_pipe[0] != -1)
2189 close (stdout_pipe[0]);
2190 if (stderr_pipe[0] != -1)
2191 close (stderr_pipe[0]);
2192 if (stdtst_pipe[0] != -1)
2193 close (stdtst_pipe[0]);
2198 wr = waitpid (test_trap_last_pid, &status, 0);
2199 while (wr < 0 && errno == EINTR);
2200 if (WIFEXITED (status)) /* normal exit */
2201 test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
2202 else if (WIFSIGNALED (status))
2203 test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
2204 else /* WCOREDUMP (status) */
2205 test_trap_last_status = 512; /* coredump */
2207 test_trap_last_stdout = g_string_free (sout, FALSE);
2208 test_trap_last_stderr = g_string_free (serr, FALSE);
2212 g_message ("Not implemented: g_test_trap_fork");
2219 * g_test_trap_has_passed:
2221 * Check the result of the last g_test_trap_fork() call.
2223 * Returns: %TRUE if the last forked child terminated successfully.
2228 g_test_trap_has_passed (void)
2230 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
2234 * g_test_trap_reached_timeout:
2236 * Check the result of the last g_test_trap_fork() call.
2238 * Returns: %TRUE if the last forked child got killed due to a fork timeout.
2243 g_test_trap_reached_timeout (void)
2245 return 0 != (test_trap_last_status & 1024); /* timeout flag */
2249 g_test_trap_assertions (const char *domain,
2253 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
2254 const char *pattern)
2257 gboolean must_pass = assertion_flags == 0;
2258 gboolean must_fail = assertion_flags == 1;
2259 gboolean match_result = 0 == (assertion_flags & 1);
2260 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
2261 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
2262 const char *match_error = match_result ? "failed to match" : "contains invalid match";
2263 if (test_trap_last_pid == 0)
2264 g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
2265 if (must_pass && !g_test_trap_has_passed())
2267 char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
2268 g_assertion_message (domain, file, line, func, msg);
2271 if (must_fail && g_test_trap_has_passed())
2273 char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
2274 g_assertion_message (domain, file, line, func, msg);
2277 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
2279 char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
2280 g_assertion_message (domain, file, line, func, msg);
2283 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
2285 char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
2286 g_assertion_message (domain, file, line, func, msg);
2293 gstring_overwrite_int (GString *gstring,
2297 vuint = g_htonl (vuint);
2298 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
2302 gstring_append_int (GString *gstring,
2305 vuint = g_htonl (vuint);
2306 g_string_append_len (gstring, (const gchar*) &vuint, 4);
2310 gstring_append_double (GString *gstring,
2313 union { double vdouble; guint64 vuint64; } u;
2314 u.vdouble = vdouble;
2315 u.vuint64 = GUINT64_TO_BE (u.vuint64);
2316 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
2320 g_test_log_dump (GTestLogMsg *msg,
2323 GString *gstring = g_string_sized_new (1024);
2325 gstring_append_int (gstring, 0); /* message length */
2326 gstring_append_int (gstring, msg->log_type);
2327 gstring_append_int (gstring, msg->n_strings);
2328 gstring_append_int (gstring, msg->n_nums);
2329 gstring_append_int (gstring, 0); /* reserved */
2330 for (ui = 0; ui < msg->n_strings; ui++)
2332 guint l = strlen (msg->strings[ui]);
2333 gstring_append_int (gstring, l);
2334 g_string_append_len (gstring, msg->strings[ui], l);
2336 for (ui = 0; ui < msg->n_nums; ui++)
2337 gstring_append_double (gstring, msg->nums[ui]);
2338 *len = gstring->len;
2339 gstring_overwrite_int (gstring, 0, *len); /* message length */
2340 return (guint8*) g_string_free (gstring, FALSE);
2343 static inline long double
2344 net_double (const gchar **ipointer)
2346 union { guint64 vuint64; double vdouble; } u;
2347 guint64 aligned_int64;
2348 memcpy (&aligned_int64, *ipointer, 8);
2350 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
2354 static inline guint32
2355 net_int (const gchar **ipointer)
2357 guint32 aligned_int;
2358 memcpy (&aligned_int, *ipointer, 4);
2360 return g_ntohl (aligned_int);
2364 g_test_log_extract (GTestLogBuffer *tbuffer)
2366 const gchar *p = tbuffer->data->str;
2369 if (tbuffer->data->len < 4 * 5)
2371 mlength = net_int (&p);
2372 if (tbuffer->data->len < mlength)
2374 msg.log_type = net_int (&p);
2375 msg.n_strings = net_int (&p);
2376 msg.n_nums = net_int (&p);
2377 if (net_int (&p) == 0)
2380 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
2381 msg.nums = g_new0 (long double, msg.n_nums);
2382 for (ui = 0; ui < msg.n_strings; ui++)
2384 guint sl = net_int (&p);
2385 msg.strings[ui] = g_strndup (p, sl);
2388 for (ui = 0; ui < msg.n_nums; ui++)
2389 msg.nums[ui] = net_double (&p);
2390 if (p <= tbuffer->data->str + mlength)
2392 g_string_erase (tbuffer->data, 0, mlength);
2393 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
2398 g_strfreev (msg.strings);
2399 g_error ("corrupt log stream from test program");
2404 * g_test_log_buffer_new:
2406 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2409 g_test_log_buffer_new (void)
2411 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
2412 tb->data = g_string_sized_new (1024);
2417 * g_test_log_buffer_free
2419 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2422 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
2424 g_return_if_fail (tbuffer != NULL);
2425 while (tbuffer->msgs)
2426 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
2427 g_string_free (tbuffer->data, TRUE);
2432 * g_test_log_buffer_push
2434 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2437 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
2439 const guint8 *bytes)
2441 g_return_if_fail (tbuffer != NULL);
2444 gboolean more_messages;
2445 g_return_if_fail (bytes != NULL);
2446 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
2448 more_messages = g_test_log_extract (tbuffer);
2449 while (more_messages);
2454 * g_test_log_buffer_pop:
2456 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
2459 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
2461 GTestLogMsg *msg = NULL;
2462 g_return_val_if_fail (tbuffer != NULL, NULL);
2465 GSList *slist = g_slist_last (tbuffer->msgs);
2467 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
2473 * g_test_log_msg_free:
2475 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2478 g_test_log_msg_free (GTestLogMsg *tmsg)
2480 g_return_if_fail (tmsg != NULL);
2481 g_strfreev (tmsg->strings);
2482 g_free (tmsg->nums);
2486 /* --- macros docs START --- */
2489 * @testpath: The test path for a new test case.
2490 * @Fixture: The type of a fixture data structure.
2491 * @tdata: Data argument for the test functions.
2492 * @fsetup: The function to set up the fixture data.
2493 * @ftest: The actual test function.
2494 * @fteardown: The function to tear down the fixture data.
2496 * Hook up a new test case at @testpath, similar to g_test_add_func().
2497 * A fixture data structure with setup and teardown function may be provided
2498 * though, similar to g_test_create_case().
2499 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2500 * fteardown() callbacks can expect a @Fixture pointer as first argument in
2501 * a type safe manner.
2505 /* --- macros docs END --- */