tests: Fix leak when checking for du binary
[glib.git] / glib / gtestutils.c
blob93f2ba0959b8754c6714920a9be0492ef7a4a4dc
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.1 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, see <http://www.gnu.org/licenses/>.
19 #include "config.h"
21 #include "gtestutils.h"
22 #include "gfileutils.h"
24 #include <sys/types.h>
25 #ifdef G_OS_UNIX
26 #include <sys/wait.h>
27 #include <sys/time.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <glib/gstdio.h>
31 #endif
32 #include <string.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #ifdef HAVE_SYS_RESOURCE_H
36 #include <sys/resource.h>
37 #endif
38 #ifdef G_OS_WIN32
39 #include <io.h>
40 #include <windows.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"
54 #include "gspawn.h"
55 #include "glib-private.h"
58 /**
59 * SECTION:testing
60 * @title: Testing
61 * @short_description: a test framework
62 * @see_also: [gtester][gtester], [gtester-report][gtester-report]
64 * GLib provides a framework for writing and maintaining unit tests
65 * in parallel to the code they are testing. The API is designed according
66 * to established concepts found in the other test frameworks (JUnit, NUnit,
67 * RUnit), which in turn is based on smalltalk unit testing concepts.
69 * - Test case: Tests (test methods) are grouped together with their
70 * fixture into test cases.
72 * - Fixture: A test fixture consists of fixture data and setup and
73 * teardown methods to establish the environment for the test
74 * functions. We use fresh fixtures, i.e. fixtures are newly set
75 * up and torn down around each test invocation to avoid dependencies
76 * between tests.
78 * - Test suite: Test cases can be grouped into test suites, to allow
79 * subsets of the available tests to be run. Test suites can be
80 * grouped into other test suites as well.
82 * The API is designed to handle creation and registration of test suites
83 * and test cases implicitly. A simple call like
84 * |[<!-- language="C" -->
85 * g_test_add_func ("/misc/assertions", test_assertions);
86 * ]|
87 * creates a test suite called "misc" with a single test case named
88 * "assertions", which consists of running the test_assertions function.
90 * In addition to the traditional g_assert(), the test framework provides
91 * an extended set of assertions for comparisons: g_assert_cmpfloat(),
92 * g_assert_cmpfloat_with_epsilon(), g_assert_cmpint(), g_assert_cmpuint(),
93 * g_assert_cmphex(), g_assert_cmpstr(), and g_assert_cmpmem(). The
94 * advantage of these variants over plain g_assert() is that the assertion
95 * messages can be more elaborate, and include the values of the compared
96 * entities.
98 * A full example of creating a test suite with two tests using fixtures:
99 * |[<!-- language="C" -->
100 * #include <glib.h>
101 * #include <locale.h>
103 * typedef struct {
104 * MyObject *obj;
105 * OtherObject *helper;
106 * } MyObjectFixture;
108 * static void
109 * my_object_fixture_set_up (MyObjectFixture *fixture,
110 * gconstpointer user_data)
112 * fixture->obj = my_object_new ();
113 * my_object_set_prop1 (fixture->obj, "some-value");
114 * my_object_do_some_complex_setup (fixture->obj, user_data);
116 * fixture->helper = other_object_new ();
119 * static void
120 * my_object_fixture_tear_down (MyObjectFixture *fixture,
121 * gconstpointer user_data)
123 * g_clear_object (&fixture->helper);
124 * g_clear_object (&fixture->obj);
127 * static void
128 * test_my_object_test1 (MyObjectFixture *fixture,
129 * gconstpointer user_data)
131 * g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "initial-value");
134 * static void
135 * test_my_object_test2 (MyObjectFixture *fixture,
136 * gconstpointer user_data)
138 * my_object_do_some_work_using_helper (fixture->obj, fixture->helper);
139 * g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "updated-value");
142 * int
143 * main (int argc, char *argv[])
145 * setlocale (LC_ALL, "");
147 * g_test_init (&argc, &argv, NULL);
148 * g_test_bug_base ("http://bugzilla.gnome.org/show_bug.cgi?id=");
150 * // Define the tests.
151 * g_test_add ("/my-object/test1", MyObjectFixture, "some-user-data",
152 * my_object_fixture_set_up, test_my_object_test1,
153 * my_object_fixture_tear_down);
154 * g_test_add ("/my-object/test2", MyObjectFixture, "some-user-data",
155 * my_object_fixture_set_up, test_my_object_test2,
156 * my_object_fixture_tear_down);
158 * return g_test_run ();
160 * ]|
162 * ### Integrating GTest in your project
164 * If you are using the [Meson](http://mesonbuild.com) build system, you will
165 * typically use the provided `test()` primitive to call the test binaries,
166 * e.g.:
168 * |[<!-- language="plain" -->
169 * test(
170 * 'foo',
171 * executable('foo', 'foo.c', dependencies: deps),
172 * env: [
173 * 'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
174 * 'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
175 * ],
178 * test(
179 * 'bar',
180 * executable('bar', 'bar.c', dependencies: deps),
181 * env: [
182 * 'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
183 * 'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
184 * ],
186 * ]|
188 * If you are using Autotools, you're strongly encouraged to use the Automake
189 * [TAP](https://testanything.org/) harness; GLib provides template files for
190 * easily integrating with it:
192 * - [glib-tap.mk](https://git.gnome.org/browse/glib/tree/glib-tap.mk)
193 * - [tap-test](https://git.gnome.org/browse/glib/tree/tap-test)
194 * - [tap-driver.sh](https://git.gnome.org/browse/glib/tree/tap-driver.sh)
196 * You can copy these files in your own project's root directory, and then
197 * set up your `Makefile.am` file to reference them, for instance:
199 * |[<!-- language="plain" -->
200 * include $(top_srcdir)/glib-tap.mk
202 * # test binaries
203 * test_programs = \
204 * foo \
205 * bar
207 * # data distributed in the tarball
208 * dist_test_data = \
209 * foo.data.txt \
210 * bar.data.txt
212 * # data not distributed in the tarball
213 * test_data = \
214 * blah.data.txt
215 * ]|
217 * Make sure to distribute the TAP files, using something like the following
218 * in your top-level `Makefile.am`:
220 * |[<!-- language="plain" -->
221 * EXTRA_DIST += \
222 * tap-driver.sh \
223 * tap-test
224 * ]|
226 * `glib-tap.mk` will be distributed implicitly due to being included in a
227 * `Makefile.am`. All three files should be added to version control.
229 * If you don't have access to the Autotools TAP harness, you can use the
230 * [gtester][gtester] and [gtester-report][gtester-report] tools, and use
231 * the [glib.mk](https://git.gnome.org/browse/glib/tree/glib.mk) Automake
232 * template provided by GLib.
236 * g_test_initialized:
238 * Returns %TRUE if g_test_init() has been called.
240 * Returns: %TRUE if g_test_init() has been called.
242 * Since: 2.36
246 * g_test_quick:
248 * Returns %TRUE if tests are run in quick mode.
249 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
250 * there is no "medium speed".
252 * By default, tests are run in quick mode. In tests that use
253 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
254 * can be used to change this.
256 * Returns: %TRUE if in quick mode
260 * g_test_slow:
262 * Returns %TRUE if tests are run in slow mode.
263 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
264 * there is no "medium speed".
266 * By default, tests are run in quick mode. In tests that use
267 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
268 * can be used to change this.
270 * Returns: the opposite of g_test_quick()
274 * g_test_thorough:
276 * Returns %TRUE if tests are run in thorough mode, equivalent to
277 * g_test_slow().
279 * By default, tests are run in quick mode. In tests that use
280 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
281 * can be used to change this.
283 * Returns: the same thing as g_test_slow()
287 * g_test_perf:
289 * Returns %TRUE if tests are run in performance mode.
291 * By default, tests are run in quick mode. In tests that use
292 * g_test_init(), the option `-m perf` enables performance tests, while
293 * `-m quick` disables them.
295 * Returns: %TRUE if in performance mode
299 * g_test_undefined:
301 * Returns %TRUE if tests may provoke assertions and other formally-undefined
302 * behaviour, to verify that appropriate warnings are given. It might, in some
303 * cases, be useful to turn this off with if running tests under valgrind;
304 * in tests that use g_test_init(), the option `-m no-undefined` disables
305 * those tests, while `-m undefined` explicitly enables them (the default
306 * behaviour).
308 * Returns: %TRUE if tests may provoke programming errors
312 * g_test_verbose:
314 * Returns %TRUE if tests are run in verbose mode.
315 * In tests that use g_test_init(), the option `--verbose` enables this,
316 * while `-q` or `--quiet` disables it.
317 * The default is neither g_test_verbose() nor g_test_quiet().
319 * Returns: %TRUE if in verbose mode
323 * g_test_quiet:
325 * Returns %TRUE if tests are run in quiet mode.
326 * In tests that use g_test_init(), the option `-q` or `--quiet` enables
327 * this, while `--verbose` disables it.
328 * The default is neither g_test_verbose() nor g_test_quiet().
330 * Returns: %TRUE if in quiet mode
334 * g_test_queue_unref:
335 * @gobject: the object to unref
337 * Enqueue an object to be released with g_object_unref() during
338 * the next teardown phase. This is equivalent to calling
339 * g_test_queue_destroy() with a destroy callback of g_object_unref().
341 * Since: 2.16
345 * GTestTrapFlags:
346 * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
347 * `/dev/null` so it cannot be observed on the console during test
348 * runs. The actual output is still captured though to allow later
349 * tests with g_test_trap_assert_stdout().
350 * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
351 * `/dev/null` so it cannot be observed on the console during test
352 * runs. The actual output is still captured though to allow later
353 * tests with g_test_trap_assert_stderr().
354 * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
355 * child process is shared with stdin of its parent process.
356 * It is redirected to `/dev/null` otherwise.
358 * Test traps are guards around forked tests.
359 * These flags determine what traps to set.
361 * Deprecated: #GTestTrapFlags is used only with g_test_trap_fork(),
362 * which is deprecated. g_test_trap_subprocess() uses
363 * #GTestSubprocessFlags.
367 * GTestSubprocessFlags:
368 * @G_TEST_SUBPROCESS_INHERIT_STDIN: If this flag is given, the child
369 * process will inherit the parent's stdin. Otherwise, the child's
370 * stdin is redirected to `/dev/null`.
371 * @G_TEST_SUBPROCESS_INHERIT_STDOUT: If this flag is given, the child
372 * process will inherit the parent's stdout. Otherwise, the child's
373 * stdout will not be visible, but it will be captured to allow
374 * later tests with g_test_trap_assert_stdout().
375 * @G_TEST_SUBPROCESS_INHERIT_STDERR: If this flag is given, the child
376 * process will inherit the parent's stderr. Otherwise, the child's
377 * stderr will not be visible, but it will be captured to allow
378 * later tests with g_test_trap_assert_stderr().
380 * Flags to pass to g_test_trap_subprocess() to control input and output.
382 * Note that in contrast with g_test_trap_fork(), the default is to
383 * not show stdout and stderr.
387 * g_test_trap_assert_passed:
389 * Assert that the last test subprocess passed.
390 * See g_test_trap_subprocess().
392 * Since: 2.16
396 * g_test_trap_assert_failed:
398 * Assert that the last test subprocess failed.
399 * See g_test_trap_subprocess().
401 * This is sometimes used to test situations that are formally considered to
402 * be undefined behaviour, like inputs that fail a g_return_if_fail()
403 * check. In these situations you should skip the entire test, including the
404 * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
405 * to indicate that undefined behaviour may be tested.
407 * Since: 2.16
411 * g_test_trap_assert_stdout:
412 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
414 * Assert that the stdout output of the last test subprocess matches
415 * @soutpattern. See g_test_trap_subprocess().
417 * Since: 2.16
421 * g_test_trap_assert_stdout_unmatched:
422 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
424 * Assert that the stdout output of the last test subprocess
425 * does not match @soutpattern. See g_test_trap_subprocess().
427 * Since: 2.16
431 * g_test_trap_assert_stderr:
432 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
434 * Assert that the stderr output of the last test subprocess
435 * matches @serrpattern. See g_test_trap_subprocess().
437 * This is sometimes used to test situations that are formally
438 * considered to be undefined behaviour, like code that hits a
439 * g_assert() or g_error(). In these situations you should skip the
440 * entire test, including the call to g_test_trap_subprocess(), unless
441 * g_test_undefined() returns %TRUE to indicate that undefined
442 * behaviour may be tested.
444 * Since: 2.16
448 * g_test_trap_assert_stderr_unmatched:
449 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
451 * Assert that the stderr output of the last test subprocess
452 * does not match @serrpattern. See g_test_trap_subprocess().
454 * Since: 2.16
458 * g_test_rand_bit:
460 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
461 * for details on test case random numbers.
463 * Since: 2.16
467 * g_assert:
468 * @expr: the expression to check
470 * Debugging macro to terminate the application if the assertion
471 * fails. If the assertion fails (i.e. the expression is not true),
472 * an error message is logged and the application is terminated.
474 * The macro can be turned off in final releases of code by defining
475 * `G_DISABLE_ASSERT` when compiling the application, so code must
476 * not depend on any side effects from @expr.
480 * g_assert_not_reached:
482 * Debugging macro to terminate the application if it is ever
483 * reached. If it is reached, an error message is logged and the
484 * application is terminated.
486 * The macro can be turned off in final releases of code by defining
487 * `G_DISABLE_ASSERT` when compiling the application.
491 * g_assert_true:
492 * @expr: the expression to check
494 * Debugging macro to check that an expression is true.
496 * If the assertion fails (i.e. the expression is not true),
497 * an error message is logged and the application is either
498 * terminated or the testcase marked as failed.
500 * See g_test_set_nonfatal_assertions().
502 * Since: 2.38
506 * g_assert_false:
507 * @expr: the expression to check
509 * Debugging macro to check an expression is false.
511 * If the assertion fails (i.e. the expression is not false),
512 * an error message is logged and the application is either
513 * terminated or the testcase marked as failed.
515 * See g_test_set_nonfatal_assertions().
517 * Since: 2.38
521 * g_assert_null:
522 * @expr: the expression to check
524 * Debugging macro to check an expression is %NULL.
526 * If the assertion fails (i.e. the expression is not %NULL),
527 * an error message is logged and the application is either
528 * terminated or the testcase marked as failed.
530 * See g_test_set_nonfatal_assertions().
532 * Since: 2.38
536 * g_assert_nonnull:
537 * @expr: the expression to check
539 * Debugging macro to check an expression is not %NULL.
541 * If the assertion fails (i.e. the expression is %NULL),
542 * an error message is logged and the application is either
543 * terminated or the testcase marked as failed.
545 * See g_test_set_nonfatal_assertions().
547 * Since: 2.40
551 * g_assert_cmpstr:
552 * @s1: a string (may be %NULL)
553 * @cmp: The comparison operator to use.
554 * One of ==, !=, <, >, <=, >=.
555 * @s2: another string (may be %NULL)
557 * Debugging macro to compare two strings. If the comparison fails,
558 * an error message is logged and the application is either terminated
559 * or the testcase marked as failed.
560 * The strings are compared using g_strcmp0().
562 * The effect of `g_assert_cmpstr (s1, op, s2)` is
563 * the same as `g_assert_true (g_strcmp0 (s1, s2) op 0)`.
564 * The advantage of this macro is that it can produce a message that
565 * includes the actual values of @s1 and @s2.
567 * |[<!-- language="C" -->
568 * g_assert_cmpstr (mystring, ==, "fubar");
569 * ]|
571 * Since: 2.16
575 * g_assert_cmpint:
576 * @n1: an integer
577 * @cmp: The comparison operator to use.
578 * One of ==, !=, <, >, <=, >=.
579 * @n2: another integer
581 * Debugging macro to compare two integers.
583 * The effect of `g_assert_cmpint (n1, op, n2)` is
584 * the same as `g_assert_true (n1 op n2)`. The advantage
585 * of this macro is that it can produce a message that includes the
586 * actual values of @n1 and @n2.
588 * Since: 2.16
592 * g_assert_cmpuint:
593 * @n1: an unsigned integer
594 * @cmp: The comparison operator to use.
595 * One of ==, !=, <, >, <=, >=.
596 * @n2: another unsigned integer
598 * Debugging macro to compare two unsigned integers.
600 * The effect of `g_assert_cmpuint (n1, op, n2)` is
601 * the same as `g_assert_true (n1 op n2)`. The advantage
602 * of this macro is that it can produce a message that includes the
603 * actual values of @n1 and @n2.
605 * Since: 2.16
609 * g_assert_cmphex:
610 * @n1: an unsigned integer
611 * @cmp: The comparison operator to use.
612 * One of ==, !=, <, >, <=, >=.
613 * @n2: another unsigned integer
615 * Debugging macro to compare to unsigned integers.
617 * This is a variant of g_assert_cmpuint() that displays the numbers
618 * in hexadecimal notation in the message.
620 * Since: 2.16
624 * g_assert_cmpfloat:
625 * @n1: an floating point number
626 * @cmp: The comparison operator to use.
627 * One of ==, !=, <, >, <=, >=.
628 * @n2: another floating point number
630 * Debugging macro to compare two floating point numbers.
632 * The effect of `g_assert_cmpfloat (n1, op, n2)` is
633 * the same as `g_assert_true (n1 op n2)`. The advantage
634 * of this macro is that it can produce a message that includes the
635 * actual values of @n1 and @n2.
637 * Since: 2.16
641 * g_assert_cmpfloat_with_epsilon:
642 * @n1: an floating point number
643 * @n2: another floating point number
644 * @epsilon: a numeric value that expresses the expected tolerance
645 * between @n1 and @n2
647 * Debugging macro to compare two floating point numbers within an epsilon.
649 * The effect of `g_assert_cmpfloat_with_epsilon (n1, n2, epsilon)` is
650 * the same as `g_assert_true (abs (n1 - n2) < epsilon)`. The advantage
651 * of this macro is that it can produce a message that includes the
652 * actual values of @n1 and @n2.
654 * Since: 2.58
658 * g_assert_cmpmem:
659 * @m1: pointer to a buffer
660 * @l1: length of @m1
661 * @m2: pointer to another buffer
662 * @l2: length of @m2
664 * Debugging macro to compare memory regions. If the comparison fails,
665 * an error message is logged and the application is either terminated
666 * or the testcase marked as failed.
668 * The effect of `g_assert_cmpmem (m1, l1, m2, l2)` is
669 * the same as `g_assert_true (l1 == l2 && memcmp (m1, m2, l1) == 0)`.
670 * The advantage of this macro is that it can produce a message that
671 * includes the actual values of @l1 and @l2.
673 * |[<!-- language="C" -->
674 * g_assert_cmpmem (buf->data, buf->len, expected, sizeof (expected));
675 * ]|
677 * Since: 2.46
681 * g_assert_no_error:
682 * @err: a #GError, possibly %NULL
684 * Debugging macro to check that a #GError is not set.
686 * The effect of `g_assert_no_error (err)` is
687 * the same as `g_assert_true (err == NULL)`. The advantage
688 * of this macro is that it can produce a message that includes
689 * the error message and code.
691 * Since: 2.20
695 * g_assert_error:
696 * @err: a #GError, possibly %NULL
697 * @dom: the expected error domain (a #GQuark)
698 * @c: the expected error code
700 * Debugging macro to check that a method has returned
701 * the correct #GError.
703 * The effect of `g_assert_error (err, dom, c)` is
704 * the same as `g_assert_true (err != NULL && err->domain
705 * == dom && err->code == c)`. The advantage of this
706 * macro is that it can produce a message that includes the incorrect
707 * error message and code.
709 * This can only be used to test for a specific error. If you want to
710 * test that @err is set, but don't care what it's set to, just use
711 * `g_assert (err != NULL)`
713 * Since: 2.20
717 * GTestCase:
719 * An opaque structure representing a test case.
723 * GTestSuite:
725 * An opaque structure representing a test suite.
729 /* Global variable for storing assertion messages; this is the counterpart to
730 * glibc's (private) __abort_msg variable, and allows developers and crash
731 * analysis systems like Apport and ABRT to fish out assertion messages from
732 * core dumps, instead of having to catch them on screen output.
734 GLIB_VAR char *__glib_assert_msg;
735 char *__glib_assert_msg = NULL;
737 /* --- constants --- */
738 #define G_TEST_STATUS_TIMED_OUT 1024
740 /* --- structures --- */
741 struct GTestCase
743 gchar *name;
744 guint fixture_size;
745 void (*fixture_setup) (void*, gconstpointer);
746 void (*fixture_test) (void*, gconstpointer);
747 void (*fixture_teardown) (void*, gconstpointer);
748 gpointer test_data;
750 struct GTestSuite
752 gchar *name;
753 GSList *suites;
754 GSList *cases;
756 typedef struct DestroyEntry DestroyEntry;
757 struct DestroyEntry
759 DestroyEntry *next;
760 GDestroyNotify destroy_func;
761 gpointer destroy_data;
764 /* --- prototypes --- */
765 static void test_run_seed (const gchar *rseed);
766 static void test_trap_clear (void);
767 static guint8* g_test_log_dump (GTestLogMsg *msg,
768 guint *len);
769 static void gtest_default_log_handler (const gchar *log_domain,
770 GLogLevelFlags log_level,
771 const gchar *message,
772 gpointer unused_data);
775 static const char * const g_test_result_names[] = {
776 "OK",
777 "SKIP",
778 "FAIL",
779 "TODO"
782 /* --- variables --- */
783 static int test_log_fd = -1;
784 static gboolean test_mode_fatal = TRUE;
785 static gboolean g_test_run_once = TRUE;
786 static gboolean test_run_list = FALSE;
787 static gchar *test_run_seedstr = NULL;
788 static GRand *test_run_rand = NULL;
789 static gchar *test_run_name = "";
790 static GSList **test_filename_free_list;
791 static guint test_run_forks = 0;
792 static guint test_run_count = 0;
793 static guint test_count = 0;
794 static guint test_skipped_count = 0;
795 static GTestResult test_run_success = G_TEST_RUN_FAILURE;
796 static gchar *test_run_msg = NULL;
797 static guint test_startup_skip_count = 0;
798 static GTimer *test_user_timer = NULL;
799 static double test_user_stamp = 0;
800 static GSList *test_paths = NULL;
801 static GSList *test_paths_skipped = NULL;
802 static GTestSuite *test_suite_root = NULL;
803 static int test_trap_last_status = 0; /* unmodified platform-specific status */
804 static GPid test_trap_last_pid = 0;
805 static char *test_trap_last_subprocess = NULL;
806 static char *test_trap_last_stdout = NULL;
807 static char *test_trap_last_stderr = NULL;
808 static char *test_uri_base = NULL;
809 static gboolean test_debug_log = FALSE;
810 static gboolean test_tap_log = FALSE;
811 static gboolean test_nonfatal_assertions = FALSE;
812 static DestroyEntry *test_destroy_queue = NULL;
813 static char *test_argv0 = NULL;
814 static char *test_argv0_dirname;
815 static const char *test_disted_files_dir;
816 static const char *test_built_files_dir;
817 static char *test_initial_cwd = NULL;
818 static gboolean test_in_forked_child = FALSE;
819 static gboolean test_in_subprocess = FALSE;
820 static GTestConfig mutable_test_config_vars = {
821 FALSE, /* test_initialized */
822 TRUE, /* test_quick */
823 FALSE, /* test_perf */
824 FALSE, /* test_verbose */
825 FALSE, /* test_quiet */
826 TRUE, /* test_undefined */
828 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
829 static gboolean no_g_set_prgname = FALSE;
831 /* --- functions --- */
832 const char*
833 g_test_log_type_name (GTestLogType log_type)
835 switch (log_type)
837 case G_TEST_LOG_NONE: return "none";
838 case G_TEST_LOG_ERROR: return "error";
839 case G_TEST_LOG_START_BINARY: return "binary";
840 case G_TEST_LOG_LIST_CASE: return "list";
841 case G_TEST_LOG_SKIP_CASE: return "skip";
842 case G_TEST_LOG_START_CASE: return "start";
843 case G_TEST_LOG_STOP_CASE: return "stop";
844 case G_TEST_LOG_MIN_RESULT: return "minperf";
845 case G_TEST_LOG_MAX_RESULT: return "maxperf";
846 case G_TEST_LOG_MESSAGE: return "message";
847 case G_TEST_LOG_START_SUITE: return "start suite";
848 case G_TEST_LOG_STOP_SUITE: return "stop suite";
850 return "???";
853 static void
854 g_test_log_send (guint n_bytes,
855 const guint8 *buffer)
857 if (test_log_fd >= 0)
859 int r;
861 r = write (test_log_fd, buffer, n_bytes);
862 while (r < 0 && errno == EINTR);
864 if (test_debug_log)
866 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
867 GTestLogMsg *msg;
868 guint ui;
869 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
870 msg = g_test_log_buffer_pop (lbuffer);
871 g_warn_if_fail (msg != NULL);
872 g_warn_if_fail (lbuffer->data->len == 0);
873 g_test_log_buffer_free (lbuffer);
874 /* print message */
875 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
876 for (ui = 0; ui < msg->n_strings; ui++)
877 g_printerr (":{%s}", msg->strings[ui]);
878 if (msg->n_nums)
880 g_printerr (":(");
881 for (ui = 0; ui < msg->n_nums; ui++)
883 if ((long double) (long) msg->nums[ui] == msg->nums[ui])
884 g_printerr ("%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
885 else
886 g_printerr ("%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
888 g_printerr (")");
890 g_printerr (":LOG*}\n");
891 g_test_log_msg_free (msg);
895 static void
896 g_test_log (GTestLogType lbit,
897 const gchar *string1,
898 const gchar *string2,
899 guint n_args,
900 long double *largs)
902 GTestResult result;
903 gboolean fail;
904 GTestLogMsg msg;
905 gchar *astrings[3] = { NULL, NULL, NULL };
906 guint8 *dbuffer;
907 guint32 dbufferlen;
909 switch (lbit)
911 case G_TEST_LOG_START_BINARY:
912 if (test_tap_log)
913 g_print ("# random seed: %s\n", string2);
914 else if (g_test_verbose ())
915 g_print ("GTest: random seed: %s\n", string2);
916 break;
917 case G_TEST_LOG_START_SUITE:
918 if (test_tap_log)
920 if (string1[0] != 0)
921 g_print ("# Start of %s tests\n", string1);
922 else
923 g_print ("1..%d\n", test_count);
925 break;
926 case G_TEST_LOG_STOP_SUITE:
927 if (test_tap_log)
929 if (string1[0] != 0)
930 g_print ("# End of %s tests\n", string1);
932 break;
933 case G_TEST_LOG_STOP_CASE:
934 result = largs[0];
935 fail = result == G_TEST_RUN_FAILURE;
936 if (test_tap_log)
938 g_print ("%s %d %s", fail ? "not ok" : "ok", test_run_count, string1);
939 if (result == G_TEST_RUN_INCOMPLETE)
940 g_print (" # TODO %s\n", string2 ? string2 : "");
941 else if (result == G_TEST_RUN_SKIPPED)
942 g_print (" # SKIP %s\n", string2 ? string2 : "");
943 else
944 g_print ("\n");
946 else if (g_test_verbose ())
947 g_print ("GTest: result: %s\n", g_test_result_names[result]);
948 else if (!g_test_quiet ())
949 g_print ("%s\n", g_test_result_names[result]);
950 if (fail && test_mode_fatal)
952 if (test_tap_log)
953 g_print ("Bail out!\n");
954 g_abort ();
956 if (result == G_TEST_RUN_SKIPPED)
957 test_skipped_count++;
958 break;
959 case G_TEST_LOG_MIN_RESULT:
960 if (test_tap_log)
961 g_print ("# min perf: %s\n", string1);
962 else if (g_test_verbose ())
963 g_print ("(MINPERF:%s)\n", string1);
964 break;
965 case G_TEST_LOG_MAX_RESULT:
966 if (test_tap_log)
967 g_print ("# max perf: %s\n", string1);
968 else if (g_test_verbose ())
969 g_print ("(MAXPERF:%s)\n", string1);
970 break;
971 case G_TEST_LOG_MESSAGE:
972 if (test_tap_log)
973 g_print ("# %s\n", string1);
974 else if (g_test_verbose ())
975 g_print ("(MSG: %s)\n", string1);
976 break;
977 case G_TEST_LOG_ERROR:
978 if (test_tap_log)
979 g_print ("Bail out! %s\n", string1);
980 else if (g_test_verbose ())
981 g_print ("(ERROR: %s)\n", string1);
982 break;
983 default: ;
986 msg.log_type = lbit;
987 msg.n_strings = (string1 != NULL) + (string1 && string2);
988 msg.strings = astrings;
989 astrings[0] = (gchar*) string1;
990 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
991 msg.n_nums = n_args;
992 msg.nums = largs;
993 dbuffer = g_test_log_dump (&msg, &dbufferlen);
994 g_test_log_send (dbufferlen, dbuffer);
995 g_free (dbuffer);
997 switch (lbit)
999 case G_TEST_LOG_START_CASE:
1000 if (test_tap_log)
1002 else if (g_test_verbose ())
1003 g_print ("GTest: run: %s\n", string1);
1004 else if (!g_test_quiet ())
1005 g_print ("%s: ", string1);
1006 break;
1007 default: ;
1011 /* We intentionally parse the command line without GOptionContext
1012 * because otherwise you would never be able to test it.
1014 static void
1015 parse_args (gint *argc_p,
1016 gchar ***argv_p)
1018 guint argc = *argc_p;
1019 gchar **argv = *argv_p;
1020 guint i, e;
1022 test_argv0 = argv[0];
1023 test_initial_cwd = g_get_current_dir ();
1025 /* parse known args */
1026 for (i = 1; i < argc; i++)
1028 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
1030 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1031 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1032 g_log_set_always_fatal (fatal_mask);
1033 argv[i] = NULL;
1035 else if (strcmp (argv[i], "--keep-going") == 0 ||
1036 strcmp (argv[i], "-k") == 0)
1038 test_mode_fatal = FALSE;
1039 argv[i] = NULL;
1041 else if (strcmp (argv[i], "--debug-log") == 0)
1043 test_debug_log = TRUE;
1044 argv[i] = NULL;
1046 else if (strcmp (argv[i], "--tap") == 0)
1048 test_tap_log = TRUE;
1049 argv[i] = NULL;
1051 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
1053 gchar *equal = argv[i] + 12;
1054 if (*equal == '=')
1055 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
1056 else if (i + 1 < argc)
1058 argv[i++] = NULL;
1059 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
1061 argv[i] = NULL;
1063 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
1065 gchar *equal = argv[i] + 16;
1066 if (*equal == '=')
1067 test_startup_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
1068 else if (i + 1 < argc)
1070 argv[i++] = NULL;
1071 test_startup_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
1073 argv[i] = NULL;
1075 else if (strcmp ("--GTestSubprocess", argv[i]) == 0)
1077 test_in_subprocess = TRUE;
1078 /* We typically expect these child processes to crash, and some
1079 * tests spawn a *lot* of them. Avoid spamming system crash
1080 * collection programs such as systemd-coredump and abrt.
1082 #ifdef HAVE_SYS_RESOURCE_H
1084 struct rlimit limit = { 0, 0 };
1085 (void) setrlimit (RLIMIT_CORE, &limit);
1087 #endif
1088 argv[i] = NULL;
1090 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
1092 gchar *equal = argv[i] + 2;
1093 if (*equal == '=')
1094 test_paths = g_slist_prepend (test_paths, equal + 1);
1095 else if (i + 1 < argc)
1097 argv[i++] = NULL;
1098 test_paths = g_slist_prepend (test_paths, argv[i]);
1100 argv[i] = NULL;
1102 else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
1104 gchar *equal = argv[i] + 2;
1105 if (*equal == '=')
1106 test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
1107 else if (i + 1 < argc)
1109 argv[i++] = NULL;
1110 test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
1112 argv[i] = NULL;
1114 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
1116 gchar *equal = argv[i] + 2;
1117 const gchar *mode = "";
1118 if (*equal == '=')
1119 mode = equal + 1;
1120 else if (i + 1 < argc)
1122 argv[i++] = NULL;
1123 mode = argv[i];
1125 if (strcmp (mode, "perf") == 0)
1126 mutable_test_config_vars.test_perf = TRUE;
1127 else if (strcmp (mode, "slow") == 0)
1128 mutable_test_config_vars.test_quick = FALSE;
1129 else if (strcmp (mode, "thorough") == 0)
1130 mutable_test_config_vars.test_quick = FALSE;
1131 else if (strcmp (mode, "quick") == 0)
1133 mutable_test_config_vars.test_quick = TRUE;
1134 mutable_test_config_vars.test_perf = FALSE;
1136 else if (strcmp (mode, "undefined") == 0)
1137 mutable_test_config_vars.test_undefined = TRUE;
1138 else if (strcmp (mode, "no-undefined") == 0)
1139 mutable_test_config_vars.test_undefined = FALSE;
1140 else
1141 g_error ("unknown test mode: -m %s", mode);
1142 argv[i] = NULL;
1144 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
1146 mutable_test_config_vars.test_quiet = TRUE;
1147 mutable_test_config_vars.test_verbose = FALSE;
1148 argv[i] = NULL;
1150 else if (strcmp ("--verbose", argv[i]) == 0)
1152 mutable_test_config_vars.test_quiet = FALSE;
1153 mutable_test_config_vars.test_verbose = TRUE;
1154 argv[i] = NULL;
1156 else if (strcmp ("-l", argv[i]) == 0)
1158 test_run_list = TRUE;
1159 argv[i] = NULL;
1161 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
1163 gchar *equal = argv[i] + 6;
1164 if (*equal == '=')
1165 test_run_seedstr = equal + 1;
1166 else if (i + 1 < argc)
1168 argv[i++] = NULL;
1169 test_run_seedstr = argv[i];
1171 argv[i] = NULL;
1173 else if (strcmp ("-?", argv[i]) == 0 ||
1174 strcmp ("-h", argv[i]) == 0 ||
1175 strcmp ("--help", argv[i]) == 0)
1177 printf ("Usage:\n"
1178 " %s [OPTION...]\n\n"
1179 "Help Options:\n"
1180 " -h, --help Show help options\n\n"
1181 "Test Options:\n"
1182 " --g-fatal-warnings Make all warnings fatal\n"
1183 " -l List test cases available in a test executable\n"
1184 " -m {perf|slow|thorough|quick} Execute tests according to mode\n"
1185 " -m {undefined|no-undefined} Execute tests according to mode\n"
1186 " -p TESTPATH Only start test cases matching TESTPATH\n"
1187 " -s TESTPATH Skip all tests matching TESTPATH\n"
1188 " --seed=SEEDSTRING Start tests with random seed SEEDSTRING\n"
1189 " --debug-log debug test logging output\n"
1190 " -q, --quiet Run tests quietly\n"
1191 " --verbose Run tests verbosely\n",
1192 argv[0]);
1193 exit (0);
1196 /* collapse argv */
1197 e = 1;
1198 for (i = 1; i < argc; i++)
1199 if (argv[i])
1201 argv[e++] = argv[i];
1202 if (i >= e)
1203 argv[i] = NULL;
1205 *argc_p = e;
1209 * g_test_init:
1210 * @argc: Address of the @argc parameter of the main() function.
1211 * Changed if any arguments were handled.
1212 * @argv: Address of the @argv parameter of main().
1213 * Any parameters understood by g_test_init() stripped before return.
1214 * @...: %NULL-terminated list of special options. Currently the only
1215 * defined option is `"no_g_set_prgname"`, which
1216 * will cause g_test_init() to not call g_set_prgname().
1218 * Initialize the GLib testing framework, e.g. by seeding the
1219 * test random number generator, the name for g_get_prgname()
1220 * and parsing test related command line args.
1222 * So far, the following arguments are understood:
1224 * - `-l`: List test cases available in a test executable.
1225 * - `--seed=SEED`: Provide a random seed to reproduce test
1226 * runs using random numbers.
1227 * - `--verbose`: Run tests verbosely.
1228 * - `-q`, `--quiet`: Run tests quietly.
1229 * - `-p PATH`: Execute all tests matching the given path.
1230 * - `-s PATH`: Skip all tests matching the given path.
1231 * This can also be used to force a test to run that would otherwise
1232 * be skipped (ie, a test whose name contains "/subprocess").
1233 * - `-m {perf|slow|thorough|quick|undefined|no-undefined}`: Execute tests according to these test modes:
1235 * `perf`: Performance tests, may take long and report results (off by default).
1237 * `slow`, `thorough`: Slow and thorough tests, may take quite long and maximize coverage
1238 * (off by default).
1240 * `quick`: Quick tests, should run really quickly and give good coverage (the default).
1242 * `undefined`: Tests for undefined behaviour, may provoke programming errors
1243 * under g_test_trap_subprocess() or g_test_expect_message() to check
1244 * that appropriate assertions or warnings are given (the default).
1246 * `no-undefined`: Avoid tests for undefined behaviour
1248 * - `--debug-log`: Debug test logging output.
1250 * Since: 2.16
1252 void
1253 g_test_init (int *argc,
1254 char ***argv,
1255 ...)
1257 static char seedstr[4 + 4 * 8 + 1];
1258 va_list args;
1259 gpointer option;
1260 /* make warnings and criticals fatal for all test programs */
1261 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1263 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1264 g_log_set_always_fatal (fatal_mask);
1265 /* check caller args */
1266 g_return_if_fail (argc != NULL);
1267 g_return_if_fail (argv != NULL);
1268 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
1269 mutable_test_config_vars.test_initialized = TRUE;
1271 va_start (args, argv);
1272 while ((option = va_arg (args, char *)))
1274 if (g_strcmp0 (option, "no_g_set_prgname") == 0)
1275 no_g_set_prgname = TRUE;
1277 va_end (args);
1279 /* setup random seed string */
1280 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
1281 test_run_seedstr = seedstr;
1283 /* parse args, sets up mode, changes seed, etc. */
1284 parse_args (argc, argv);
1286 if (!g_get_prgname() && !no_g_set_prgname)
1287 g_set_prgname ((*argv)[0]);
1289 /* sanity check */
1290 if (test_tap_log)
1292 if (test_paths || test_startup_skip_count)
1294 /* Not invoking every test (even if SKIPped) breaks the "1..XX" plan */
1295 g_printerr ("%s: -p and --GTestSkipCount options are incompatible with --tap\n",
1296 (*argv)[0]);
1297 exit (1);
1301 /* verify GRand reliability, needed for reliable seeds */
1302 if (1)
1304 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
1305 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
1306 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
1307 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
1308 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
1309 g_rand_free (rg);
1312 /* check rand seed */
1313 test_run_seed (test_run_seedstr);
1315 /* report program start */
1316 g_log_set_default_handler (gtest_default_log_handler, NULL);
1317 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
1319 test_argv0_dirname = g_path_get_dirname (test_argv0);
1321 /* Make sure we get the real dirname that the test was run from */
1322 if (g_str_has_suffix (test_argv0_dirname, "/.libs"))
1324 gchar *tmp;
1325 tmp = g_path_get_dirname (test_argv0_dirname);
1326 g_free (test_argv0_dirname);
1327 test_argv0_dirname = tmp;
1330 test_disted_files_dir = g_getenv ("G_TEST_SRCDIR");
1331 if (!test_disted_files_dir)
1332 test_disted_files_dir = test_argv0_dirname;
1334 test_built_files_dir = g_getenv ("G_TEST_BUILDDIR");
1335 if (!test_built_files_dir)
1336 test_built_files_dir = test_argv0_dirname;
1339 static void
1340 test_run_seed (const gchar *rseed)
1342 guint seed_failed = 0;
1343 if (test_run_rand)
1344 g_rand_free (test_run_rand);
1345 test_run_rand = NULL;
1346 while (strchr (" \t\v\r\n\f", *rseed))
1347 rseed++;
1348 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
1350 const char *s = rseed + 4;
1351 if (strlen (s) >= 32) /* require 4 * 8 chars */
1353 guint32 seedarray[4];
1354 gchar *p, hexbuf[9] = { 0, };
1355 memcpy (hexbuf, s + 0, 8);
1356 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
1357 seed_failed += p != NULL && *p != 0;
1358 memcpy (hexbuf, s + 8, 8);
1359 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
1360 seed_failed += p != NULL && *p != 0;
1361 memcpy (hexbuf, s + 16, 8);
1362 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
1363 seed_failed += p != NULL && *p != 0;
1364 memcpy (hexbuf, s + 24, 8);
1365 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
1366 seed_failed += p != NULL && *p != 0;
1367 if (!seed_failed)
1369 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
1370 return;
1374 g_error ("Unknown or invalid random seed: %s", rseed);
1378 * g_test_rand_int:
1380 * Get a reproducible random integer number.
1382 * The random numbers generated by the g_test_rand_*() family of functions
1383 * change with every new test program start, unless the --seed option is
1384 * given when starting test programs.
1386 * For individual test cases however, the random number generator is
1387 * reseeded, to avoid dependencies between tests and to make --seed
1388 * effective for all test cases.
1390 * Returns: a random number from the seeded random number generator.
1392 * Since: 2.16
1394 gint32
1395 g_test_rand_int (void)
1397 return g_rand_int (test_run_rand);
1401 * g_test_rand_int_range:
1402 * @begin: the minimum value returned by this function
1403 * @end: the smallest value not to be returned by this function
1405 * Get a reproducible random integer number out of a specified range,
1406 * see g_test_rand_int() for details on test case random numbers.
1408 * Returns: a number with @begin <= number < @end.
1410 * Since: 2.16
1412 gint32
1413 g_test_rand_int_range (gint32 begin,
1414 gint32 end)
1416 return g_rand_int_range (test_run_rand, begin, end);
1420 * g_test_rand_double:
1422 * Get a reproducible random floating point number,
1423 * see g_test_rand_int() for details on test case random numbers.
1425 * Returns: a random number from the seeded random number generator.
1427 * Since: 2.16
1429 double
1430 g_test_rand_double (void)
1432 return g_rand_double (test_run_rand);
1436 * g_test_rand_double_range:
1437 * @range_start: the minimum value returned by this function
1438 * @range_end: the minimum value not returned by this function
1440 * Get a reproducible random floating pointer number out of a specified range,
1441 * see g_test_rand_int() for details on test case random numbers.
1443 * Returns: a number with @range_start <= number < @range_end.
1445 * Since: 2.16
1447 double
1448 g_test_rand_double_range (double range_start,
1449 double range_end)
1451 return g_rand_double_range (test_run_rand, range_start, range_end);
1455 * g_test_timer_start:
1457 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1458 * to be done. Call this function again to restart the timer.
1460 * Since: 2.16
1462 void
1463 g_test_timer_start (void)
1465 if (!test_user_timer)
1466 test_user_timer = g_timer_new();
1467 test_user_stamp = 0;
1468 g_timer_start (test_user_timer);
1472 * g_test_timer_elapsed:
1474 * Get the time since the last start of the timer with g_test_timer_start().
1476 * Returns: the time since the last start of the timer, as a double
1478 * Since: 2.16
1480 double
1481 g_test_timer_elapsed (void)
1483 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1484 return test_user_stamp;
1488 * g_test_timer_last:
1490 * Report the last result of g_test_timer_elapsed().
1492 * Returns: the last result of g_test_timer_elapsed(), as a double
1494 * Since: 2.16
1496 double
1497 g_test_timer_last (void)
1499 return test_user_stamp;
1503 * g_test_minimized_result:
1504 * @minimized_quantity: the reported value
1505 * @format: the format string of the report message
1506 * @...: arguments to pass to the printf() function
1508 * Report the result of a performance or measurement test.
1509 * The test should generally strive to minimize the reported
1510 * quantities (smaller values are better than larger ones),
1511 * this and @minimized_quantity can determine sorting
1512 * order for test result reports.
1514 * Since: 2.16
1516 void
1517 g_test_minimized_result (double minimized_quantity,
1518 const char *format,
1519 ...)
1521 long double largs = minimized_quantity;
1522 gchar *buffer;
1523 va_list args;
1525 va_start (args, format);
1526 buffer = g_strdup_vprintf (format, args);
1527 va_end (args);
1529 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1530 g_free (buffer);
1534 * g_test_maximized_result:
1535 * @maximized_quantity: the reported value
1536 * @format: the format string of the report message
1537 * @...: arguments to pass to the printf() function
1539 * Report the result of a performance or measurement test.
1540 * The test should generally strive to maximize the reported
1541 * quantities (larger values are better than smaller ones),
1542 * this and @maximized_quantity can determine sorting
1543 * order for test result reports.
1545 * Since: 2.16
1547 void
1548 g_test_maximized_result (double maximized_quantity,
1549 const char *format,
1550 ...)
1552 long double largs = maximized_quantity;
1553 gchar *buffer;
1554 va_list args;
1556 va_start (args, format);
1557 buffer = g_strdup_vprintf (format, args);
1558 va_end (args);
1560 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1561 g_free (buffer);
1565 * g_test_message:
1566 * @format: the format string
1567 * @...: printf-like arguments to @format
1569 * Add a message to the test report.
1571 * Since: 2.16
1573 void
1574 g_test_message (const char *format,
1575 ...)
1577 gchar *buffer;
1578 va_list args;
1580 va_start (args, format);
1581 buffer = g_strdup_vprintf (format, args);
1582 va_end (args);
1584 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1585 g_free (buffer);
1589 * g_test_bug_base:
1590 * @uri_pattern: the base pattern for bug URIs
1592 * Specify the base URI for bug reports.
1594 * The base URI is used to construct bug report messages for
1595 * g_test_message() when g_test_bug() is called.
1596 * Calling this function outside of a test case sets the
1597 * default base URI for all test cases. Calling it from within
1598 * a test case changes the base URI for the scope of the test
1599 * case only.
1600 * Bug URIs are constructed by appending a bug specific URI
1601 * portion to @uri_pattern, or by replacing the special string
1602 * '\%s' within @uri_pattern if that is present.
1604 * Since: 2.16
1606 void
1607 g_test_bug_base (const char *uri_pattern)
1609 g_free (test_uri_base);
1610 test_uri_base = g_strdup (uri_pattern);
1614 * g_test_bug:
1615 * @bug_uri_snippet: Bug specific bug tracker URI portion.
1617 * This function adds a message to test reports that
1618 * associates a bug URI with a test case.
1619 * Bug URIs are constructed from a base URI set with g_test_bug_base()
1620 * and @bug_uri_snippet.
1622 * Since: 2.16
1624 void
1625 g_test_bug (const char *bug_uri_snippet)
1627 char *c;
1629 g_return_if_fail (test_uri_base != NULL);
1630 g_return_if_fail (bug_uri_snippet != NULL);
1632 c = strstr (test_uri_base, "%s");
1633 if (c)
1635 char *b = g_strndup (test_uri_base, c - test_uri_base);
1636 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1637 g_free (b);
1638 g_test_message ("Bug Reference: %s", s);
1639 g_free (s);
1641 else
1642 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1646 * g_test_get_root:
1648 * Get the toplevel test suite for the test path API.
1650 * Returns: the toplevel #GTestSuite
1652 * Since: 2.16
1654 GTestSuite*
1655 g_test_get_root (void)
1657 if (!test_suite_root)
1659 test_suite_root = g_test_create_suite ("root");
1660 g_free (test_suite_root->name);
1661 test_suite_root->name = g_strdup ("");
1664 return test_suite_root;
1668 * g_test_run:
1670 * Runs all tests under the toplevel suite which can be retrieved
1671 * with g_test_get_root(). Similar to g_test_run_suite(), the test
1672 * cases to be run are filtered according to test path arguments
1673 * (`-p testpath` and `-s testpath`) as parsed by g_test_init().
1674 * g_test_run_suite() or g_test_run() may only be called once in a
1675 * program.
1677 * In general, the tests and sub-suites within each suite are run in
1678 * the order in which they are defined. However, note that prior to
1679 * GLib 2.36, there was a bug in the `g_test_add_*`
1680 * functions which caused them to create multiple suites with the same
1681 * name, meaning that if you created tests "/foo/simple",
1682 * "/bar/simple", and "/foo/using-bar" in that order, they would get
1683 * run in that order (since g_test_run() would run the first "/foo"
1684 * suite, then the "/bar" suite, then the second "/foo" suite). As of
1685 * 2.36, this bug is fixed, and adding the tests in that order would
1686 * result in a running order of "/foo/simple", "/foo/using-bar",
1687 * "/bar/simple". If this new ordering is sub-optimal (because it puts
1688 * more-complicated tests before simpler ones, making it harder to
1689 * figure out exactly what has failed), you can fix it by changing the
1690 * test paths to group tests by suite in a way that will result in the
1691 * desired running order. Eg, "/simple/foo", "/simple/bar",
1692 * "/complex/foo-using-bar".
1694 * However, you should never make the actual result of a test depend
1695 * on the order that tests are run in. If you need to ensure that some
1696 * particular code runs before or after a given test case, use
1697 * g_test_add(), which lets you specify setup and teardown functions.
1699 * If all tests are skipped, this function will return 0 if
1700 * producing TAP output, or 77 (treated as "skip test" by Automake) otherwise.
1702 * Returns: 0 on success, 1 on failure (assuming it returns at all),
1703 * 0 or 77 if all tests were skipped with g_test_skip()
1705 * Since: 2.16
1708 g_test_run (void)
1710 if (g_test_run_suite (g_test_get_root()) != 0)
1711 return 1;
1713 /* 77 is special to Automake's default driver, but not Automake's TAP driver
1714 * or Perl's prove(1) TAP driver. */
1715 if (test_tap_log)
1716 return 0;
1718 if (test_run_count > 0 && test_run_count == test_skipped_count)
1719 return 77;
1720 else
1721 return 0;
1725 * g_test_create_case:
1726 * @test_name: the name for the test case
1727 * @data_size: the size of the fixture data structure
1728 * @test_data: test data argument for the test functions
1729 * @data_setup: (scope async): the function to set up the fixture data
1730 * @data_test: (scope async): the actual test function
1731 * @data_teardown: (scope async): the function to teardown the fixture data
1733 * Create a new #GTestCase, named @test_name, this API is fairly
1734 * low level, calling g_test_add() or g_test_add_func() is preferable.
1735 * When this test is executed, a fixture structure of size @data_size
1736 * will be automatically allocated and filled with zeros. Then @data_setup is
1737 * called to initialize the fixture. After fixture setup, the actual test
1738 * function @data_test is called. Once the test run completes, the
1739 * fixture structure is torn down by calling @data_teardown and
1740 * after that the memory is automatically released by the test framework.
1742 * Splitting up a test run into fixture setup, test function and
1743 * fixture teardown is most useful if the same fixture is used for
1744 * multiple tests. In this cases, g_test_create_case() will be
1745 * called with the same fixture, but varying @test_name and
1746 * @data_test arguments.
1748 * Returns: a newly allocated #GTestCase.
1750 * Since: 2.16
1752 GTestCase*
1753 g_test_create_case (const char *test_name,
1754 gsize data_size,
1755 gconstpointer test_data,
1756 GTestFixtureFunc data_setup,
1757 GTestFixtureFunc data_test,
1758 GTestFixtureFunc data_teardown)
1760 GTestCase *tc;
1762 g_return_val_if_fail (test_name != NULL, NULL);
1763 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1764 g_return_val_if_fail (test_name[0] != 0, NULL);
1765 g_return_val_if_fail (data_test != NULL, NULL);
1767 tc = g_slice_new0 (GTestCase);
1768 tc->name = g_strdup (test_name);
1769 tc->test_data = (gpointer) test_data;
1770 tc->fixture_size = data_size;
1771 tc->fixture_setup = (void*) data_setup;
1772 tc->fixture_test = (void*) data_test;
1773 tc->fixture_teardown = (void*) data_teardown;
1775 return tc;
1778 static gint
1779 find_suite (gconstpointer l, gconstpointer s)
1781 const GTestSuite *suite = l;
1782 const gchar *str = s;
1784 return strcmp (suite->name, str);
1787 static gint
1788 find_case (gconstpointer l, gconstpointer s)
1790 const GTestCase *tc = l;
1791 const gchar *str = s;
1793 return strcmp (tc->name, str);
1797 * GTestFixtureFunc:
1798 * @fixture: (not nullable): the test fixture
1799 * @user_data: the data provided when registering the test
1801 * The type used for functions that operate on test fixtures. This is
1802 * used for the fixture setup and teardown functions as well as for the
1803 * testcases themselves.
1805 * @user_data is a pointer to the data that was given when registering
1806 * the test case.
1808 * @fixture will be a pointer to the area of memory allocated by the
1809 * test framework, of the size requested. If the requested size was
1810 * zero then @fixture will be equal to @user_data.
1812 * Since: 2.28
1814 void
1815 g_test_add_vtable (const char *testpath,
1816 gsize data_size,
1817 gconstpointer test_data,
1818 GTestFixtureFunc data_setup,
1819 GTestFixtureFunc fixture_test_func,
1820 GTestFixtureFunc data_teardown)
1822 gchar **segments;
1823 guint ui;
1824 GTestSuite *suite;
1826 g_return_if_fail (testpath != NULL);
1827 g_return_if_fail (g_path_is_absolute (testpath));
1828 g_return_if_fail (fixture_test_func != NULL);
1830 suite = g_test_get_root();
1831 segments = g_strsplit (testpath, "/", -1);
1832 for (ui = 0; segments[ui] != NULL; ui++)
1834 const char *seg = segments[ui];
1835 gboolean islast = segments[ui + 1] == NULL;
1836 if (islast && !seg[0])
1837 g_error ("invalid test case path: %s", testpath);
1838 else if (!seg[0])
1839 continue; /* initial or duplicate slash */
1840 else if (!islast)
1842 GSList *l;
1843 GTestSuite *csuite;
1844 l = g_slist_find_custom (suite->suites, seg, find_suite);
1845 if (l)
1847 csuite = l->data;
1849 else
1851 csuite = g_test_create_suite (seg);
1852 g_test_suite_add_suite (suite, csuite);
1854 suite = csuite;
1856 else /* islast */
1858 GTestCase *tc;
1860 if (g_slist_find_custom (suite->cases, seg, find_case))
1861 g_error ("duplicate test case path: %s", testpath);
1863 tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1864 g_test_suite_add (suite, tc);
1867 g_strfreev (segments);
1871 * g_test_fail:
1873 * Indicates that a test failed. This function can be called
1874 * multiple times from the same test. You can use this function
1875 * if your test failed in a recoverable way.
1877 * Do not use this function if the failure of a test could cause
1878 * other tests to malfunction.
1880 * Calling this function will not stop the test from running, you
1881 * need to return from the test function yourself. So you can
1882 * produce additional diagnostic messages or even continue running
1883 * the test.
1885 * If not called from inside a test, this function does nothing.
1887 * Since: 2.30
1889 void
1890 g_test_fail (void)
1892 test_run_success = G_TEST_RUN_FAILURE;
1896 * g_test_incomplete:
1897 * @msg: (nullable): explanation
1899 * Indicates that a test failed because of some incomplete
1900 * functionality. This function can be called multiple times
1901 * from the same test.
1903 * Calling this function will not stop the test from running, you
1904 * need to return from the test function yourself. So you can
1905 * produce additional diagnostic messages or even continue running
1906 * the test.
1908 * If not called from inside a test, this function does nothing.
1910 * Since: 2.38
1912 void
1913 g_test_incomplete (const gchar *msg)
1915 test_run_success = G_TEST_RUN_INCOMPLETE;
1916 g_free (test_run_msg);
1917 test_run_msg = g_strdup (msg);
1921 * g_test_skip:
1922 * @msg: (nullable): explanation
1924 * Indicates that a test was skipped.
1926 * Calling this function will not stop the test from running, you
1927 * need to return from the test function yourself. So you can
1928 * produce additional diagnostic messages or even continue running
1929 * the test.
1931 * If not called from inside a test, this function does nothing.
1933 * Since: 2.38
1935 void
1936 g_test_skip (const gchar *msg)
1938 test_run_success = G_TEST_RUN_SKIPPED;
1939 g_free (test_run_msg);
1940 test_run_msg = g_strdup (msg);
1944 * g_test_failed:
1946 * Returns whether a test has already failed. This will
1947 * be the case when g_test_fail(), g_test_incomplete()
1948 * or g_test_skip() have been called, but also if an
1949 * assertion has failed.
1951 * This can be useful to return early from a test if
1952 * continuing after a failed assertion might be harmful.
1954 * The return value of this function is only meaningful
1955 * if it is called from inside a test function.
1957 * Returns: %TRUE if the test has failed
1959 * Since: 2.38
1961 gboolean
1962 g_test_failed (void)
1964 return test_run_success != G_TEST_RUN_SUCCESS;
1968 * g_test_set_nonfatal_assertions:
1970 * Changes the behaviour of g_assert_cmpstr(), g_assert_cmpint(),
1971 * g_assert_cmpuint(), g_assert_cmphex(), g_assert_cmpfloat(),
1972 * g_assert_true(), g_assert_false(), g_assert_null(), g_assert_no_error(),
1973 * g_assert_error(), g_test_assert_expected_messages() and the various
1974 * g_test_trap_assert_*() macros to not abort to program, but instead
1975 * call g_test_fail() and continue. (This also changes the behavior of
1976 * g_test_fail() so that it will not cause the test program to abort
1977 * after completing the failed test.)
1979 * Note that the g_assert_not_reached() and g_assert() are not
1980 * affected by this.
1982 * This function can only be called after g_test_init().
1984 * Since: 2.38
1986 void
1987 g_test_set_nonfatal_assertions (void)
1989 if (!g_test_config_vars->test_initialized)
1990 g_error ("g_test_set_nonfatal_assertions called without g_test_init");
1991 test_nonfatal_assertions = TRUE;
1992 test_mode_fatal = FALSE;
1996 * GTestFunc:
1998 * The type used for test case functions.
2000 * Since: 2.28
2004 * g_test_add_func:
2005 * @testpath: /-separated test case path name for the test.
2006 * @test_func: (scope async): The test function to invoke for this test.
2008 * Create a new test case, similar to g_test_create_case(). However
2009 * the test is assumed to use no fixture, and test suites are automatically
2010 * created on the fly and added to the root fixture, based on the
2011 * slash-separated portions of @testpath.
2013 * If @testpath includes the component "subprocess" anywhere in it,
2014 * the test will be skipped by default, and only run if explicitly
2015 * required via the `-p` command-line option or g_test_trap_subprocess().
2017 * Since: 2.16
2019 void
2020 g_test_add_func (const char *testpath,
2021 GTestFunc test_func)
2023 g_return_if_fail (testpath != NULL);
2024 g_return_if_fail (testpath[0] == '/');
2025 g_return_if_fail (test_func != NULL);
2026 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
2030 * GTestDataFunc:
2031 * @user_data: the data provided when registering the test
2033 * The type used for test case functions that take an extra pointer
2034 * argument.
2036 * Since: 2.28
2040 * g_test_add_data_func:
2041 * @testpath: /-separated test case path name for the test.
2042 * @test_data: Test data argument for the test function.
2043 * @test_func: (scope async): The test function to invoke for this test.
2045 * Create a new test case, similar to g_test_create_case(). However
2046 * the test is assumed to use no fixture, and test suites are automatically
2047 * created on the fly and added to the root fixture, based on the
2048 * slash-separated portions of @testpath. The @test_data argument
2049 * will be passed as first argument to @test_func.
2051 * If @testpath includes the component "subprocess" anywhere in it,
2052 * the test will be skipped by default, and only run if explicitly
2053 * required via the `-p` command-line option or g_test_trap_subprocess().
2055 * Since: 2.16
2057 void
2058 g_test_add_data_func (const char *testpath,
2059 gconstpointer test_data,
2060 GTestDataFunc test_func)
2062 g_return_if_fail (testpath != NULL);
2063 g_return_if_fail (testpath[0] == '/');
2064 g_return_if_fail (test_func != NULL);
2066 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
2070 * g_test_add_data_func_full:
2071 * @testpath: /-separated test case path name for the test.
2072 * @test_data: Test data argument for the test function.
2073 * @test_func: The test function to invoke for this test.
2074 * @data_free_func: #GDestroyNotify for @test_data.
2076 * Create a new test case, as with g_test_add_data_func(), but freeing
2077 * @test_data after the test run is complete.
2079 * Since: 2.34
2081 void
2082 g_test_add_data_func_full (const char *testpath,
2083 gpointer test_data,
2084 GTestDataFunc test_func,
2085 GDestroyNotify data_free_func)
2087 g_return_if_fail (testpath != NULL);
2088 g_return_if_fail (testpath[0] == '/');
2089 g_return_if_fail (test_func != NULL);
2091 g_test_add_vtable (testpath, 0, test_data, NULL,
2092 (GTestFixtureFunc) test_func,
2093 (GTestFixtureFunc) data_free_func);
2096 static gboolean
2097 g_test_suite_case_exists (GTestSuite *suite,
2098 const char *test_path)
2100 GSList *iter;
2101 char *slash;
2102 GTestCase *tc;
2104 test_path++;
2105 slash = strchr (test_path, '/');
2107 if (slash)
2109 for (iter = suite->suites; iter; iter = iter->next)
2111 GTestSuite *child_suite = iter->data;
2113 if (!strncmp (child_suite->name, test_path, slash - test_path))
2114 if (g_test_suite_case_exists (child_suite, slash))
2115 return TRUE;
2118 else
2120 for (iter = suite->cases; iter; iter = iter->next)
2122 tc = iter->data;
2123 if (!strcmp (tc->name, test_path))
2124 return TRUE;
2128 return FALSE;
2132 * g_test_create_suite:
2133 * @suite_name: a name for the suite
2135 * Create a new test suite with the name @suite_name.
2137 * Returns: A newly allocated #GTestSuite instance.
2139 * Since: 2.16
2141 GTestSuite*
2142 g_test_create_suite (const char *suite_name)
2144 GTestSuite *ts;
2145 g_return_val_if_fail (suite_name != NULL, NULL);
2146 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
2147 g_return_val_if_fail (suite_name[0] != 0, NULL);
2148 ts = g_slice_new0 (GTestSuite);
2149 ts->name = g_strdup (suite_name);
2150 return ts;
2154 * g_test_suite_add:
2155 * @suite: a #GTestSuite
2156 * @test_case: a #GTestCase
2158 * Adds @test_case to @suite.
2160 * Since: 2.16
2162 void
2163 g_test_suite_add (GTestSuite *suite,
2164 GTestCase *test_case)
2166 g_return_if_fail (suite != NULL);
2167 g_return_if_fail (test_case != NULL);
2169 suite->cases = g_slist_append (suite->cases, test_case);
2173 * g_test_suite_add_suite:
2174 * @suite: a #GTestSuite
2175 * @nestedsuite: another #GTestSuite
2177 * Adds @nestedsuite to @suite.
2179 * Since: 2.16
2181 void
2182 g_test_suite_add_suite (GTestSuite *suite,
2183 GTestSuite *nestedsuite)
2185 g_return_if_fail (suite != NULL);
2186 g_return_if_fail (nestedsuite != NULL);
2188 suite->suites = g_slist_append (suite->suites, nestedsuite);
2192 * g_test_queue_free:
2193 * @gfree_pointer: the pointer to be stored.
2195 * Enqueue a pointer to be released with g_free() during the next
2196 * teardown phase. This is equivalent to calling g_test_queue_destroy()
2197 * with a destroy callback of g_free().
2199 * Since: 2.16
2201 void
2202 g_test_queue_free (gpointer gfree_pointer)
2204 if (gfree_pointer)
2205 g_test_queue_destroy (g_free, gfree_pointer);
2209 * g_test_queue_destroy:
2210 * @destroy_func: Destroy callback for teardown phase.
2211 * @destroy_data: Destroy callback data.
2213 * This function enqueus a callback @destroy_func to be executed
2214 * during the next test case teardown phase. This is most useful
2215 * to auto destruct allocated test resources at the end of a test run.
2216 * Resources are released in reverse queue order, that means enqueueing
2217 * callback A before callback B will cause B() to be called before
2218 * A() during teardown.
2220 * Since: 2.16
2222 void
2223 g_test_queue_destroy (GDestroyNotify destroy_func,
2224 gpointer destroy_data)
2226 DestroyEntry *dentry;
2228 g_return_if_fail (destroy_func != NULL);
2230 dentry = g_slice_new0 (DestroyEntry);
2231 dentry->destroy_func = destroy_func;
2232 dentry->destroy_data = destroy_data;
2233 dentry->next = test_destroy_queue;
2234 test_destroy_queue = dentry;
2237 static gboolean
2238 test_case_run (GTestCase *tc)
2240 gchar *old_base = g_strdup (test_uri_base);
2241 GSList **old_free_list, *filename_free_list = NULL;
2242 gboolean success = G_TEST_RUN_SUCCESS;
2244 old_free_list = test_filename_free_list;
2245 test_filename_free_list = &filename_free_list;
2247 if (++test_run_count <= test_startup_skip_count)
2248 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
2249 else if (test_run_list)
2251 g_print ("%s\n", test_run_name);
2252 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
2254 else
2256 GTimer *test_run_timer = g_timer_new();
2257 long double largs[3];
2258 void *fixture;
2259 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
2260 test_run_forks = 0;
2261 test_run_success = G_TEST_RUN_SUCCESS;
2262 g_clear_pointer (&test_run_msg, g_free);
2263 g_test_log_set_fatal_handler (NULL, NULL);
2264 if (test_paths_skipped && g_slist_find_custom (test_paths_skipped, test_run_name, (GCompareFunc)g_strcmp0))
2265 g_test_skip ("by request (-s option)");
2266 else
2268 g_timer_start (test_run_timer);
2269 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
2270 test_run_seed (test_run_seedstr);
2271 if (tc->fixture_setup)
2272 tc->fixture_setup (fixture, tc->test_data);
2273 tc->fixture_test (fixture, tc->test_data);
2274 test_trap_clear();
2275 while (test_destroy_queue)
2277 DestroyEntry *dentry = test_destroy_queue;
2278 test_destroy_queue = dentry->next;
2279 dentry->destroy_func (dentry->destroy_data);
2280 g_slice_free (DestroyEntry, dentry);
2282 if (tc->fixture_teardown)
2283 tc->fixture_teardown (fixture, tc->test_data);
2284 if (tc->fixture_size)
2285 g_free (fixture);
2286 g_timer_stop (test_run_timer);
2288 success = test_run_success;
2289 test_run_success = G_TEST_RUN_FAILURE;
2290 largs[0] = success; /* OK */
2291 largs[1] = test_run_forks;
2292 largs[2] = g_timer_elapsed (test_run_timer, NULL);
2293 g_test_log (G_TEST_LOG_STOP_CASE, test_run_name, test_run_msg, G_N_ELEMENTS (largs), largs);
2294 g_clear_pointer (&test_run_msg, g_free);
2295 g_timer_destroy (test_run_timer);
2298 g_slist_free_full (filename_free_list, g_free);
2299 test_filename_free_list = old_free_list;
2300 g_free (test_uri_base);
2301 test_uri_base = old_base;
2303 return (success == G_TEST_RUN_SUCCESS ||
2304 success == G_TEST_RUN_SKIPPED);
2307 static gboolean
2308 path_has_prefix (const char *path,
2309 const char *prefix)
2311 int prefix_len = strlen (prefix);
2313 return (strncmp (path, prefix, prefix_len) == 0 &&
2314 (path[prefix_len] == '\0' ||
2315 path[prefix_len] == '/'));
2318 static gboolean
2319 test_should_run (const char *test_path,
2320 const char *cmp_path)
2322 if (strstr (test_run_name, "/subprocess"))
2324 if (g_strcmp0 (test_path, cmp_path) == 0)
2325 return TRUE;
2327 if (g_test_verbose ())
2328 g_print ("GTest: skipping: %s\n", test_run_name);
2329 return FALSE;
2332 return !cmp_path || path_has_prefix (test_path, cmp_path);
2335 /* Recurse through @suite, running tests matching @path (or all tests
2336 * if @path is %NULL).
2338 static int
2339 g_test_run_suite_internal (GTestSuite *suite,
2340 const char *path)
2342 guint n_bad = 0;
2343 gchar *old_name = test_run_name;
2344 GSList *iter;
2346 g_return_val_if_fail (suite != NULL, -1);
2348 g_test_log (G_TEST_LOG_START_SUITE, suite->name, NULL, 0, NULL);
2350 for (iter = suite->cases; iter; iter = iter->next)
2352 GTestCase *tc = iter->data;
2354 test_run_name = g_build_path ("/", old_name, tc->name, NULL);
2355 if (test_should_run (test_run_name, path))
2357 if (!test_case_run (tc))
2358 n_bad++;
2360 g_free (test_run_name);
2363 for (iter = suite->suites; iter; iter = iter->next)
2365 GTestSuite *ts = iter->data;
2367 test_run_name = g_build_path ("/", old_name, ts->name, NULL);
2368 if (!path || path_has_prefix (path, test_run_name))
2369 n_bad += g_test_run_suite_internal (ts, path);
2370 g_free (test_run_name);
2373 test_run_name = old_name;
2375 g_test_log (G_TEST_LOG_STOP_SUITE, suite->name, NULL, 0, NULL);
2377 return n_bad;
2380 static int
2381 g_test_suite_count (GTestSuite *suite)
2383 int n = 0;
2384 GSList *iter;
2386 g_return_val_if_fail (suite != NULL, -1);
2388 for (iter = suite->cases; iter; iter = iter->next)
2390 GTestCase *tc = iter->data;
2392 if (strcmp (tc->name, "subprocess") != 0)
2393 n++;
2396 for (iter = suite->suites; iter; iter = iter->next)
2398 GTestSuite *ts = iter->data;
2400 if (strcmp (ts->name, "subprocess") != 0)
2401 n += g_test_suite_count (ts);
2404 return n;
2408 * g_test_run_suite:
2409 * @suite: a #GTestSuite
2411 * Execute the tests within @suite and all nested #GTestSuites.
2412 * The test suites to be executed are filtered according to
2413 * test path arguments (`-p testpath` and `-s testpath`) as parsed by
2414 * g_test_init(). See the g_test_run() documentation for more
2415 * information on the order that tests are run in.
2417 * g_test_run_suite() or g_test_run() may only be called once
2418 * in a program.
2420 * Returns: 0 on success
2422 * Since: 2.16
2425 g_test_run_suite (GTestSuite *suite)
2427 int n_bad = 0;
2429 g_return_val_if_fail (g_test_run_once == TRUE, -1);
2431 g_test_run_once = FALSE;
2432 test_count = g_test_suite_count (suite);
2434 test_run_name = g_strdup_printf ("/%s", suite->name);
2436 if (test_paths)
2438 GSList *iter;
2440 for (iter = test_paths; iter; iter = iter->next)
2441 n_bad += g_test_run_suite_internal (suite, iter->data);
2443 else
2444 n_bad = g_test_run_suite_internal (suite, NULL);
2446 g_free (test_run_name);
2447 test_run_name = NULL;
2449 return n_bad;
2452 static void
2453 gtest_default_log_handler (const gchar *log_domain,
2454 GLogLevelFlags log_level,
2455 const gchar *message,
2456 gpointer unused_data)
2458 const gchar *strv[16];
2459 gboolean fatal = FALSE;
2460 gchar *msg;
2461 guint i = 0;
2463 if (log_domain)
2465 strv[i++] = log_domain;
2466 strv[i++] = "-";
2468 if (log_level & G_LOG_FLAG_FATAL)
2470 strv[i++] = "FATAL-";
2471 fatal = TRUE;
2473 if (log_level & G_LOG_FLAG_RECURSION)
2474 strv[i++] = "RECURSIVE-";
2475 if (log_level & G_LOG_LEVEL_ERROR)
2476 strv[i++] = "ERROR";
2477 if (log_level & G_LOG_LEVEL_CRITICAL)
2478 strv[i++] = "CRITICAL";
2479 if (log_level & G_LOG_LEVEL_WARNING)
2480 strv[i++] = "WARNING";
2481 if (log_level & G_LOG_LEVEL_MESSAGE)
2482 strv[i++] = "MESSAGE";
2483 if (log_level & G_LOG_LEVEL_INFO)
2484 strv[i++] = "INFO";
2485 if (log_level & G_LOG_LEVEL_DEBUG)
2486 strv[i++] = "DEBUG";
2487 strv[i++] = ": ";
2488 strv[i++] = message;
2489 strv[i++] = NULL;
2491 msg = g_strjoinv ("", (gchar**) strv);
2492 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
2493 g_log_default_handler (log_domain, log_level, message, unused_data);
2495 g_free (msg);
2498 void
2499 g_assertion_message (const char *domain,
2500 const char *file,
2501 int line,
2502 const char *func,
2503 const char *message)
2505 char lstr[32];
2506 char *s;
2508 if (!message)
2509 message = "code should not be reached";
2510 g_snprintf (lstr, 32, "%d", line);
2511 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
2512 "ERROR:", file, ":", lstr, ":",
2513 func, func[0] ? ":" : "",
2514 " ", message, NULL);
2515 g_printerr ("**\n%s\n", s);
2517 /* Don't print a fatal error indication if assertions are non-fatal, or
2518 * if we are a child process that might be sharing the parent's stdout. */
2519 if (test_nonfatal_assertions || test_in_subprocess || test_in_forked_child)
2520 g_test_log (G_TEST_LOG_MESSAGE, s, NULL, 0, NULL);
2521 else
2522 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
2524 if (test_nonfatal_assertions)
2526 g_free (s);
2527 g_test_fail ();
2528 return;
2531 /* store assertion message in global variable, so that it can be found in a
2532 * core dump */
2533 if (__glib_assert_msg != NULL)
2534 /* free the old one */
2535 free (__glib_assert_msg);
2536 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
2537 strcpy (__glib_assert_msg, s);
2539 g_free (s);
2541 if (test_in_subprocess)
2543 /* If this is a test case subprocess then it probably hit this
2544 * assertion on purpose, so just exit() rather than abort()ing,
2545 * to avoid triggering any system crash-reporting daemon.
2547 _exit (1);
2549 else
2550 g_abort ();
2554 * g_assertion_message_expr: (skip)
2555 * @domain: (nullable):
2556 * @file:
2557 * @line:
2558 * @func:
2559 * @expr: (nullable):
2561 void
2562 g_assertion_message_expr (const char *domain,
2563 const char *file,
2564 int line,
2565 const char *func,
2566 const char *expr)
2568 char *s;
2569 if (!expr)
2570 s = g_strdup ("code should not be reached");
2571 else
2572 s = g_strconcat ("assertion failed: (", expr, ")", NULL);
2573 g_assertion_message (domain, file, line, func, s);
2574 g_free (s);
2576 /* Normally g_assertion_message() won't return, but we need this for
2577 * when test_nonfatal_assertions is set, since
2578 * g_assertion_message_expr() is used for always-fatal assertions.
2580 if (test_in_subprocess)
2581 _exit (1);
2582 else
2583 g_abort ();
2586 void
2587 g_assertion_message_cmpnum (const char *domain,
2588 const char *file,
2589 int line,
2590 const char *func,
2591 const char *expr,
2592 long double arg1,
2593 const char *cmp,
2594 long double arg2,
2595 char numtype)
2597 char *s = NULL;
2599 switch (numtype)
2601 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;
2602 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;
2603 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr, (double) arg1, cmp, (double) arg2); break;
2604 /* ideally use: floats=%.7g double=%.17g */
2606 g_assertion_message (domain, file, line, func, s);
2607 g_free (s);
2610 void
2611 g_assertion_message_cmpstr (const char *domain,
2612 const char *file,
2613 int line,
2614 const char *func,
2615 const char *expr,
2616 const char *arg1,
2617 const char *cmp,
2618 const char *arg2)
2620 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
2621 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
2622 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
2623 g_free (t1);
2624 g_free (t2);
2625 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
2626 g_free (a1);
2627 g_free (a2);
2628 g_assertion_message (domain, file, line, func, s);
2629 g_free (s);
2632 void
2633 g_assertion_message_error (const char *domain,
2634 const char *file,
2635 int line,
2636 const char *func,
2637 const char *expr,
2638 const GError *error,
2639 GQuark error_domain,
2640 int error_code)
2642 GString *gstring;
2644 /* This is used by both g_assert_error() and g_assert_no_error(), so there
2645 * are three cases: expected an error but got the wrong error, expected
2646 * an error but got no error, and expected no error but got an error.
2649 gstring = g_string_new ("assertion failed ");
2650 if (error_domain)
2651 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
2652 g_quark_to_string (error_domain), error_code);
2653 else
2654 g_string_append_printf (gstring, "(%s == NULL): ", expr);
2656 if (error)
2657 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
2658 g_quark_to_string (error->domain), error->code);
2659 else
2660 g_string_append_printf (gstring, "%s is NULL", expr);
2662 g_assertion_message (domain, file, line, func, gstring->str);
2663 g_string_free (gstring, TRUE);
2667 * g_strcmp0:
2668 * @str1: (nullable): a C string or %NULL
2669 * @str2: (nullable): another C string or %NULL
2671 * Compares @str1 and @str2 like strcmp(). Handles %NULL
2672 * gracefully by sorting it before non-%NULL strings.
2673 * Comparing two %NULL pointers returns 0.
2675 * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
2677 * Since: 2.16
2680 g_strcmp0 (const char *str1,
2681 const char *str2)
2683 if (!str1)
2684 return -(str1 != str2);
2685 if (!str2)
2686 return str1 != str2;
2687 return strcmp (str1, str2);
2690 static void
2691 test_trap_clear (void)
2693 test_trap_last_status = 0;
2694 test_trap_last_pid = 0;
2695 g_clear_pointer (&test_trap_last_subprocess, g_free);
2696 g_clear_pointer (&test_trap_last_stdout, g_free);
2697 g_clear_pointer (&test_trap_last_stderr, g_free);
2700 #ifdef G_OS_UNIX
2702 static int
2703 sane_dup2 (int fd1,
2704 int fd2)
2706 int ret;
2708 ret = dup2 (fd1, fd2);
2709 while (ret < 0 && errno == EINTR);
2710 return ret;
2713 #endif
2715 typedef struct {
2716 GPid pid;
2717 GMainLoop *loop;
2718 int child_status; /* unmodified platform-specific status */
2720 GIOChannel *stdout_io;
2721 gboolean echo_stdout;
2722 GString *stdout_str;
2724 GIOChannel *stderr_io;
2725 gboolean echo_stderr;
2726 GString *stderr_str;
2727 } WaitForChildData;
2729 static void
2730 check_complete (WaitForChildData *data)
2732 if (data->child_status != -1 && data->stdout_io == NULL && data->stderr_io == NULL)
2733 g_main_loop_quit (data->loop);
2736 static void
2737 child_exited (GPid pid,
2738 gint status,
2739 gpointer user_data)
2741 WaitForChildData *data = user_data;
2743 g_assert (status != -1);
2744 data->child_status = status;
2746 check_complete (data);
2749 static gboolean
2750 child_timeout (gpointer user_data)
2752 WaitForChildData *data = user_data;
2754 #ifdef G_OS_WIN32
2755 TerminateProcess (data->pid, G_TEST_STATUS_TIMED_OUT);
2756 #else
2757 kill (data->pid, SIGALRM);
2758 #endif
2760 return FALSE;
2763 static gboolean
2764 child_read (GIOChannel *io, GIOCondition cond, gpointer user_data)
2766 WaitForChildData *data = user_data;
2767 GIOStatus status;
2768 gsize nread, nwrote, total;
2769 gchar buf[4096];
2770 FILE *echo_file = NULL;
2772 status = g_io_channel_read_chars (io, buf, sizeof (buf), &nread, NULL);
2773 if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF)
2775 // FIXME data->error = (status == G_IO_STATUS_ERROR);
2776 if (io == data->stdout_io)
2777 g_clear_pointer (&data->stdout_io, g_io_channel_unref);
2778 else
2779 g_clear_pointer (&data->stderr_io, g_io_channel_unref);
2781 check_complete (data);
2782 return FALSE;
2784 else if (status == G_IO_STATUS_AGAIN)
2785 return TRUE;
2787 if (io == data->stdout_io)
2789 g_string_append_len (data->stdout_str, buf, nread);
2790 if (data->echo_stdout)
2791 echo_file = stdout;
2793 else
2795 g_string_append_len (data->stderr_str, buf, nread);
2796 if (data->echo_stderr)
2797 echo_file = stderr;
2800 if (echo_file)
2802 for (total = 0; total < nread; total += nwrote)
2804 int errsv;
2806 nwrote = fwrite (buf + total, 1, nread - total, echo_file);
2807 errsv = errno;
2808 if (nwrote == 0)
2809 g_error ("write failed: %s", g_strerror (errsv));
2813 return TRUE;
2816 static void
2817 wait_for_child (GPid pid,
2818 int stdout_fd, gboolean echo_stdout,
2819 int stderr_fd, gboolean echo_stderr,
2820 guint64 timeout)
2822 WaitForChildData data;
2823 GMainContext *context;
2824 GSource *source;
2826 data.pid = pid;
2827 data.child_status = -1;
2829 context = g_main_context_new ();
2830 data.loop = g_main_loop_new (context, FALSE);
2832 source = g_child_watch_source_new (pid);
2833 g_source_set_callback (source, (GSourceFunc) child_exited, &data, NULL);
2834 g_source_attach (source, context);
2835 g_source_unref (source);
2837 data.echo_stdout = echo_stdout;
2838 data.stdout_str = g_string_new (NULL);
2839 data.stdout_io = g_io_channel_unix_new (stdout_fd);
2840 g_io_channel_set_close_on_unref (data.stdout_io, TRUE);
2841 g_io_channel_set_encoding (data.stdout_io, NULL, NULL);
2842 g_io_channel_set_buffered (data.stdout_io, FALSE);
2843 source = g_io_create_watch (data.stdout_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2844 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2845 g_source_attach (source, context);
2846 g_source_unref (source);
2848 data.echo_stderr = echo_stderr;
2849 data.stderr_str = g_string_new (NULL);
2850 data.stderr_io = g_io_channel_unix_new (stderr_fd);
2851 g_io_channel_set_close_on_unref (data.stderr_io, TRUE);
2852 g_io_channel_set_encoding (data.stderr_io, NULL, NULL);
2853 g_io_channel_set_buffered (data.stderr_io, FALSE);
2854 source = g_io_create_watch (data.stderr_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2855 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2856 g_source_attach (source, context);
2857 g_source_unref (source);
2859 if (timeout)
2861 source = g_timeout_source_new (0);
2862 g_source_set_ready_time (source, g_get_monotonic_time () + timeout);
2863 g_source_set_callback (source, (GSourceFunc) child_timeout, &data, NULL);
2864 g_source_attach (source, context);
2865 g_source_unref (source);
2868 g_main_loop_run (data.loop);
2869 g_main_loop_unref (data.loop);
2870 g_main_context_unref (context);
2872 test_trap_last_pid = pid;
2873 test_trap_last_status = data.child_status;
2874 test_trap_last_stdout = g_string_free (data.stdout_str, FALSE);
2875 test_trap_last_stderr = g_string_free (data.stderr_str, FALSE);
2877 g_clear_pointer (&data.stdout_io, g_io_channel_unref);
2878 g_clear_pointer (&data.stderr_io, g_io_channel_unref);
2882 * g_test_trap_fork:
2883 * @usec_timeout: Timeout for the forked test in micro seconds.
2884 * @test_trap_flags: Flags to modify forking behaviour.
2886 * Fork the current test program to execute a test case that might
2887 * not return or that might abort.
2889 * If @usec_timeout is non-0, the forked test case is aborted and
2890 * considered failing if its run time exceeds it.
2892 * The forking behavior can be configured with the #GTestTrapFlags flags.
2894 * In the following example, the test code forks, the forked child
2895 * process produces some sample output and exits successfully.
2896 * The forking parent process then asserts successful child program
2897 * termination and validates child program outputs.
2899 * |[<!-- language="C" -->
2900 * static void
2901 * test_fork_patterns (void)
2903 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2905 * g_print ("some stdout text: somagic17\n");
2906 * g_printerr ("some stderr text: semagic43\n");
2907 * exit (0); // successful test run
2909 * g_test_trap_assert_passed ();
2910 * g_test_trap_assert_stdout ("*somagic17*");
2911 * g_test_trap_assert_stderr ("*semagic43*");
2913 * ]|
2915 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2917 * Since: 2.16
2919 * Deprecated: This function is implemented only on Unix platforms,
2920 * and is not always reliable due to problems inherent in
2921 * fork-without-exec. Use g_test_trap_subprocess() instead.
2923 gboolean
2924 g_test_trap_fork (guint64 usec_timeout,
2925 GTestTrapFlags test_trap_flags)
2927 #ifdef G_OS_UNIX
2928 int stdout_pipe[2] = { -1, -1 };
2929 int stderr_pipe[2] = { -1, -1 };
2930 int errsv;
2932 test_trap_clear();
2933 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0)
2935 errsv = errno;
2936 g_error ("failed to create pipes to fork test program: %s", g_strerror (errsv));
2938 test_trap_last_pid = fork ();
2939 errsv = errno;
2940 if (test_trap_last_pid < 0)
2941 g_error ("failed to fork test program: %s", g_strerror (errsv));
2942 if (test_trap_last_pid == 0) /* child */
2944 int fd0 = -1;
2945 test_in_forked_child = TRUE;
2946 close (stdout_pipe[0]);
2947 close (stderr_pipe[0]);
2948 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2950 fd0 = g_open ("/dev/null", O_RDONLY, 0);
2951 if (fd0 < 0)
2952 g_error ("failed to open /dev/null for stdin redirection");
2954 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2956 errsv = errno;
2957 g_error ("failed to dup2() in forked test program: %s", g_strerror (errsv));
2959 if (fd0 >= 3)
2960 close (fd0);
2961 if (stdout_pipe[1] >= 3)
2962 close (stdout_pipe[1]);
2963 if (stderr_pipe[1] >= 3)
2964 close (stderr_pipe[1]);
2965 return TRUE;
2967 else /* parent */
2969 test_run_forks++;
2970 close (stdout_pipe[1]);
2971 close (stderr_pipe[1]);
2973 wait_for_child (test_trap_last_pid,
2974 stdout_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT),
2975 stderr_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR),
2976 usec_timeout);
2977 return FALSE;
2979 #else
2980 g_message ("Not implemented: g_test_trap_fork");
2982 return FALSE;
2983 #endif
2987 * g_test_trap_subprocess:
2988 * @test_path: (nullable): Test to run in a subprocess
2989 * @usec_timeout: Timeout for the subprocess test in micro seconds.
2990 * @test_flags: Flags to modify subprocess behaviour.
2992 * Respawns the test program to run only @test_path in a subprocess.
2993 * This can be used for a test case that might not return, or that
2994 * might abort.
2996 * If @test_path is %NULL then the same test is re-run in a subprocess.
2997 * You can use g_test_subprocess() to determine whether the test is in
2998 * a subprocess or not.
3000 * @test_path can also be the name of the parent test, followed by
3001 * "`/subprocess/`" and then a name for the specific subtest (or just
3002 * ending with "`/subprocess`" if the test only has one child test);
3003 * tests with names of this form will automatically be skipped in the
3004 * parent process.
3006 * If @usec_timeout is non-0, the test subprocess is aborted and
3007 * considered failing if its run time exceeds it.
3009 * The subprocess behavior can be configured with the
3010 * #GTestSubprocessFlags flags.
3012 * You can use methods such as g_test_trap_assert_passed(),
3013 * g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to
3014 * check the results of the subprocess. (But note that
3015 * g_test_trap_assert_stdout() and g_test_trap_assert_stderr()
3016 * cannot be used if @test_flags specifies that the child should
3017 * inherit the parent stdout/stderr.)
3019 * If your `main ()` needs to behave differently in
3020 * the subprocess, you can call g_test_subprocess() (after calling
3021 * g_test_init()) to see whether you are in a subprocess.
3023 * The following example tests that calling
3024 * `my_object_new(1000000)` will abort with an error
3025 * message.
3027 * |[<!-- language="C" -->
3028 * static void
3029 * test_create_large_object (void)
3031 * if (g_test_subprocess ())
3033 * my_object_new (1000000);
3034 * return;
3037 * // Reruns this same test in a subprocess
3038 * g_test_trap_subprocess (NULL, 0, 0);
3039 * g_test_trap_assert_failed ();
3040 * g_test_trap_assert_stderr ("*ERROR*too large*");
3043 * int
3044 * main (int argc, char **argv)
3046 * g_test_init (&argc, &argv, NULL);
3048 * g_test_add_func ("/myobject/create_large_object",
3049 * test_create_large_object);
3050 * return g_test_run ();
3052 * ]|
3054 * Since: 2.38
3056 void
3057 g_test_trap_subprocess (const char *test_path,
3058 guint64 usec_timeout,
3059 GTestSubprocessFlags test_flags)
3061 GError *error = NULL;
3062 GPtrArray *argv;
3063 GSpawnFlags flags;
3064 int stdout_fd, stderr_fd;
3065 GPid pid;
3067 /* Sanity check that they used GTestSubprocessFlags, not GTestTrapFlags */
3068 g_assert ((test_flags & (G_TEST_TRAP_INHERIT_STDIN | G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR)) == 0);
3070 if (test_path)
3072 if (!g_test_suite_case_exists (g_test_get_root (), test_path))
3073 g_error ("g_test_trap_subprocess: test does not exist: %s", test_path);
3075 else
3077 test_path = test_run_name;
3080 if (g_test_verbose ())
3081 g_print ("GTest: subprocess: %s\n", test_path);
3083 test_trap_clear ();
3084 test_trap_last_subprocess = g_strdup (test_path);
3086 argv = g_ptr_array_new ();
3087 g_ptr_array_add (argv, test_argv0);
3088 g_ptr_array_add (argv, "-q");
3089 g_ptr_array_add (argv, "-p");
3090 g_ptr_array_add (argv, (char *)test_path);
3091 g_ptr_array_add (argv, "--GTestSubprocess");
3092 if (test_log_fd != -1)
3094 char log_fd_buf[128];
3096 g_ptr_array_add (argv, "--GTestLogFD");
3097 g_snprintf (log_fd_buf, sizeof (log_fd_buf), "%d", test_log_fd);
3098 g_ptr_array_add (argv, log_fd_buf);
3100 g_ptr_array_add (argv, NULL);
3102 flags = G_SPAWN_DO_NOT_REAP_CHILD;
3103 if (test_flags & G_TEST_TRAP_INHERIT_STDIN)
3104 flags |= G_SPAWN_CHILD_INHERITS_STDIN;
3106 if (!g_spawn_async_with_pipes (test_initial_cwd,
3107 (char **)argv->pdata,
3108 NULL, flags,
3109 NULL, NULL,
3110 &pid, NULL, &stdout_fd, &stderr_fd,
3111 &error))
3113 g_error ("g_test_trap_subprocess() failed: %s",
3114 error->message);
3116 g_ptr_array_free (argv, TRUE);
3118 wait_for_child (pid,
3119 stdout_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDOUT),
3120 stderr_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDERR),
3121 usec_timeout);
3125 * g_test_subprocess:
3127 * Returns %TRUE (after g_test_init() has been called) if the test
3128 * program is running under g_test_trap_subprocess().
3130 * Returns: %TRUE if the test program is running under
3131 * g_test_trap_subprocess().
3133 * Since: 2.38
3135 gboolean
3136 g_test_subprocess (void)
3138 return test_in_subprocess;
3142 * g_test_trap_has_passed:
3144 * Check the result of the last g_test_trap_subprocess() call.
3146 * Returns: %TRUE if the last test subprocess terminated successfully.
3148 * Since: 2.16
3150 gboolean
3151 g_test_trap_has_passed (void)
3153 #ifdef G_OS_UNIX
3154 return (WIFEXITED (test_trap_last_status) &&
3155 WEXITSTATUS (test_trap_last_status) == 0);
3156 #else
3157 return test_trap_last_status == 0;
3158 #endif
3162 * g_test_trap_reached_timeout:
3164 * Check the result of the last g_test_trap_subprocess() call.
3166 * Returns: %TRUE if the last test subprocess got killed due to a timeout.
3168 * Since: 2.16
3170 gboolean
3171 g_test_trap_reached_timeout (void)
3173 #ifdef G_OS_UNIX
3174 return (WIFSIGNALED (test_trap_last_status) &&
3175 WTERMSIG (test_trap_last_status) == SIGALRM);
3176 #else
3177 return test_trap_last_status == G_TEST_STATUS_TIMED_OUT;
3178 #endif
3181 static gboolean
3182 log_child_output (const gchar *process_id)
3184 gchar *escaped;
3186 #ifdef G_OS_UNIX
3187 if (WIFEXITED (test_trap_last_status)) /* normal exit */
3189 if (WEXITSTATUS (test_trap_last_status) == 0)
3190 g_test_message ("child process (%s) exit status: 0 (success)",
3191 process_id);
3192 else
3193 g_test_message ("child process (%s) exit status: %d (error)",
3194 process_id, WEXITSTATUS (test_trap_last_status));
3196 else if (WIFSIGNALED (test_trap_last_status) &&
3197 WTERMSIG (test_trap_last_status) == SIGALRM)
3199 g_test_message ("child process (%s) timed out", process_id);
3201 else if (WIFSIGNALED (test_trap_last_status))
3203 const gchar *maybe_dumped_core = "";
3205 #ifdef WCOREDUMP
3206 if (WCOREDUMP (test_trap_last_status))
3207 maybe_dumped_core = ", core dumped";
3208 #endif
3210 g_test_message ("child process (%s) killed by signal %d (%s)%s",
3211 process_id, WTERMSIG (test_trap_last_status),
3212 g_strsignal (WTERMSIG (test_trap_last_status)),
3213 maybe_dumped_core);
3215 else
3217 g_test_message ("child process (%s) unknown wait status %d",
3218 process_id, test_trap_last_status);
3220 #else
3221 if (test_trap_last_status == 0)
3222 g_test_message ("child process (%s) exit status: 0 (success)",
3223 process_id);
3224 else
3225 g_test_message ("child process (%s) exit status: %d (error)",
3226 process_id, test_trap_last_status);
3227 #endif
3229 escaped = g_strescape (test_trap_last_stdout, NULL);
3230 g_test_message ("child process (%s) stdout: \"%s\"", process_id, escaped);
3231 g_free (escaped);
3233 escaped = g_strescape (test_trap_last_stderr, NULL);
3234 g_test_message ("child process (%s) stderr: \"%s\"", process_id, escaped);
3235 g_free (escaped);
3237 /* so we can use short-circuiting:
3238 * logged_child_output = logged_child_output || log_child_output (...) */
3239 return TRUE;
3242 void
3243 g_test_trap_assertions (const char *domain,
3244 const char *file,
3245 int line,
3246 const char *func,
3247 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
3248 const char *pattern)
3250 gboolean must_pass = assertion_flags == 0;
3251 gboolean must_fail = assertion_flags == 1;
3252 gboolean match_result = 0 == (assertion_flags & 1);
3253 gboolean logged_child_output = FALSE;
3254 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
3255 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
3256 const char *match_error = match_result ? "failed to match" : "contains invalid match";
3257 char *process_id;
3259 #ifdef G_OS_UNIX
3260 if (test_trap_last_subprocess != NULL)
3262 process_id = g_strdup_printf ("%s [%d]", test_trap_last_subprocess,
3263 test_trap_last_pid);
3265 else if (test_trap_last_pid != 0)
3266 process_id = g_strdup_printf ("%d", test_trap_last_pid);
3267 #else
3268 if (test_trap_last_subprocess != NULL)
3269 process_id = g_strdup (test_trap_last_subprocess);
3270 #endif
3271 else
3272 g_error ("g_test_trap_ assertion with no trapped test");
3274 if (must_pass && !g_test_trap_has_passed())
3276 char *msg;
3278 logged_child_output = logged_child_output || log_child_output (process_id);
3280 msg = g_strdup_printf ("child process (%s) failed unexpectedly", process_id);
3281 g_assertion_message (domain, file, line, func, msg);
3282 g_free (msg);
3284 if (must_fail && g_test_trap_has_passed())
3286 char *msg;
3288 logged_child_output = logged_child_output || log_child_output (process_id);
3290 msg = g_strdup_printf ("child process (%s) did not fail as expected", process_id);
3291 g_assertion_message (domain, file, line, func, msg);
3292 g_free (msg);
3294 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
3296 char *msg;
3298 logged_child_output = logged_child_output || log_child_output (process_id);
3300 msg = g_strdup_printf ("stdout of child process (%s) %s: %s", process_id, match_error, stdout_pattern);
3301 g_assertion_message (domain, file, line, func, msg);
3302 g_free (msg);
3304 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
3306 char *msg;
3308 logged_child_output = logged_child_output || log_child_output (process_id);
3310 msg = g_strdup_printf ("stderr of child process (%s) %s: %s", process_id, match_error, stderr_pattern);
3311 g_assertion_message (domain, file, line, func, msg);
3312 g_free (msg);
3314 g_free (process_id);
3317 static void
3318 gstring_overwrite_int (GString *gstring,
3319 guint pos,
3320 guint32 vuint)
3322 vuint = g_htonl (vuint);
3323 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
3326 static void
3327 gstring_append_int (GString *gstring,
3328 guint32 vuint)
3330 vuint = g_htonl (vuint);
3331 g_string_append_len (gstring, (const gchar*) &vuint, 4);
3334 static void
3335 gstring_append_double (GString *gstring,
3336 double vdouble)
3338 union { double vdouble; guint64 vuint64; } u;
3339 u.vdouble = vdouble;
3340 u.vuint64 = GUINT64_TO_BE (u.vuint64);
3341 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
3344 static guint8*
3345 g_test_log_dump (GTestLogMsg *msg,
3346 guint *len)
3348 GString *gstring = g_string_sized_new (1024);
3349 guint ui;
3350 gstring_append_int (gstring, 0); /* message length */
3351 gstring_append_int (gstring, msg->log_type);
3352 gstring_append_int (gstring, msg->n_strings);
3353 gstring_append_int (gstring, msg->n_nums);
3354 gstring_append_int (gstring, 0); /* reserved */
3355 for (ui = 0; ui < msg->n_strings; ui++)
3357 guint l = strlen (msg->strings[ui]);
3358 gstring_append_int (gstring, l);
3359 g_string_append_len (gstring, msg->strings[ui], l);
3361 for (ui = 0; ui < msg->n_nums; ui++)
3362 gstring_append_double (gstring, msg->nums[ui]);
3363 *len = gstring->len;
3364 gstring_overwrite_int (gstring, 0, *len); /* message length */
3365 return (guint8*) g_string_free (gstring, FALSE);
3368 static inline long double
3369 net_double (const gchar **ipointer)
3371 union { guint64 vuint64; double vdouble; } u;
3372 guint64 aligned_int64;
3373 memcpy (&aligned_int64, *ipointer, 8);
3374 *ipointer += 8;
3375 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
3376 return u.vdouble;
3379 static inline guint32
3380 net_int (const gchar **ipointer)
3382 guint32 aligned_int;
3383 memcpy (&aligned_int, *ipointer, 4);
3384 *ipointer += 4;
3385 return g_ntohl (aligned_int);
3388 static gboolean
3389 g_test_log_extract (GTestLogBuffer *tbuffer)
3391 const gchar *p = tbuffer->data->str;
3392 GTestLogMsg msg;
3393 guint mlength;
3394 if (tbuffer->data->len < 4 * 5)
3395 return FALSE;
3396 mlength = net_int (&p);
3397 if (tbuffer->data->len < mlength)
3398 return FALSE;
3399 msg.log_type = net_int (&p);
3400 msg.n_strings = net_int (&p);
3401 msg.n_nums = net_int (&p);
3402 if (net_int (&p) == 0)
3404 guint ui;
3405 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
3406 msg.nums = g_new0 (long double, msg.n_nums);
3407 for (ui = 0; ui < msg.n_strings; ui++)
3409 guint sl = net_int (&p);
3410 msg.strings[ui] = g_strndup (p, sl);
3411 p += sl;
3413 for (ui = 0; ui < msg.n_nums; ui++)
3414 msg.nums[ui] = net_double (&p);
3415 if (p <= tbuffer->data->str + mlength)
3417 g_string_erase (tbuffer->data, 0, mlength);
3418 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
3419 return TRUE;
3422 g_free (msg.nums);
3423 g_strfreev (msg.strings);
3426 g_error ("corrupt log stream from test program");
3427 return FALSE;
3431 * g_test_log_buffer_new:
3433 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3435 GTestLogBuffer*
3436 g_test_log_buffer_new (void)
3438 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
3439 tb->data = g_string_sized_new (1024);
3440 return tb;
3444 * g_test_log_buffer_free:
3446 * Internal function for gtester to free test log messages, no ABI guarantees provided.
3448 void
3449 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
3451 g_return_if_fail (tbuffer != NULL);
3452 while (tbuffer->msgs)
3453 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
3454 g_string_free (tbuffer->data, TRUE);
3455 g_free (tbuffer);
3459 * g_test_log_buffer_push:
3461 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3463 void
3464 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
3465 guint n_bytes,
3466 const guint8 *bytes)
3468 g_return_if_fail (tbuffer != NULL);
3469 if (n_bytes)
3471 gboolean more_messages;
3472 g_return_if_fail (bytes != NULL);
3473 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
3475 more_messages = g_test_log_extract (tbuffer);
3476 while (more_messages);
3481 * g_test_log_buffer_pop:
3483 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
3485 GTestLogMsg*
3486 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
3488 GTestLogMsg *msg = NULL;
3489 g_return_val_if_fail (tbuffer != NULL, NULL);
3490 if (tbuffer->msgs)
3492 GSList *slist = g_slist_last (tbuffer->msgs);
3493 msg = slist->data;
3494 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
3496 return msg;
3500 * g_test_log_msg_free:
3502 * Internal function for gtester to free test log messages, no ABI guarantees provided.
3504 void
3505 g_test_log_msg_free (GTestLogMsg *tmsg)
3507 g_return_if_fail (tmsg != NULL);
3508 g_strfreev (tmsg->strings);
3509 g_free (tmsg->nums);
3510 g_free (tmsg);
3513 static gchar *
3514 g_test_build_filename_va (GTestFileType file_type,
3515 const gchar *first_path,
3516 va_list ap)
3518 const gchar *pathv[16];
3519 gint num_path_segments;
3521 if (file_type == G_TEST_DIST)
3522 pathv[0] = test_disted_files_dir;
3523 else if (file_type == G_TEST_BUILT)
3524 pathv[0] = test_built_files_dir;
3525 else
3526 g_assert_not_reached ();
3528 pathv[1] = first_path;
3530 for (num_path_segments = 2; num_path_segments < G_N_ELEMENTS (pathv); num_path_segments++)
3532 pathv[num_path_segments] = va_arg (ap, const char *);
3533 if (pathv[num_path_segments] == NULL)
3534 break;
3537 g_assert_cmpint (num_path_segments, <, G_N_ELEMENTS (pathv));
3539 return g_build_filenamev ((gchar **) pathv);
3543 * g_test_build_filename:
3544 * @file_type: the type of file (built vs. distributed)
3545 * @first_path: the first segment of the pathname
3546 * @...: %NULL-terminated additional path segments
3548 * Creates the pathname to a data file that is required for a test.
3550 * This function is conceptually similar to g_build_filename() except
3551 * that the first argument has been replaced with a #GTestFileType
3552 * argument.
3554 * The data file should either have been distributed with the module
3555 * containing the test (%G_TEST_DIST) or built as part of the build
3556 * system of that module (%G_TEST_BUILT).
3558 * In order for this function to work in srcdir != builddir situations,
3559 * the G_TEST_SRCDIR and G_TEST_BUILDDIR environment variables need to
3560 * have been defined. As of 2.38, this is done by the glib.mk
3561 * included in GLib. Please ensure that your copy is up to date before
3562 * using this function.
3564 * In case neither variable is set, this function will fall back to
3565 * using the dirname portion of argv[0], possibly removing ".libs".
3566 * This allows for casual running of tests directly from the commandline
3567 * in the srcdir == builddir case and should also support running of
3568 * installed tests, assuming the data files have been installed in the
3569 * same relative path as the test binary.
3571 * Returns: the path of the file, to be freed using g_free()
3573 * Since: 2.38
3576 * GTestFileType:
3577 * @G_TEST_DIST: a file that was included in the distribution tarball
3578 * @G_TEST_BUILT: a file that was built on the compiling machine
3580 * The type of file to return the filename for, when used with
3581 * g_test_build_filename().
3583 * These two options correspond rather directly to the 'dist' and
3584 * 'built' terminology that automake uses and are explicitly used to
3585 * distinguish between the 'srcdir' and 'builddir' being separate. All
3586 * files in your project should either be dist (in the
3587 * `EXTRA_DIST` or `dist_schema_DATA`
3588 * sense, in which case they will always be in the srcdir) or built (in
3589 * the `BUILT_SOURCES` sense, in which case they will
3590 * always be in the builddir).
3592 * Note: as a general rule of automake, files that are generated only as
3593 * part of the build-from-git process (but then are distributed with the
3594 * tarball) always go in srcdir (even if doing a srcdir != builddir
3595 * build from git) and are considered as distributed files.
3597 * Since: 2.38
3599 gchar *
3600 g_test_build_filename (GTestFileType file_type,
3601 const gchar *first_path,
3602 ...)
3604 gchar *result;
3605 va_list ap;
3607 g_assert (g_test_initialized ());
3609 va_start (ap, first_path);
3610 result = g_test_build_filename_va (file_type, first_path, ap);
3611 va_end (ap);
3613 return result;
3617 * g_test_get_dir:
3618 * @file_type: the type of file (built vs. distributed)
3620 * Gets the pathname of the directory containing test files of the type
3621 * specified by @file_type.
3623 * This is approximately the same as calling g_test_build_filename("."),
3624 * but you don't need to free the return value.
3626 * Returns: (type filename): the path of the directory, owned by GLib
3628 * Since: 2.38
3630 const gchar *
3631 g_test_get_dir (GTestFileType file_type)
3633 g_assert (g_test_initialized ());
3635 if (file_type == G_TEST_DIST)
3636 return test_disted_files_dir;
3637 else if (file_type == G_TEST_BUILT)
3638 return test_built_files_dir;
3640 g_assert_not_reached ();
3644 * g_test_get_filename:
3645 * @file_type: the type of file (built vs. distributed)
3646 * @first_path: the first segment of the pathname
3647 * @...: %NULL-terminated additional path segments
3649 * Gets the pathname to a data file that is required for a test.
3651 * This is the same as g_test_build_filename() with two differences.
3652 * The first difference is that must only use this function from within
3653 * a testcase function. The second difference is that you need not free
3654 * the return value -- it will be automatically freed when the testcase
3655 * finishes running.
3657 * It is safe to use this function from a thread inside of a testcase
3658 * but you must ensure that all such uses occur before the main testcase
3659 * function returns (ie: it is best to ensure that all threads have been
3660 * joined).
3662 * Returns: the path, automatically freed at the end of the testcase
3664 * Since: 2.38
3666 const gchar *
3667 g_test_get_filename (GTestFileType file_type,
3668 const gchar *first_path,
3669 ...)
3671 gchar *result;
3672 GSList *node;
3673 va_list ap;
3675 g_assert (g_test_initialized ());
3676 if (test_filename_free_list == NULL)
3677 g_error ("g_test_get_filename() can only be used within testcase functions");
3679 va_start (ap, first_path);
3680 result = g_test_build_filename_va (file_type, first_path, ap);
3681 va_end (ap);
3683 node = g_slist_prepend (NULL, result);
3685 node->next = *test_filename_free_list;
3686 while (!g_atomic_pointer_compare_and_exchange (test_filename_free_list, node->next, node));
3688 return result;
3691 /* --- macros docs START --- */
3693 * g_test_add:
3694 * @testpath: The test path for a new test case.
3695 * @Fixture: The type of a fixture data structure.
3696 * @tdata: Data argument for the test functions.
3697 * @fsetup: The function to set up the fixture data.
3698 * @ftest: The actual test function.
3699 * @fteardown: The function to tear down the fixture data.
3701 * Hook up a new test case at @testpath, similar to g_test_add_func().
3702 * A fixture data structure with setup and teardown functions may be provided,
3703 * similar to g_test_create_case().
3705 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
3706 * fteardown() callbacks can expect a @Fixture pointer as their first argument
3707 * in a type safe manner. They otherwise have type #GTestFixtureFunc.
3709 * Since: 2.16
3711 /* --- macros docs END --- */