GObject: substantially rework g_object_new()
[glib.git] / glib / gtestutils.c
blob4089758c6a07db00e067c7caa61ade7649b4077b
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.
21 #include "config.h"
23 #include "gtestutils.h"
24 #include "gfileutils.h"
26 #include <sys/types.h>
27 #ifdef G_OS_UNIX
28 #include <sys/wait.h>
29 #include <sys/time.h>
30 #include <fcntl.h>
31 #include <glib/gstdio.h>
32 #endif
33 #include <string.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #ifdef G_OS_WIN32
40 #include <io.h>
41 #endif
42 #include <errno.h>
43 #include <signal.h>
44 #ifdef HAVE_SYS_SELECT_H
45 #include <sys/select.h>
46 #endif /* HAVE_SYS_SELECT_H */
48 #include "gmain.h"
49 #include "gpattern.h"
50 #include "grand.h"
51 #include "gstrfuncs.h"
52 #include "gtimer.h"
53 #include "gslice.h"
56 /**
57 * SECTION:testing
58 * @title: Testing
59 * @short_description: a test framework
60 * @see_also: <link linkend="gtester">gtester</link>,
61 * <link linkend="gtester-report">gtester-report</link>
63 * GLib provides a framework for writing and maintaining unit tests
64 * in parallel to the code they are testing. The API is designed according
65 * to established concepts found in the other test frameworks (JUnit, NUnit,
66 * RUnit), which in turn is based on smalltalk unit testing concepts.
68 * <variablelist>
69 * <varlistentry>
70 * <term>Test case</term>
71 * <listitem>Tests (test methods) are grouped together with their
72 * fixture into test cases.</listitem>
73 * </varlistentry>
74 * <varlistentry>
75 * <term>Fixture</term>
76 * <listitem>A test fixture consists of fixture data and setup and
77 * teardown methods to establish the environment for the test
78 * functions. We use fresh fixtures, i.e. fixtures are newly set
79 * up and torn down around each test invocation to avoid dependencies
80 * between tests.</listitem>
81 * </varlistentry>
82 * <varlistentry>
83 * <term>Test suite</term>
84 * <listitem>Test cases can be grouped into test suites, to allow
85 * subsets of the available tests to be run. Test suites can be
86 * grouped into other test suites as well.</listitem>
87 * </varlistentry>
88 * </variablelist>
89 * The API is designed to handle creation and registration of test suites
90 * and test cases implicitly. A simple call like
91 * |[
92 * g_test_add_func ("/misc/assertions", test_assertions);
93 * ]|
94 * creates a test suite called "misc" with a single test case named
95 * "assertions", which consists of running the test_assertions function.
97 * In addition to the traditional g_assert(), the test framework provides
98 * an extended set of assertions for string and numerical comparisons:
99 * g_assert_cmpfloat(), g_assert_cmpint(), g_assert_cmpuint(),
100 * g_assert_cmphex(), g_assert_cmpstr(). The advantage of these variants
101 * over plain g_assert() is that the assertion messages can be more
102 * elaborate, and include the values of the compared entities.
104 * GLib ships with two utilities called gtester and gtester-report to
105 * facilitate running tests and producing nicely formatted test reports.
109 * g_test_initialized:
111 * Returns %TRUE if g_test_init() has been called.
113 * Returns: %TRUE if g_test_init() has been called.
115 * Since: 2.36
119 * g_test_quick:
121 * Returns %TRUE if tests are run in quick mode.
122 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
123 * there is no "medium speed".
125 * Returns: %TRUE if in quick mode
129 * g_test_slow:
131 * Returns %TRUE if tests are run in slow mode.
132 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
133 * there is no "medium speed".
135 * Returns: the opposite of g_test_quick()
139 * g_test_thorough:
141 * Returns %TRUE if tests are run in thorough mode, equivalent to
142 * g_test_slow().
144 * Returns: the same thing as g_test_slow()
148 * g_test_perf:
150 * Returns %TRUE if tests are run in performance mode.
152 * Returns: %TRUE if in performance mode
156 * g_test_undefined:
158 * Returns %TRUE if tests may provoke assertions and other formally-undefined
159 * behaviour under g_test_trap_fork(), to verify that appropriate warnings
160 * are given. It can be useful to turn this off if running tests under
161 * valgrind.
163 * Returns: %TRUE if tests may provoke programming errors
167 * g_test_verbose:
169 * Returns %TRUE if tests are run in verbose mode.
170 * The default is neither g_test_verbose() nor g_test_quiet().
172 * Returns: %TRUE if in verbose mode
176 * g_test_quiet:
178 * Returns %TRUE if tests are run in quiet mode.
179 * The default is neither g_test_verbose() nor g_test_quiet().
181 * Returns: %TRUE if in quiet mode
185 * g_test_queue_unref:
186 * @gobject: the object to unref
188 * Enqueue an object to be released with g_object_unref() during
189 * the next teardown phase. This is equivalent to calling
190 * g_test_queue_destroy() with a destroy callback of g_object_unref().
192 * Since: 2.16
196 * GTestTrapFlags:
197 * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
198 * <filename>/dev/null</filename> so it cannot be observed on the
199 * console during test runs. The actual output is still captured
200 * though to allow later tests with g_test_trap_assert_stdout().
201 * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
202 * <filename>/dev/null</filename> so it cannot be observed on the
203 * console during test runs. The actual output is still captured
204 * though to allow later tests with g_test_trap_assert_stderr().
205 * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
206 * forked child process is shared with stdin of its parent process.
207 * It is redirected to <filename>/dev/null</filename> otherwise.
209 * Test traps are guards around forked tests.
210 * These flags determine what traps to set.
214 * g_test_trap_assert_passed:
216 * Assert that the last forked test passed.
217 * See g_test_trap_fork().
219 * Since: 2.16
223 * g_test_trap_assert_failed:
225 * Assert that the last forked test failed.
226 * See g_test_trap_fork().
228 * This is sometimes used to test situations that are formally considered to
229 * be undefined behaviour, like inputs that fail a g_return_if_fail()
230 * check. In these situations you should skip the entire test, including the
231 * call to g_test_trap_fork(), unless g_test_undefined() returns %TRUE
232 * to indicate that undefined behaviour may be tested.
234 * Since: 2.16
238 * g_test_trap_assert_stdout:
239 * @soutpattern: a glob-style
240 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
242 * Assert that the stdout output of the last forked test matches
243 * @soutpattern. See g_test_trap_fork().
245 * Since: 2.16
249 * g_test_trap_assert_stdout_unmatched:
250 * @soutpattern: a glob-style
251 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
253 * Assert that the stdout output of the last forked test
254 * does not match @soutpattern. See g_test_trap_fork().
256 * Since: 2.16
260 * g_test_trap_assert_stderr:
261 * @serrpattern: a glob-style
262 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
264 * Assert that the stderr output of the last forked test
265 * matches @serrpattern. See g_test_trap_fork().
267 * This is sometimes used to test situations that are formally considered to
268 * be undefined behaviour, like inputs that fail a g_return_if_fail()
269 * check. In these situations you should skip the entire test, including the
270 * call to g_test_trap_fork(), unless g_test_undefined() returns %TRUE
271 * to indicate that undefined behaviour may be tested.
273 * Since: 2.16
277 * g_test_trap_assert_stderr_unmatched:
278 * @serrpattern: a glob-style
279 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
281 * Assert that the stderr output of the last forked test
282 * does not match @serrpattern. See g_test_trap_fork().
284 * Since: 2.16
288 * g_test_rand_bit:
290 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
291 * for details on test case random numbers.
293 * Since: 2.16
297 * g_assert:
298 * @expr: the expression to check
300 * Debugging macro to terminate the application if the assertion
301 * fails. If the assertion fails (i.e. the expression is not true),
302 * an error message is logged and the application is terminated.
304 * The macro can be turned off in final releases of code by defining
305 * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
309 * g_assert_not_reached:
311 * Debugging macro to terminate the application if it is ever
312 * reached. If it is reached, an error message is logged and the
313 * application is terminated.
315 * The macro can be turned off in final releases of code by defining
316 * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
320 * g_assert_cmpstr:
321 * @s1: a string (may be %NULL)
322 * @cmp: The comparison operator to use.
323 * One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
324 * @s2: another string (may be %NULL)
326 * Debugging macro to terminate the application with a warning
327 * message if a string comparison fails. The strings are compared
328 * using g_strcmp0().
330 * The effect of <literal>g_assert_cmpstr (s1, op, s2)</literal> is
331 * the same as <literal>g_assert (g_strcmp0 (s1, s2) op 0)</literal>.
332 * The advantage of this macro is that it can produce a message that
333 * includes the actual values of @s1 and @s2.
335 * |[
336 * g_assert_cmpstr (mystring, ==, "fubar");
337 * ]|
339 * Since: 2.16
343 * g_assert_cmpint:
344 * @n1: an integer
345 * @cmp: The comparison operator to use.
346 * One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
347 * @n2: another integer
349 * Debugging macro to terminate the application with a warning
350 * message if an integer comparison fails.
352 * The effect of <literal>g_assert_cmpint (n1, op, n2)</literal> is
353 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
354 * of this macro is that it can produce a message that includes the
355 * actual values of @n1 and @n2.
357 * Since: 2.16
361 * g_assert_cmpuint:
362 * @n1: an unsigned integer
363 * @cmp: The comparison operator to use.
364 * One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
365 * @n2: another unsigned integer
367 * Debugging macro to terminate the application with a warning
368 * message if an unsigned integer comparison fails.
370 * The effect of <literal>g_assert_cmpuint (n1, op, n2)</literal> is
371 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
372 * of this macro is that it can produce a message that includes the
373 * actual values of @n1 and @n2.
375 * Since: 2.16
379 * g_assert_cmphex:
380 * @n1: an unsigned integer
381 * @cmp: The comparison operator to use.
382 * One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
383 * @n2: another unsigned integer
385 * Debugging macro to terminate the application with a warning
386 * message if an unsigned integer comparison fails.
388 * This is a variant of g_assert_cmpuint() that displays the numbers
389 * in hexadecimal notation in the message.
391 * Since: 2.16
395 * g_assert_cmpfloat:
396 * @n1: an floating point number
397 * @cmp: The comparison operator to use.
398 * One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
399 * @n2: another floating point number
401 * Debugging macro to terminate the application with a warning
402 * message if a floating point number comparison fails.
404 * The effect of <literal>g_assert_cmpfloat (n1, op, n2)</literal> is
405 * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
406 * of this macro is that it can produce a message that includes the
407 * actual values of @n1 and @n2.
409 * Since: 2.16
413 * g_assert_no_error:
414 * @err: a #GError, possibly %NULL
416 * Debugging macro to terminate the application with a warning
417 * message if a method has returned a #GError.
419 * The effect of <literal>g_assert_no_error (err)</literal> is
420 * the same as <literal>g_assert (err == NULL)</literal>. The advantage
421 * of this macro is that it can produce a message that includes
422 * the error message and code.
424 * Since: 2.20
428 * g_assert_error:
429 * @err: a #GError, possibly %NULL
430 * @dom: the expected error domain (a #GQuark)
431 * @c: the expected error code
433 * Debugging macro to terminate the application with a warning
434 * message if a method has not returned the correct #GError.
436 * The effect of <literal>g_assert_error (err, dom, c)</literal> is
437 * the same as <literal>g_assert (err != NULL &amp;&amp; err->domain
438 * == dom &amp;&amp; err->code == c)</literal>. The advantage of this
439 * macro is that it can produce a message that includes the incorrect
440 * error message and code.
442 * This can only be used to test for a specific error. If you want to
443 * test that @err is set, but don't care what it's set to, just use
444 * <literal>g_assert (err != NULL)</literal>
446 * Since: 2.20
450 * GTestCase:
452 * An opaque structure representing a test case.
456 * GTestSuite:
458 * An opaque structure representing a test suite.
462 /* Global variable for storing assertion messages; this is the counterpart to
463 * glibc's (private) __abort_msg variable, and allows developers and crash
464 * analysis systems like Apport and ABRT to fish out assertion messages from
465 * core dumps, instead of having to catch them on screen output.
467 char *__glib_assert_msg = NULL;
469 /* --- structures --- */
470 struct GTestCase
472 gchar *name;
473 guint fixture_size;
474 void (*fixture_setup) (void*, gconstpointer);
475 void (*fixture_test) (void*, gconstpointer);
476 void (*fixture_teardown) (void*, gconstpointer);
477 gpointer test_data;
479 struct GTestSuite
481 gchar *name;
482 GSList *suites;
483 GSList *cases;
485 typedef struct DestroyEntry DestroyEntry;
486 struct DestroyEntry
488 DestroyEntry *next;
489 GDestroyNotify destroy_func;
490 gpointer destroy_data;
493 /* --- prototypes --- */
494 static void test_run_seed (const gchar *rseed);
495 static void test_trap_clear (void);
496 static guint8* g_test_log_dump (GTestLogMsg *msg,
497 guint *len);
498 static void gtest_default_log_handler (const gchar *log_domain,
499 GLogLevelFlags log_level,
500 const gchar *message,
501 gpointer unused_data);
504 /* --- variables --- */
505 static int test_log_fd = -1;
506 static gboolean test_mode_fatal = TRUE;
507 static gboolean g_test_run_once = TRUE;
508 static gboolean test_run_list = FALSE;
509 static gchar *test_run_seedstr = NULL;
510 static GRand *test_run_rand = NULL;
511 static gchar *test_run_name = "";
512 static guint test_run_forks = 0;
513 static guint test_run_count = 0;
514 static guint test_run_success = FALSE;
515 static guint test_skip_count = 0;
516 static GTimer *test_user_timer = NULL;
517 static double test_user_stamp = 0;
518 static GSList *test_paths = NULL;
519 static GSList *test_paths_skipped = NULL;
520 static GTestSuite *test_suite_root = NULL;
521 static int test_trap_last_status = 0;
522 static int test_trap_last_pid = 0;
523 static char *test_trap_last_stdout = NULL;
524 static char *test_trap_last_stderr = NULL;
525 static char *test_uri_base = NULL;
526 static gboolean test_debug_log = FALSE;
527 static DestroyEntry *test_destroy_queue = NULL;
528 static GTestConfig mutable_test_config_vars = {
529 FALSE, /* test_initialized */
530 TRUE, /* test_quick */
531 FALSE, /* test_perf */
532 FALSE, /* test_verbose */
533 FALSE, /* test_quiet */
534 TRUE, /* test_undefined */
536 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
538 /* --- functions --- */
539 const char*
540 g_test_log_type_name (GTestLogType log_type)
542 switch (log_type)
544 case G_TEST_LOG_NONE: return "none";
545 case G_TEST_LOG_ERROR: return "error";
546 case G_TEST_LOG_START_BINARY: return "binary";
547 case G_TEST_LOG_LIST_CASE: return "list";
548 case G_TEST_LOG_SKIP_CASE: return "skip";
549 case G_TEST_LOG_START_CASE: return "start";
550 case G_TEST_LOG_STOP_CASE: return "stop";
551 case G_TEST_LOG_MIN_RESULT: return "minperf";
552 case G_TEST_LOG_MAX_RESULT: return "maxperf";
553 case G_TEST_LOG_MESSAGE: return "message";
555 return "???";
558 static void
559 g_test_log_send (guint n_bytes,
560 const guint8 *buffer)
562 if (test_log_fd >= 0)
564 int r;
566 r = write (test_log_fd, buffer, n_bytes);
567 while (r < 0 && errno == EINTR);
569 if (test_debug_log)
571 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
572 GTestLogMsg *msg;
573 guint ui;
574 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
575 msg = g_test_log_buffer_pop (lbuffer);
576 g_warn_if_fail (msg != NULL);
577 g_warn_if_fail (lbuffer->data->len == 0);
578 g_test_log_buffer_free (lbuffer);
579 /* print message */
580 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
581 for (ui = 0; ui < msg->n_strings; ui++)
582 g_printerr (":{%s}", msg->strings[ui]);
583 if (msg->n_nums)
585 g_printerr (":(");
586 for (ui = 0; ui < msg->n_nums; ui++)
588 if ((long double) (long) msg->nums[ui] == msg->nums[ui])
589 g_printerr ("%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
590 else
591 g_printerr ("%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
593 g_printerr (")");
595 g_printerr (":LOG*}\n");
596 g_test_log_msg_free (msg);
600 static void
601 g_test_log (GTestLogType lbit,
602 const gchar *string1,
603 const gchar *string2,
604 guint n_args,
605 long double *largs)
607 gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
608 GTestLogMsg msg;
609 gchar *astrings[3] = { NULL, NULL, NULL };
610 guint8 *dbuffer;
611 guint32 dbufferlen;
613 switch (lbit)
615 case G_TEST_LOG_START_BINARY:
616 if (g_test_verbose())
617 g_print ("GTest: random seed: %s\n", string2);
618 break;
619 case G_TEST_LOG_STOP_CASE:
620 if (g_test_verbose())
621 g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
622 else if (!g_test_quiet())
623 g_print ("%s\n", fail ? "FAIL" : "OK");
624 if (fail && test_mode_fatal)
625 abort();
626 break;
627 case G_TEST_LOG_MIN_RESULT:
628 if (g_test_verbose())
629 g_print ("(MINPERF:%s)\n", string1);
630 break;
631 case G_TEST_LOG_MAX_RESULT:
632 if (g_test_verbose())
633 g_print ("(MAXPERF:%s)\n", string1);
634 break;
635 case G_TEST_LOG_MESSAGE:
636 case G_TEST_LOG_ERROR:
637 if (g_test_verbose())
638 g_print ("(MSG: %s)\n", string1);
639 break;
640 default: ;
643 msg.log_type = lbit;
644 msg.n_strings = (string1 != NULL) + (string1 && string2);
645 msg.strings = astrings;
646 astrings[0] = (gchar*) string1;
647 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
648 msg.n_nums = n_args;
649 msg.nums = largs;
650 dbuffer = g_test_log_dump (&msg, &dbufferlen);
651 g_test_log_send (dbufferlen, dbuffer);
652 g_free (dbuffer);
654 switch (lbit)
656 case G_TEST_LOG_START_CASE:
657 if (g_test_verbose())
658 g_print ("GTest: run: %s\n", string1);
659 else if (!g_test_quiet())
660 g_print ("%s: ", string1);
661 break;
662 default: ;
666 /* We intentionally parse the command line without GOptionContext
667 * because otherwise you would never be able to test it.
669 static void
670 parse_args (gint *argc_p,
671 gchar ***argv_p)
673 guint argc = *argc_p;
674 gchar **argv = *argv_p;
675 guint i, e;
676 /* parse known args */
677 for (i = 1; i < argc; i++)
679 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
681 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
682 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
683 g_log_set_always_fatal (fatal_mask);
684 argv[i] = NULL;
686 else if (strcmp (argv[i], "--keep-going") == 0 ||
687 strcmp (argv[i], "-k") == 0)
689 test_mode_fatal = FALSE;
690 argv[i] = NULL;
692 else if (strcmp (argv[i], "--debug-log") == 0)
694 test_debug_log = TRUE;
695 argv[i] = NULL;
697 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
699 gchar *equal = argv[i] + 12;
700 if (*equal == '=')
701 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
702 else if (i + 1 < argc)
704 argv[i++] = NULL;
705 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
707 argv[i] = NULL;
709 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
711 gchar *equal = argv[i] + 16;
712 if (*equal == '=')
713 test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
714 else if (i + 1 < argc)
716 argv[i++] = NULL;
717 test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
719 argv[i] = NULL;
721 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
723 gchar *equal = argv[i] + 2;
724 if (*equal == '=')
725 test_paths = g_slist_prepend (test_paths, equal + 1);
726 else if (i + 1 < argc)
728 argv[i++] = NULL;
729 test_paths = g_slist_prepend (test_paths, argv[i]);
731 argv[i] = NULL;
733 else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
735 gchar *equal = argv[i] + 2;
736 if (*equal == '=')
737 test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
738 else if (i + 1 < argc)
740 argv[i++] = NULL;
741 test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
743 argv[i] = NULL;
745 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
747 gchar *equal = argv[i] + 2;
748 const gchar *mode = "";
749 if (*equal == '=')
750 mode = equal + 1;
751 else if (i + 1 < argc)
753 argv[i++] = NULL;
754 mode = argv[i];
756 if (strcmp (mode, "perf") == 0)
757 mutable_test_config_vars.test_perf = TRUE;
758 else if (strcmp (mode, "slow") == 0)
759 mutable_test_config_vars.test_quick = FALSE;
760 else if (strcmp (mode, "thorough") == 0)
761 mutable_test_config_vars.test_quick = FALSE;
762 else if (strcmp (mode, "quick") == 0)
764 mutable_test_config_vars.test_quick = TRUE;
765 mutable_test_config_vars.test_perf = FALSE;
767 else if (strcmp (mode, "undefined") == 0)
768 mutable_test_config_vars.test_undefined = TRUE;
769 else if (strcmp (mode, "no-undefined") == 0)
770 mutable_test_config_vars.test_undefined = FALSE;
771 else
772 g_error ("unknown test mode: -m %s", mode);
773 argv[i] = NULL;
775 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
777 mutable_test_config_vars.test_quiet = TRUE;
778 mutable_test_config_vars.test_verbose = FALSE;
779 argv[i] = NULL;
781 else if (strcmp ("--verbose", argv[i]) == 0)
783 mutable_test_config_vars.test_quiet = FALSE;
784 mutable_test_config_vars.test_verbose = TRUE;
785 argv[i] = NULL;
787 else if (strcmp ("-l", argv[i]) == 0)
789 test_run_list = TRUE;
790 argv[i] = NULL;
792 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
794 gchar *equal = argv[i] + 6;
795 if (*equal == '=')
796 test_run_seedstr = equal + 1;
797 else if (i + 1 < argc)
799 argv[i++] = NULL;
800 test_run_seedstr = argv[i];
802 argv[i] = NULL;
804 else if (strcmp ("-?", argv[i]) == 0 ||
805 strcmp ("-h", argv[i]) == 0 ||
806 strcmp ("--help", argv[i]) == 0)
808 printf ("Usage:\n"
809 " %s [OPTION...]\n\n"
810 "Help Options:\n"
811 " -h, --help Show help options\n\n"
812 "Test Options:\n"
813 " --g-fatal-warnings Make all warnings fatal\n"
814 " -l List test cases available in a test executable\n"
815 " -m {perf|slow|thorough|quick} Execute tests according to mode\n"
816 " -m {undefined|no-undefined} Execute tests according to mode\n"
817 " -p TESTPATH Only start test cases matching TESTPATH\n"
818 " -s TESTPATH Skip all tests matching TESTPATH\n"
819 " -seed=SEEDSTRING Start tests with random seed SEEDSTRING\n"
820 " --debug-log debug test logging output\n"
821 " -q, --quiet Run tests quietly\n"
822 " --verbose Run tests verbosely\n",
823 argv[0]);
824 exit (0);
827 /* collapse argv */
828 e = 1;
829 for (i = 1; i < argc; i++)
830 if (argv[i])
832 argv[e++] = argv[i];
833 if (i >= e)
834 argv[i] = NULL;
836 *argc_p = e;
840 * g_test_init:
841 * @argc: Address of the @argc parameter of the main() function.
842 * Changed if any arguments were handled.
843 * @argv: Address of the @argv parameter of main().
844 * Any parameters understood by g_test_init() stripped before return.
845 * @...: Reserved for future extension. Currently, you must pass %NULL.
847 * Initialize the GLib testing framework, e.g. by seeding the
848 * test random number generator, the name for g_get_prgname()
849 * and parsing test related command line args.
850 * So far, the following arguments are understood:
851 * <variablelist>
852 * <varlistentry>
853 * <term><option>-l</option></term>
854 * <listitem><para>
855 * List test cases available in a test executable.
856 * </para></listitem>
857 * </varlistentry>
858 * <varlistentry>
859 * <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
860 * <listitem><para>
861 * Provide a random seed to reproduce test runs using random numbers.
862 * </para></listitem>
863 * </varlistentry>
864 * <varlistentry>
865 * <term><option>--verbose</option></term>
866 * <listitem><para>Run tests verbosely.</para></listitem>
867 * </varlistentry>
868 * <varlistentry>
869 * <term><option>-q</option>, <option>--quiet</option></term>
870 * <listitem><para>Run tests quietly.</para></listitem>
871 * </varlistentry>
872 * <varlistentry>
873 * <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
874 * <listitem><para>
875 * Execute all tests matching <replaceable>TESTPATH</replaceable>.
876 * </para></listitem>
877 * </varlistentry>
878 * <varlistentry>
879 * <term><option>-m {perf|slow|thorough|quick|undefined|no-undefined}</option></term>
880 * <listitem><para>
881 * Execute tests according to these test modes:
882 * <variablelist>
883 * <varlistentry>
884 * <term>perf</term>
885 * <listitem><para>
886 * Performance tests, may take long and report results.
887 * </para></listitem>
888 * </varlistentry>
889 * <varlistentry>
890 * <term>slow, thorough</term>
891 * <listitem><para>
892 * Slow and thorough tests, may take quite long and
893 * maximize coverage.
894 * </para></listitem>
895 * </varlistentry>
896 * <varlistentry>
897 * <term>quick</term>
898 * <listitem><para>
899 * Quick tests, should run really quickly and give good coverage.
900 * </para></listitem>
901 * </varlistentry>
902 * <varlistentry>
903 * <term>undefined</term>
904 * <listitem><para>
905 * Tests for undefined behaviour, may provoke programming errors
906 * under g_test_trap_fork() to check that appropriate assertions
907 * or warnings are given
908 * </para></listitem>
909 * </varlistentry>
910 * <varlistentry>
911 * <term>no-undefined</term>
912 * <listitem><para>
913 * Avoid tests for undefined behaviour
914 * </para></listitem>
915 * </varlistentry>
916 * </variablelist>
917 * </para></listitem>
918 * </varlistentry>
919 * <varlistentry>
920 * <term><option>--debug-log</option></term>
921 * <listitem><para>Debug test logging output.</para></listitem>
922 * </varlistentry>
923 * </variablelist>
925 * Since: 2.16
927 void
928 g_test_init (int *argc,
929 char ***argv,
930 ...)
932 static char seedstr[4 + 4 * 8 + 1];
933 va_list args;
934 gpointer vararg1;
935 /* make warnings and criticals fatal for all test programs */
936 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
937 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
938 g_log_set_always_fatal (fatal_mask);
939 /* check caller args */
940 g_return_if_fail (argc != NULL);
941 g_return_if_fail (argv != NULL);
942 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
943 mutable_test_config_vars.test_initialized = TRUE;
945 va_start (args, argv);
946 vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
947 va_end (args);
948 g_return_if_fail (vararg1 == NULL);
950 /* setup random seed string */
951 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
952 test_run_seedstr = seedstr;
954 /* parse args, sets up mode, changes seed, etc. */
955 parse_args (argc, argv);
956 if (!g_get_prgname())
957 g_set_prgname ((*argv)[0]);
959 /* verify GRand reliability, needed for reliable seeds */
960 if (1)
962 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
963 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
964 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
965 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
966 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
967 g_rand_free (rg);
970 /* check rand seed */
971 test_run_seed (test_run_seedstr);
973 /* report program start */
974 g_log_set_default_handler (gtest_default_log_handler, NULL);
975 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
978 static void
979 test_run_seed (const gchar *rseed)
981 guint seed_failed = 0;
982 if (test_run_rand)
983 g_rand_free (test_run_rand);
984 test_run_rand = NULL;
985 while (strchr (" \t\v\r\n\f", *rseed))
986 rseed++;
987 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
989 const char *s = rseed + 4;
990 if (strlen (s) >= 32) /* require 4 * 8 chars */
992 guint32 seedarray[4];
993 gchar *p, hexbuf[9] = { 0, };
994 memcpy (hexbuf, s + 0, 8);
995 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
996 seed_failed += p != NULL && *p != 0;
997 memcpy (hexbuf, s + 8, 8);
998 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
999 seed_failed += p != NULL && *p != 0;
1000 memcpy (hexbuf, s + 16, 8);
1001 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
1002 seed_failed += p != NULL && *p != 0;
1003 memcpy (hexbuf, s + 24, 8);
1004 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
1005 seed_failed += p != NULL && *p != 0;
1006 if (!seed_failed)
1008 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
1009 return;
1013 g_error ("Unknown or invalid random seed: %s", rseed);
1017 * g_test_rand_int:
1019 * Get a reproducible random integer number.
1021 * The random numbers generated by the g_test_rand_*() family of functions
1022 * change with every new test program start, unless the --seed option is
1023 * given when starting test programs.
1025 * For individual test cases however, the random number generator is
1026 * reseeded, to avoid dependencies between tests and to make --seed
1027 * effective for all test cases.
1029 * Returns: a random number from the seeded random number generator.
1031 * Since: 2.16
1033 gint32
1034 g_test_rand_int (void)
1036 return g_rand_int (test_run_rand);
1040 * g_test_rand_int_range:
1041 * @begin: the minimum value returned by this function
1042 * @end: the smallest value not to be returned by this function
1044 * Get a reproducible random integer number out of a specified range,
1045 * see g_test_rand_int() for details on test case random numbers.
1047 * Returns: a number with @begin <= number < @end.
1049 * Since: 2.16
1051 gint32
1052 g_test_rand_int_range (gint32 begin,
1053 gint32 end)
1055 return g_rand_int_range (test_run_rand, begin, end);
1059 * g_test_rand_double:
1061 * Get a reproducible random floating point number,
1062 * see g_test_rand_int() for details on test case random numbers.
1064 * Returns: a random number from the seeded random number generator.
1066 * Since: 2.16
1068 double
1069 g_test_rand_double (void)
1071 return g_rand_double (test_run_rand);
1075 * g_test_rand_double_range:
1076 * @range_start: the minimum value returned by this function
1077 * @range_end: the minimum value not returned by this function
1079 * Get a reproducible random floating pointer number out of a specified range,
1080 * see g_test_rand_int() for details on test case random numbers.
1082 * Returns: a number with @range_start <= number < @range_end.
1084 * Since: 2.16
1086 double
1087 g_test_rand_double_range (double range_start,
1088 double range_end)
1090 return g_rand_double_range (test_run_rand, range_start, range_end);
1094 * g_test_timer_start:
1096 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1097 * to be done. Call this function again to restart the timer.
1099 * Since: 2.16
1101 void
1102 g_test_timer_start (void)
1104 if (!test_user_timer)
1105 test_user_timer = g_timer_new();
1106 test_user_stamp = 0;
1107 g_timer_start (test_user_timer);
1111 * g_test_timer_elapsed:
1113 * Get the time since the last start of the timer with g_test_timer_start().
1115 * Returns: the time since the last start of the timer, as a double
1117 * Since: 2.16
1119 double
1120 g_test_timer_elapsed (void)
1122 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1123 return test_user_stamp;
1127 * g_test_timer_last:
1129 * Report the last result of g_test_timer_elapsed().
1131 * Returns: the last result of g_test_timer_elapsed(), as a double
1133 * Since: 2.16
1135 double
1136 g_test_timer_last (void)
1138 return test_user_stamp;
1142 * g_test_minimized_result:
1143 * @minimized_quantity: the reported value
1144 * @format: the format string of the report message
1145 * @...: arguments to pass to the printf() function
1147 * Report the result of a performance or measurement test.
1148 * The test should generally strive to minimize the reported
1149 * quantities (smaller values are better than larger ones),
1150 * this and @minimized_quantity can determine sorting
1151 * order for test result reports.
1153 * Since: 2.16
1155 void
1156 g_test_minimized_result (double minimized_quantity,
1157 const char *format,
1158 ...)
1160 long double largs = minimized_quantity;
1161 gchar *buffer;
1162 va_list args;
1164 va_start (args, format);
1165 buffer = g_strdup_vprintf (format, args);
1166 va_end (args);
1168 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1169 g_free (buffer);
1173 * g_test_maximized_result:
1174 * @maximized_quantity: the reported value
1175 * @format: the format string of the report message
1176 * @...: arguments to pass to the printf() function
1178 * Report the result of a performance or measurement test.
1179 * The test should generally strive to maximize the reported
1180 * quantities (larger values are better than smaller ones),
1181 * this and @maximized_quantity can determine sorting
1182 * order for test result reports.
1184 * Since: 2.16
1186 void
1187 g_test_maximized_result (double maximized_quantity,
1188 const char *format,
1189 ...)
1191 long double largs = maximized_quantity;
1192 gchar *buffer;
1193 va_list args;
1195 va_start (args, format);
1196 buffer = g_strdup_vprintf (format, args);
1197 va_end (args);
1199 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1200 g_free (buffer);
1204 * g_test_message:
1205 * @format: the format string
1206 * @...: printf-like arguments to @format
1208 * Add a message to the test report.
1210 * Since: 2.16
1212 void
1213 g_test_message (const char *format,
1214 ...)
1216 gchar *buffer;
1217 va_list args;
1219 va_start (args, format);
1220 buffer = g_strdup_vprintf (format, args);
1221 va_end (args);
1223 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1224 g_free (buffer);
1228 * g_test_bug_base:
1229 * @uri_pattern: the base pattern for bug URIs
1231 * Specify the base URI for bug reports.
1233 * The base URI is used to construct bug report messages for
1234 * g_test_message() when g_test_bug() is called.
1235 * Calling this function outside of a test case sets the
1236 * default base URI for all test cases. Calling it from within
1237 * a test case changes the base URI for the scope of the test
1238 * case only.
1239 * Bug URIs are constructed by appending a bug specific URI
1240 * portion to @uri_pattern, or by replacing the special string
1241 * '\%s' within @uri_pattern if that is present.
1243 * Since: 2.16
1245 void
1246 g_test_bug_base (const char *uri_pattern)
1248 g_free (test_uri_base);
1249 test_uri_base = g_strdup (uri_pattern);
1253 * g_test_bug:
1254 * @bug_uri_snippet: Bug specific bug tracker URI portion.
1256 * This function adds a message to test reports that
1257 * associates a bug URI with a test case.
1258 * Bug URIs are constructed from a base URI set with g_test_bug_base()
1259 * and @bug_uri_snippet.
1261 * Since: 2.16
1263 void
1264 g_test_bug (const char *bug_uri_snippet)
1266 char *c;
1268 g_return_if_fail (test_uri_base != NULL);
1269 g_return_if_fail (bug_uri_snippet != NULL);
1271 c = strstr (test_uri_base, "%s");
1272 if (c)
1274 char *b = g_strndup (test_uri_base, c - test_uri_base);
1275 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1276 g_free (b);
1277 g_test_message ("Bug Reference: %s", s);
1278 g_free (s);
1280 else
1281 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1285 * g_test_get_root:
1287 * Get the toplevel test suite for the test path API.
1289 * Returns: the toplevel #GTestSuite
1291 * Since: 2.16
1293 GTestSuite*
1294 g_test_get_root (void)
1296 if (!test_suite_root)
1298 test_suite_root = g_test_create_suite ("root");
1299 g_free (test_suite_root->name);
1300 test_suite_root->name = g_strdup ("");
1303 return test_suite_root;
1307 * g_test_run:
1309 * Runs all tests under the toplevel suite which can be retrieved
1310 * with g_test_get_root(). Similar to g_test_run_suite(), the test
1311 * cases to be run are filtered according to
1312 * test path arguments (-p <replaceable>testpath</replaceable>) as
1313 * parsed by g_test_init().
1314 * g_test_run_suite() or g_test_run() may only be called once
1315 * in a program.
1317 * Returns: 0 on success
1319 * Since: 2.16
1322 g_test_run (void)
1324 return g_test_run_suite (g_test_get_root());
1328 * g_test_create_case:
1329 * @test_name: the name for the test case
1330 * @data_size: the size of the fixture data structure
1331 * @test_data: test data argument for the test functions
1332 * @data_setup: the function to set up the fixture data
1333 * @data_test: the actual test function
1334 * @data_teardown: the function to teardown the fixture data
1336 * Create a new #GTestCase, named @test_name, this API is fairly
1337 * low level, calling g_test_add() or g_test_add_func() is preferable.
1338 * When this test is executed, a fixture structure of size @data_size
1339 * will be allocated and filled with 0s. Then @data_setup is called
1340 * to initialize the fixture. After fixture setup, the actual test
1341 * function @data_test is called. Once the test run completed, the
1342 * fixture structure is torn down by calling @data_teardown and
1343 * after that the memory is released.
1345 * Splitting up a test run into fixture setup, test function and
1346 * fixture teardown is most usful if the same fixture is used for
1347 * multiple tests. In this cases, g_test_create_case() will be
1348 * called with the same fixture, but varying @test_name and
1349 * @data_test arguments.
1351 * Returns: a newly allocated #GTestCase.
1353 * Since: 2.16
1355 GTestCase*
1356 g_test_create_case (const char *test_name,
1357 gsize data_size,
1358 gconstpointer test_data,
1359 GTestFixtureFunc data_setup,
1360 GTestFixtureFunc data_test,
1361 GTestFixtureFunc data_teardown)
1363 GTestCase *tc;
1365 g_return_val_if_fail (test_name != NULL, NULL);
1366 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1367 g_return_val_if_fail (test_name[0] != 0, NULL);
1368 g_return_val_if_fail (data_test != NULL, NULL);
1370 tc = g_slice_new0 (GTestCase);
1371 tc->name = g_strdup (test_name);
1372 tc->test_data = (gpointer) test_data;
1373 tc->fixture_size = data_size;
1374 tc->fixture_setup = (void*) data_setup;
1375 tc->fixture_test = (void*) data_test;
1376 tc->fixture_teardown = (void*) data_teardown;
1378 return tc;
1381 static gint
1382 find_suite (gconstpointer l, gconstpointer s)
1384 const GTestSuite *suite = l;
1385 const gchar *str = s;
1387 return strcmp (suite->name, str);
1391 * GTestFixtureFunc:
1392 * @fixture: the test fixture
1393 * @user_data: the data provided when registering the test
1395 * The type used for functions that operate on test fixtures. This is
1396 * used for the fixture setup and teardown functions as well as for the
1397 * testcases themselves.
1399 * @user_data is a pointer to the data that was given when registering
1400 * the test case.
1402 * @fixture will be a pointer to the area of memory allocated by the
1403 * test framework, of the size requested. If the requested size was
1404 * zero then @fixture will be equal to @user_data.
1406 * Since: 2.28
1408 void
1409 g_test_add_vtable (const char *testpath,
1410 gsize data_size,
1411 gconstpointer test_data,
1412 GTestFixtureFunc data_setup,
1413 GTestFixtureFunc fixture_test_func,
1414 GTestFixtureFunc data_teardown)
1416 gchar **segments;
1417 guint ui;
1418 GTestSuite *suite;
1420 g_return_if_fail (testpath != NULL);
1421 g_return_if_fail (g_path_is_absolute (testpath));
1422 g_return_if_fail (fixture_test_func != NULL);
1424 if (g_slist_find_custom (test_paths_skipped, testpath, (GCompareFunc)g_strcmp0))
1425 return;
1427 suite = g_test_get_root();
1428 segments = g_strsplit (testpath, "/", -1);
1429 for (ui = 0; segments[ui] != NULL; ui++)
1431 const char *seg = segments[ui];
1432 gboolean islast = segments[ui + 1] == NULL;
1433 if (islast && !seg[0])
1434 g_error ("invalid test case path: %s", testpath);
1435 else if (!seg[0])
1436 continue; /* initial or duplicate slash */
1437 else if (!islast)
1439 GSList *l;
1440 GTestSuite *csuite;
1441 l = g_slist_find_custom (suite->suites, seg, find_suite);
1442 if (l)
1444 csuite = l->data;
1446 else
1448 csuite = g_test_create_suite (seg);
1449 g_test_suite_add_suite (suite, csuite);
1451 suite = csuite;
1453 else /* islast */
1455 GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1456 g_test_suite_add (suite, tc);
1459 g_strfreev (segments);
1463 * g_test_fail:
1465 * Indicates that a test failed. This function can be called
1466 * multiple times from the same test. You can use this function
1467 * if your test failed in a recoverable way.
1469 * Do not use this function if the failure of a test could cause
1470 * other tests to malfunction.
1472 * Calling this function will not stop the test from running, you
1473 * need to return from the test function yourself. So you can
1474 * produce additional diagnostic messages or even continue running
1475 * the test.
1477 * If not called from inside a test, this function does nothing.
1479 * Since: 2.30
1481 void
1482 g_test_fail (void)
1484 test_run_success = FALSE;
1488 * GTestFunc:
1490 * The type used for test case functions.
1492 * Since: 2.28
1496 * g_test_add_func:
1497 * @testpath: /-separated test case path name for the test.
1498 * @test_func: The test function to invoke for this test.
1500 * Create a new test case, similar to g_test_create_case(). However
1501 * the test is assumed to use no fixture, and test suites are automatically
1502 * created on the fly and added to the root fixture, based on the
1503 * slash-separated portions of @testpath.
1505 * Since: 2.16
1507 void
1508 g_test_add_func (const char *testpath,
1509 GTestFunc test_func)
1511 g_return_if_fail (testpath != NULL);
1512 g_return_if_fail (testpath[0] == '/');
1513 g_return_if_fail (test_func != NULL);
1514 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1518 * GTestDataFunc:
1519 * @user_data: the data provided when registering the test
1521 * The type used for test case functions that take an extra pointer
1522 * argument.
1524 * Since: 2.28
1528 * g_test_add_data_func:
1529 * @testpath: /-separated test case path name for the test.
1530 * @test_data: Test data argument for the test function.
1531 * @test_func: The test function to invoke for this test.
1533 * Create a new test case, similar to g_test_create_case(). However
1534 * the test is assumed to use no fixture, and test suites are automatically
1535 * created on the fly and added to the root fixture, based on the
1536 * slash-separated portions of @testpath. The @test_data argument
1537 * will be passed as first argument to @test_func.
1539 * Since: 2.16
1541 void
1542 g_test_add_data_func (const char *testpath,
1543 gconstpointer test_data,
1544 GTestDataFunc test_func)
1546 g_return_if_fail (testpath != NULL);
1547 g_return_if_fail (testpath[0] == '/');
1548 g_return_if_fail (test_func != NULL);
1550 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1554 * g_test_add_data_func_full:
1555 * @testpath: /-separated test case path name for the test.
1556 * @test_data: Test data argument for the test function.
1557 * @test_func: The test function to invoke for this test.
1558 * @data_free_func: #GDestroyNotify for @test_data.
1560 * Create a new test case, as with g_test_add_data_func(), but freeing
1561 * @test_data after the test run is complete.
1563 * Since: 2.34
1565 void
1566 g_test_add_data_func_full (const char *testpath,
1567 gpointer test_data,
1568 GTestDataFunc test_func,
1569 GDestroyNotify data_free_func)
1571 g_return_if_fail (testpath != NULL);
1572 g_return_if_fail (testpath[0] == '/');
1573 g_return_if_fail (test_func != NULL);
1575 g_test_add_vtable (testpath, 0, test_data, NULL,
1576 (GTestFixtureFunc) test_func,
1577 (GTestFixtureFunc) data_free_func);
1581 * g_test_create_suite:
1582 * @suite_name: a name for the suite
1584 * Create a new test suite with the name @suite_name.
1586 * Returns: A newly allocated #GTestSuite instance.
1588 * Since: 2.16
1590 GTestSuite*
1591 g_test_create_suite (const char *suite_name)
1593 GTestSuite *ts;
1594 g_return_val_if_fail (suite_name != NULL, NULL);
1595 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1596 g_return_val_if_fail (suite_name[0] != 0, NULL);
1597 ts = g_slice_new0 (GTestSuite);
1598 ts->name = g_strdup (suite_name);
1599 return ts;
1603 * g_test_suite_add:
1604 * @suite: a #GTestSuite
1605 * @test_case: a #GTestCase
1607 * Adds @test_case to @suite.
1609 * Since: 2.16
1611 void
1612 g_test_suite_add (GTestSuite *suite,
1613 GTestCase *test_case)
1615 g_return_if_fail (suite != NULL);
1616 g_return_if_fail (test_case != NULL);
1618 suite->cases = g_slist_prepend (suite->cases, test_case);
1622 * g_test_suite_add_suite:
1623 * @suite: a #GTestSuite
1624 * @nestedsuite: another #GTestSuite
1626 * Adds @nestedsuite to @suite.
1628 * Since: 2.16
1630 void
1631 g_test_suite_add_suite (GTestSuite *suite,
1632 GTestSuite *nestedsuite)
1634 g_return_if_fail (suite != NULL);
1635 g_return_if_fail (nestedsuite != NULL);
1637 suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1641 * g_test_queue_free:
1642 * @gfree_pointer: the pointer to be stored.
1644 * Enqueue a pointer to be released with g_free() during the next
1645 * teardown phase. This is equivalent to calling g_test_queue_destroy()
1646 * with a destroy callback of g_free().
1648 * Since: 2.16
1650 void
1651 g_test_queue_free (gpointer gfree_pointer)
1653 if (gfree_pointer)
1654 g_test_queue_destroy (g_free, gfree_pointer);
1658 * g_test_queue_destroy:
1659 * @destroy_func: Destroy callback for teardown phase.
1660 * @destroy_data: Destroy callback data.
1662 * This function enqueus a callback @destroy_func to be executed
1663 * during the next test case teardown phase. This is most useful
1664 * to auto destruct allocted test resources at the end of a test run.
1665 * Resources are released in reverse queue order, that means enqueueing
1666 * callback A before callback B will cause B() to be called before
1667 * A() during teardown.
1669 * Since: 2.16
1671 void
1672 g_test_queue_destroy (GDestroyNotify destroy_func,
1673 gpointer destroy_data)
1675 DestroyEntry *dentry;
1677 g_return_if_fail (destroy_func != NULL);
1679 dentry = g_slice_new0 (DestroyEntry);
1680 dentry->destroy_func = destroy_func;
1681 dentry->destroy_data = destroy_data;
1682 dentry->next = test_destroy_queue;
1683 test_destroy_queue = dentry;
1686 static gboolean
1687 test_case_run (GTestCase *tc)
1689 gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1690 gboolean success = TRUE;
1692 test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1693 if (++test_run_count <= test_skip_count)
1694 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1695 else if (test_run_list)
1697 g_print ("%s\n", test_run_name);
1698 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1700 else
1702 GTimer *test_run_timer = g_timer_new();
1703 long double largs[3];
1704 void *fixture;
1705 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1706 test_run_forks = 0;
1707 test_run_success = TRUE;
1708 g_test_log_set_fatal_handler (NULL, NULL);
1709 g_timer_start (test_run_timer);
1710 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1711 test_run_seed (test_run_seedstr);
1712 if (tc->fixture_setup)
1713 tc->fixture_setup (fixture, tc->test_data);
1714 tc->fixture_test (fixture, tc->test_data);
1715 test_trap_clear();
1716 while (test_destroy_queue)
1718 DestroyEntry *dentry = test_destroy_queue;
1719 test_destroy_queue = dentry->next;
1720 dentry->destroy_func (dentry->destroy_data);
1721 g_slice_free (DestroyEntry, dentry);
1723 if (tc->fixture_teardown)
1724 tc->fixture_teardown (fixture, tc->test_data);
1725 if (tc->fixture_size)
1726 g_free (fixture);
1727 g_timer_stop (test_run_timer);
1728 success = test_run_success;
1729 test_run_success = FALSE;
1730 largs[0] = success ? 0 : 1; /* OK */
1731 largs[1] = test_run_forks;
1732 largs[2] = g_timer_elapsed (test_run_timer, NULL);
1733 g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1734 g_timer_destroy (test_run_timer);
1736 g_free (test_run_name);
1737 test_run_name = old_name;
1738 g_free (test_uri_base);
1739 test_uri_base = old_base;
1741 return success;
1744 static int
1745 g_test_run_suite_internal (GTestSuite *suite,
1746 const char *path)
1748 guint n_bad = 0, l;
1749 gchar *rest, *old_name = test_run_name;
1750 GSList *slist, *reversed;
1752 g_return_val_if_fail (suite != NULL, -1);
1754 while (path[0] == '/')
1755 path++;
1756 l = strlen (path);
1757 rest = strchr (path, '/');
1758 l = rest ? MIN (l, rest - path) : l;
1759 test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1760 reversed = g_slist_reverse (g_slist_copy (suite->cases));
1761 for (slist = reversed; slist; slist = slist->next)
1763 GTestCase *tc = slist->data;
1764 guint n = l ? strlen (tc->name) : 0;
1765 if (l == n && strncmp (path, tc->name, n) == 0)
1767 if (!test_case_run (tc))
1768 n_bad++;
1771 g_slist_free (reversed);
1772 reversed = g_slist_reverse (g_slist_copy (suite->suites));
1773 for (slist = reversed; slist; slist = slist->next)
1775 GTestSuite *ts = slist->data;
1776 guint n = l ? strlen (ts->name) : 0;
1777 if (l == n && strncmp (path, ts->name, n) == 0)
1778 n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
1780 g_slist_free (reversed);
1781 g_free (test_run_name);
1782 test_run_name = old_name;
1784 return n_bad;
1788 * g_test_run_suite:
1789 * @suite: a #GTestSuite
1791 * Execute the tests within @suite and all nested #GTestSuites.
1792 * The test suites to be executed are filtered according to
1793 * test path arguments (-p <replaceable>testpath</replaceable>)
1794 * as parsed by g_test_init().
1795 * g_test_run_suite() or g_test_run() may only be called once
1796 * in a program.
1798 * Returns: 0 on success
1800 * Since: 2.16
1803 g_test_run_suite (GTestSuite *suite)
1805 guint n_bad = 0;
1807 g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1808 g_return_val_if_fail (g_test_run_once == TRUE, -1);
1810 g_test_run_once = FALSE;
1812 if (!test_paths)
1813 test_paths = g_slist_prepend (test_paths, "");
1814 while (test_paths)
1816 const char *rest, *path = test_paths->data;
1817 guint l, n = strlen (suite->name);
1818 test_paths = g_slist_delete_link (test_paths, test_paths);
1819 while (path[0] == '/')
1820 path++;
1821 if (!n) /* root suite, run unconditionally */
1823 n_bad += g_test_run_suite_internal (suite, path);
1824 continue;
1826 /* regular suite, match path */
1827 rest = strchr (path, '/');
1828 l = strlen (path);
1829 l = rest ? MIN (l, rest - path) : l;
1830 if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1831 n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
1834 return n_bad;
1837 static void
1838 gtest_default_log_handler (const gchar *log_domain,
1839 GLogLevelFlags log_level,
1840 const gchar *message,
1841 gpointer unused_data)
1843 const gchar *strv[16];
1844 gboolean fatal = FALSE;
1845 gchar *msg;
1846 guint i = 0;
1848 if (log_domain)
1850 strv[i++] = log_domain;
1851 strv[i++] = "-";
1853 if (log_level & G_LOG_FLAG_FATAL)
1855 strv[i++] = "FATAL-";
1856 fatal = TRUE;
1858 if (log_level & G_LOG_FLAG_RECURSION)
1859 strv[i++] = "RECURSIVE-";
1860 if (log_level & G_LOG_LEVEL_ERROR)
1861 strv[i++] = "ERROR";
1862 if (log_level & G_LOG_LEVEL_CRITICAL)
1863 strv[i++] = "CRITICAL";
1864 if (log_level & G_LOG_LEVEL_WARNING)
1865 strv[i++] = "WARNING";
1866 if (log_level & G_LOG_LEVEL_MESSAGE)
1867 strv[i++] = "MESSAGE";
1868 if (log_level & G_LOG_LEVEL_INFO)
1869 strv[i++] = "INFO";
1870 if (log_level & G_LOG_LEVEL_DEBUG)
1871 strv[i++] = "DEBUG";
1872 strv[i++] = ": ";
1873 strv[i++] = message;
1874 strv[i++] = NULL;
1876 msg = g_strjoinv ("", (gchar**) strv);
1877 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
1878 g_log_default_handler (log_domain, log_level, message, unused_data);
1880 g_free (msg);
1883 void
1884 g_assertion_message (const char *domain,
1885 const char *file,
1886 int line,
1887 const char *func,
1888 const char *message)
1890 char lstr[32];
1891 char *s;
1893 if (!message)
1894 message = "code should not be reached";
1895 g_snprintf (lstr, 32, "%d", line);
1896 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1897 "ERROR:", file, ":", lstr, ":",
1898 func, func[0] ? ":" : "",
1899 " ", message, NULL);
1900 g_printerr ("**\n%s\n", s);
1902 /* store assertion message in global variable, so that it can be found in a
1903 * core dump */
1904 if (__glib_assert_msg != NULL)
1905 /* free the old one */
1906 free (__glib_assert_msg);
1907 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
1908 strcpy (__glib_assert_msg, s);
1910 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
1911 g_free (s);
1912 abort();
1915 void
1916 g_assertion_message_expr (const char *domain,
1917 const char *file,
1918 int line,
1919 const char *func,
1920 const char *expr)
1922 char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1923 g_assertion_message (domain, file, line, func, s);
1924 g_free (s);
1927 void
1928 g_assertion_message_cmpnum (const char *domain,
1929 const char *file,
1930 int line,
1931 const char *func,
1932 const char *expr,
1933 long double arg1,
1934 const char *cmp,
1935 long double arg2,
1936 char numtype)
1938 char *s = NULL;
1940 switch (numtype)
1942 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;
1943 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;
1944 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr, (double) arg1, cmp, (double) arg2); break;
1945 /* ideally use: floats=%.7g double=%.17g */
1947 g_assertion_message (domain, file, line, func, s);
1948 g_free (s);
1951 void
1952 g_assertion_message_cmpstr (const char *domain,
1953 const char *file,
1954 int line,
1955 const char *func,
1956 const char *expr,
1957 const char *arg1,
1958 const char *cmp,
1959 const char *arg2)
1961 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1962 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1963 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1964 g_free (t1);
1965 g_free (t2);
1966 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1967 g_free (a1);
1968 g_free (a2);
1969 g_assertion_message (domain, file, line, func, s);
1970 g_free (s);
1973 void
1974 g_assertion_message_error (const char *domain,
1975 const char *file,
1976 int line,
1977 const char *func,
1978 const char *expr,
1979 const GError *error,
1980 GQuark error_domain,
1981 int error_code)
1983 GString *gstring;
1985 /* This is used by both g_assert_error() and g_assert_no_error(), so there
1986 * are three cases: expected an error but got the wrong error, expected
1987 * an error but got no error, and expected no error but got an error.
1990 gstring = g_string_new ("assertion failed ");
1991 if (error_domain)
1992 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
1993 g_quark_to_string (error_domain), error_code);
1994 else
1995 g_string_append_printf (gstring, "(%s == NULL): ", expr);
1997 if (error)
1998 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
1999 g_quark_to_string (error->domain), error->code);
2000 else
2001 g_string_append_printf (gstring, "%s is NULL", expr);
2003 g_assertion_message (domain, file, line, func, gstring->str);
2004 g_string_free (gstring, TRUE);
2008 * g_strcmp0:
2009 * @str1: (allow-none): a C string or %NULL
2010 * @str2: (allow-none): another C string or %NULL
2012 * Compares @str1 and @str2 like strcmp(). Handles %NULL
2013 * gracefully by sorting it before non-%NULL strings.
2014 * Comparing two %NULL pointers returns 0.
2016 * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
2018 * Since: 2.16
2021 g_strcmp0 (const char *str1,
2022 const char *str2)
2024 if (!str1)
2025 return -(str1 != str2);
2026 if (!str2)
2027 return str1 != str2;
2028 return strcmp (str1, str2);
2031 #ifdef G_OS_UNIX
2032 static int /* 0 on success */
2033 kill_child (int pid,
2034 int *status,
2035 int patience)
2037 int wr;
2038 if (patience >= 3) /* try graceful reap */
2040 if (waitpid (pid, status, WNOHANG) > 0)
2041 return 0;
2043 if (patience >= 2) /* try SIGHUP */
2045 kill (pid, SIGHUP);
2046 if (waitpid (pid, status, WNOHANG) > 0)
2047 return 0;
2048 g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
2049 if (waitpid (pid, status, WNOHANG) > 0)
2050 return 0;
2051 g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
2052 if (waitpid (pid, status, WNOHANG) > 0)
2053 return 0;
2054 g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
2055 if (waitpid (pid, status, WNOHANG) > 0)
2056 return 0;
2058 if (patience >= 1) /* try SIGTERM */
2060 kill (pid, SIGTERM);
2061 if (waitpid (pid, status, WNOHANG) > 0)
2062 return 0;
2063 g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
2064 if (waitpid (pid, status, WNOHANG) > 0)
2065 return 0;
2066 g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
2067 if (waitpid (pid, status, WNOHANG) > 0)
2068 return 0;
2070 /* finish it off */
2071 kill (pid, SIGKILL);
2073 wr = waitpid (pid, status, 0);
2074 while (wr < 0 && errno == EINTR);
2075 return wr;
2077 #endif
2079 static inline int
2080 g_string_must_read (GString *gstring,
2081 int fd)
2083 #define STRING_BUFFER_SIZE 4096
2084 char buf[STRING_BUFFER_SIZE];
2085 gssize bytes;
2086 again:
2087 bytes = read (fd, buf, sizeof (buf));
2088 if (bytes == 0)
2089 return 0; /* EOF, calling this function assumes data is available */
2090 else if (bytes > 0)
2092 g_string_append_len (gstring, buf, bytes);
2093 return 1;
2095 else if (bytes < 0 && errno == EINTR)
2096 goto again;
2097 else /* bytes < 0 */
2099 g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2100 return 1; /* ignore error after warning */
2104 static inline void
2105 g_string_write_out (GString *gstring,
2106 int outfd,
2107 int *stringpos)
2109 if (*stringpos < gstring->len)
2111 int r;
2113 r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
2114 while (r < 0 && errno == EINTR);
2115 *stringpos += MAX (r, 0);
2119 static void
2120 test_trap_clear (void)
2122 test_trap_last_status = 0;
2123 test_trap_last_pid = 0;
2124 g_free (test_trap_last_stdout);
2125 test_trap_last_stdout = NULL;
2126 g_free (test_trap_last_stderr);
2127 test_trap_last_stderr = NULL;
2130 #ifdef G_OS_UNIX
2132 static int
2133 sane_dup2 (int fd1,
2134 int fd2)
2136 int ret;
2138 ret = dup2 (fd1, fd2);
2139 while (ret < 0 && errno == EINTR);
2140 return ret;
2143 static guint64
2144 test_time_stamp (void)
2146 GTimeVal tv;
2147 guint64 stamp;
2148 g_get_current_time (&tv);
2149 stamp = tv.tv_sec;
2150 stamp = stamp * 1000000 + tv.tv_usec;
2151 return stamp;
2154 #endif
2157 * g_test_trap_fork:
2158 * @usec_timeout: Timeout for the forked test in micro seconds.
2159 * @test_trap_flags: Flags to modify forking behaviour.
2161 * Fork the current test program to execute a test case that might
2162 * not return or that might abort. The forked test case is aborted
2163 * and considered failing if its run time exceeds @usec_timeout.
2165 * The forking behavior can be configured with the #GTestTrapFlags flags.
2167 * In the following example, the test code forks, the forked child
2168 * process produces some sample output and exits successfully.
2169 * The forking parent process then asserts successful child program
2170 * termination and validates child program outputs.
2172 * |[
2173 * static void
2174 * test_fork_patterns (void)
2176 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2178 * g_print ("some stdout text: somagic17\n");
2179 * g_printerr ("some stderr text: semagic43\n");
2180 * exit (0); /&ast; successful test run &ast;/
2182 * g_test_trap_assert_passed();
2183 * g_test_trap_assert_stdout ("*somagic17*");
2184 * g_test_trap_assert_stderr ("*semagic43*");
2186 * ]|
2188 * This function is implemented only on Unix platforms.
2190 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2192 * Since: 2.16
2194 gboolean
2195 g_test_trap_fork (guint64 usec_timeout,
2196 GTestTrapFlags test_trap_flags)
2198 #ifdef G_OS_UNIX
2199 gboolean pass_on_forked_log = FALSE;
2200 int stdout_pipe[2] = { -1, -1 };
2201 int stderr_pipe[2] = { -1, -1 };
2202 int stdtst_pipe[2] = { -1, -1 };
2203 test_trap_clear();
2204 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
2205 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
2206 signal (SIGCHLD, SIG_DFL);
2207 test_trap_last_pid = fork ();
2208 if (test_trap_last_pid < 0)
2209 g_error ("failed to fork test program: %s", g_strerror (errno));
2210 if (test_trap_last_pid == 0) /* child */
2212 int fd0 = -1;
2213 close (stdout_pipe[0]);
2214 close (stderr_pipe[0]);
2215 close (stdtst_pipe[0]);
2216 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2217 fd0 = g_open ("/dev/null", O_RDONLY, 0);
2218 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2219 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
2220 if (fd0 >= 3)
2221 close (fd0);
2222 if (stdout_pipe[1] >= 3)
2223 close (stdout_pipe[1]);
2224 if (stderr_pipe[1] >= 3)
2225 close (stderr_pipe[1]);
2226 test_log_fd = stdtst_pipe[1];
2227 return TRUE;
2229 else /* parent */
2231 GString *sout = g_string_new (NULL);
2232 GString *serr = g_string_new (NULL);
2233 guint64 sstamp;
2234 int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
2235 test_run_forks++;
2236 close (stdout_pipe[1]);
2237 close (stderr_pipe[1]);
2238 close (stdtst_pipe[1]);
2239 sstamp = test_time_stamp();
2240 /* read data until we get EOF on all pipes */
2241 while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
2243 fd_set fds;
2244 struct timeval tv;
2245 int ret;
2246 FD_ZERO (&fds);
2247 if (stdout_pipe[0] >= 0)
2248 FD_SET (stdout_pipe[0], &fds);
2249 if (stderr_pipe[0] >= 0)
2250 FD_SET (stderr_pipe[0], &fds);
2251 if (stdtst_pipe[0] >= 0)
2252 FD_SET (stdtst_pipe[0], &fds);
2253 tv.tv_sec = 0;
2254 tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
2255 ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
2256 if (ret < 0 && errno != EINTR)
2258 g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2259 break;
2261 if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
2262 g_string_must_read (sout, stdout_pipe[0]) == 0)
2264 close (stdout_pipe[0]);
2265 stdout_pipe[0] = -1;
2267 if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
2268 g_string_must_read (serr, stderr_pipe[0]) == 0)
2270 close (stderr_pipe[0]);
2271 stderr_pipe[0] = -1;
2273 if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
2275 guint8 buffer[4096];
2276 gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
2277 if (r > 0 && test_log_fd > 0)
2279 l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
2280 while (l < 0 && errno == EINTR);
2281 if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
2283 close (stdtst_pipe[0]);
2284 stdtst_pipe[0] = -1;
2287 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
2288 g_string_write_out (sout, 1, &soutpos);
2289 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
2290 g_string_write_out (serr, 2, &serrpos);
2291 if (usec_timeout)
2293 guint64 nstamp = test_time_stamp();
2294 int status = 0;
2295 sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
2296 if (usec_timeout < nstamp - sstamp)
2298 /* timeout reached, need to abort the child now */
2299 kill_child (test_trap_last_pid, &status, 3);
2300 test_trap_last_status = 1024; /* timeout */
2301 if (0 && WIFSIGNALED (status))
2302 g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
2303 need_wait = FALSE;
2304 break;
2308 if (stdout_pipe[0] != -1)
2309 close (stdout_pipe[0]);
2310 if (stderr_pipe[0] != -1)
2311 close (stderr_pipe[0]);
2312 if (stdtst_pipe[0] != -1)
2313 close (stdtst_pipe[0]);
2314 if (need_wait)
2316 int status = 0;
2318 wr = waitpid (test_trap_last_pid, &status, 0);
2319 while (wr < 0 && errno == EINTR);
2320 if (WIFEXITED (status)) /* normal exit */
2321 test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
2322 else if (WIFSIGNALED (status))
2323 test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
2324 else /* WCOREDUMP (status) */
2325 test_trap_last_status = 512; /* coredump */
2327 test_trap_last_stdout = g_string_free (sout, FALSE);
2328 test_trap_last_stderr = g_string_free (serr, FALSE);
2329 return FALSE;
2331 #else
2332 g_message ("Not implemented: g_test_trap_fork");
2334 return FALSE;
2335 #endif
2339 * g_test_trap_has_passed:
2341 * Check the result of the last g_test_trap_fork() call.
2343 * Returns: %TRUE if the last forked child terminated successfully.
2345 * Since: 2.16
2347 gboolean
2348 g_test_trap_has_passed (void)
2350 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
2354 * g_test_trap_reached_timeout:
2356 * Check the result of the last g_test_trap_fork() call.
2358 * Returns: %TRUE if the last forked child got killed due to a fork timeout.
2360 * Since: 2.16
2362 gboolean
2363 g_test_trap_reached_timeout (void)
2365 return 0 != (test_trap_last_status & 1024); /* timeout flag */
2368 void
2369 g_test_trap_assertions (const char *domain,
2370 const char *file,
2371 int line,
2372 const char *func,
2373 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
2374 const char *pattern)
2376 #ifdef G_OS_UNIX
2377 gboolean must_pass = assertion_flags == 0;
2378 gboolean must_fail = assertion_flags == 1;
2379 gboolean match_result = 0 == (assertion_flags & 1);
2380 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
2381 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
2382 const char *match_error = match_result ? "failed to match" : "contains invalid match";
2383 if (test_trap_last_pid == 0)
2384 g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
2385 if (must_pass && !g_test_trap_has_passed())
2387 char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
2388 g_assertion_message (domain, file, line, func, msg);
2389 g_free (msg);
2391 if (must_fail && g_test_trap_has_passed())
2393 char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
2394 g_assertion_message (domain, file, line, func, msg);
2395 g_free (msg);
2397 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
2399 char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
2400 g_assertion_message (domain, file, line, func, msg);
2401 g_free (msg);
2403 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
2405 char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
2406 g_assertion_message (domain, file, line, func, msg);
2407 g_free (msg);
2409 #endif
2412 static void
2413 gstring_overwrite_int (GString *gstring,
2414 guint pos,
2415 guint32 vuint)
2417 vuint = g_htonl (vuint);
2418 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
2421 static void
2422 gstring_append_int (GString *gstring,
2423 guint32 vuint)
2425 vuint = g_htonl (vuint);
2426 g_string_append_len (gstring, (const gchar*) &vuint, 4);
2429 static void
2430 gstring_append_double (GString *gstring,
2431 double vdouble)
2433 union { double vdouble; guint64 vuint64; } u;
2434 u.vdouble = vdouble;
2435 u.vuint64 = GUINT64_TO_BE (u.vuint64);
2436 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
2439 static guint8*
2440 g_test_log_dump (GTestLogMsg *msg,
2441 guint *len)
2443 GString *gstring = g_string_sized_new (1024);
2444 guint ui;
2445 gstring_append_int (gstring, 0); /* message length */
2446 gstring_append_int (gstring, msg->log_type);
2447 gstring_append_int (gstring, msg->n_strings);
2448 gstring_append_int (gstring, msg->n_nums);
2449 gstring_append_int (gstring, 0); /* reserved */
2450 for (ui = 0; ui < msg->n_strings; ui++)
2452 guint l = strlen (msg->strings[ui]);
2453 gstring_append_int (gstring, l);
2454 g_string_append_len (gstring, msg->strings[ui], l);
2456 for (ui = 0; ui < msg->n_nums; ui++)
2457 gstring_append_double (gstring, msg->nums[ui]);
2458 *len = gstring->len;
2459 gstring_overwrite_int (gstring, 0, *len); /* message length */
2460 return (guint8*) g_string_free (gstring, FALSE);
2463 static inline long double
2464 net_double (const gchar **ipointer)
2466 union { guint64 vuint64; double vdouble; } u;
2467 guint64 aligned_int64;
2468 memcpy (&aligned_int64, *ipointer, 8);
2469 *ipointer += 8;
2470 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
2471 return u.vdouble;
2474 static inline guint32
2475 net_int (const gchar **ipointer)
2477 guint32 aligned_int;
2478 memcpy (&aligned_int, *ipointer, 4);
2479 *ipointer += 4;
2480 return g_ntohl (aligned_int);
2483 static gboolean
2484 g_test_log_extract (GTestLogBuffer *tbuffer)
2486 const gchar *p = tbuffer->data->str;
2487 GTestLogMsg msg;
2488 guint mlength;
2489 if (tbuffer->data->len < 4 * 5)
2490 return FALSE;
2491 mlength = net_int (&p);
2492 if (tbuffer->data->len < mlength)
2493 return FALSE;
2494 msg.log_type = net_int (&p);
2495 msg.n_strings = net_int (&p);
2496 msg.n_nums = net_int (&p);
2497 if (net_int (&p) == 0)
2499 guint ui;
2500 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
2501 msg.nums = g_new0 (long double, msg.n_nums);
2502 for (ui = 0; ui < msg.n_strings; ui++)
2504 guint sl = net_int (&p);
2505 msg.strings[ui] = g_strndup (p, sl);
2506 p += sl;
2508 for (ui = 0; ui < msg.n_nums; ui++)
2509 msg.nums[ui] = net_double (&p);
2510 if (p <= tbuffer->data->str + mlength)
2512 g_string_erase (tbuffer->data, 0, mlength);
2513 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
2514 return TRUE;
2517 g_free (msg.nums);
2518 g_strfreev (msg.strings);
2519 g_error ("corrupt log stream from test program");
2520 return FALSE;
2524 * g_test_log_buffer_new:
2526 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2528 GTestLogBuffer*
2529 g_test_log_buffer_new (void)
2531 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
2532 tb->data = g_string_sized_new (1024);
2533 return tb;
2537 * g_test_log_buffer_free:
2539 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2541 void
2542 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
2544 g_return_if_fail (tbuffer != NULL);
2545 while (tbuffer->msgs)
2546 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
2547 g_string_free (tbuffer->data, TRUE);
2548 g_free (tbuffer);
2552 * g_test_log_buffer_push:
2554 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2556 void
2557 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
2558 guint n_bytes,
2559 const guint8 *bytes)
2561 g_return_if_fail (tbuffer != NULL);
2562 if (n_bytes)
2564 gboolean more_messages;
2565 g_return_if_fail (bytes != NULL);
2566 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
2568 more_messages = g_test_log_extract (tbuffer);
2569 while (more_messages);
2574 * g_test_log_buffer_pop:
2576 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
2578 GTestLogMsg*
2579 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
2581 GTestLogMsg *msg = NULL;
2582 g_return_val_if_fail (tbuffer != NULL, NULL);
2583 if (tbuffer->msgs)
2585 GSList *slist = g_slist_last (tbuffer->msgs);
2586 msg = slist->data;
2587 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
2589 return msg;
2593 * g_test_log_msg_free:
2595 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2597 void
2598 g_test_log_msg_free (GTestLogMsg *tmsg)
2600 g_return_if_fail (tmsg != NULL);
2601 g_strfreev (tmsg->strings);
2602 g_free (tmsg->nums);
2603 g_free (tmsg);
2606 /* --- macros docs START --- */
2608 * g_test_add:
2609 * @testpath: The test path for a new test case.
2610 * @Fixture: The type of a fixture data structure.
2611 * @tdata: Data argument for the test functions.
2612 * @fsetup: The function to set up the fixture data.
2613 * @ftest: The actual test function.
2614 * @fteardown: The function to tear down the fixture data.
2616 * Hook up a new test case at @testpath, similar to g_test_add_func().
2617 * A fixture data structure with setup and teardown function may be provided
2618 * though, similar to g_test_create_case().
2619 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2620 * fteardown() callbacks can expect a @Fixture pointer as first argument in
2621 * a type safe manner.
2623 * Since: 2.16
2625 /* --- macros docs END --- */