docs: Fix a minor syntax error in a documentation comment
[glib.git] / glib / gtestutils.c
blobda6c7338cb9b6a1680df089b0e84adcee03ea285
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_true(), 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_true() is that the assertion
95 * messages can be more elaborate, and include the values of the compared
96 * entities.
98 * Note that g_assert() should not be used in unit tests, since it is a no-op
99 * when compiling with `G_DISABLE_ASSERT`. Use g_assert() in production code,
100 * and g_assert_true() in unit tests.
102 * A full example of creating a test suite with two tests using fixtures:
103 * |[<!-- language="C" -->
104 * #include <glib.h>
105 * #include <locale.h>
107 * typedef struct {
108 * MyObject *obj;
109 * OtherObject *helper;
110 * } MyObjectFixture;
112 * static void
113 * my_object_fixture_set_up (MyObjectFixture *fixture,
114 * gconstpointer user_data)
116 * fixture->obj = my_object_new ();
117 * my_object_set_prop1 (fixture->obj, "some-value");
118 * my_object_do_some_complex_setup (fixture->obj, user_data);
120 * fixture->helper = other_object_new ();
123 * static void
124 * my_object_fixture_tear_down (MyObjectFixture *fixture,
125 * gconstpointer user_data)
127 * g_clear_object (&fixture->helper);
128 * g_clear_object (&fixture->obj);
131 * static void
132 * test_my_object_test1 (MyObjectFixture *fixture,
133 * gconstpointer user_data)
135 * g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "initial-value");
138 * static void
139 * test_my_object_test2 (MyObjectFixture *fixture,
140 * gconstpointer user_data)
142 * my_object_do_some_work_using_helper (fixture->obj, fixture->helper);
143 * g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "updated-value");
146 * int
147 * main (int argc, char *argv[])
149 * setlocale (LC_ALL, "");
151 * g_test_init (&argc, &argv, NULL);
152 * g_test_bug_base ("http://bugzilla.gnome.org/show_bug.cgi?id=");
154 * // Define the tests.
155 * g_test_add ("/my-object/test1", MyObjectFixture, "some-user-data",
156 * my_object_fixture_set_up, test_my_object_test1,
157 * my_object_fixture_tear_down);
158 * g_test_add ("/my-object/test2", MyObjectFixture, "some-user-data",
159 * my_object_fixture_set_up, test_my_object_test2,
160 * my_object_fixture_tear_down);
162 * return g_test_run ();
164 * ]|
166 * ### Integrating GTest in your project
168 * If you are using the [Meson](http://mesonbuild.com) build system, you will
169 * typically use the provided `test()` primitive to call the test binaries,
170 * e.g.:
172 * |[<!-- language="plain" -->
173 * test(
174 * 'foo',
175 * executable('foo', 'foo.c', dependencies: deps),
176 * env: [
177 * 'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
178 * 'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
179 * ],
182 * test(
183 * 'bar',
184 * executable('bar', 'bar.c', dependencies: deps),
185 * env: [
186 * 'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
187 * 'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
188 * ],
190 * ]|
192 * If you are using Autotools, you're strongly encouraged to use the Automake
193 * [TAP](https://testanything.org/) harness; GLib provides template files for
194 * easily integrating with it:
196 * - [glib-tap.mk](https://git.gnome.org/browse/glib/tree/glib-tap.mk)
197 * - [tap-test](https://git.gnome.org/browse/glib/tree/tap-test)
198 * - [tap-driver.sh](https://git.gnome.org/browse/glib/tree/tap-driver.sh)
200 * You can copy these files in your own project's root directory, and then
201 * set up your `Makefile.am` file to reference them, for instance:
203 * |[<!-- language="plain" -->
204 * include $(top_srcdir)/glib-tap.mk
206 * # test binaries
207 * test_programs = \
208 * foo \
209 * bar
211 * # data distributed in the tarball
212 * dist_test_data = \
213 * foo.data.txt \
214 * bar.data.txt
216 * # data not distributed in the tarball
217 * test_data = \
218 * blah.data.txt
219 * ]|
221 * Make sure to distribute the TAP files, using something like the following
222 * in your top-level `Makefile.am`:
224 * |[<!-- language="plain" -->
225 * EXTRA_DIST += \
226 * tap-driver.sh \
227 * tap-test
228 * ]|
230 * `glib-tap.mk` will be distributed implicitly due to being included in a
231 * `Makefile.am`. All three files should be added to version control.
233 * If you don't have access to the Autotools TAP harness, you can use the
234 * [gtester][gtester] and [gtester-report][gtester-report] tools, and use
235 * the [glib.mk](https://git.gnome.org/browse/glib/tree/glib.mk) Automake
236 * template provided by GLib.
240 * g_test_initialized:
242 * Returns %TRUE if g_test_init() has been called.
244 * Returns: %TRUE if g_test_init() has been called.
246 * Since: 2.36
250 * g_test_quick:
252 * Returns %TRUE if tests are run in quick mode.
253 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
254 * there is no "medium speed".
256 * By default, tests are run in quick mode. In tests that use
257 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
258 * can be used to change this.
260 * Returns: %TRUE if in quick mode
264 * g_test_slow:
266 * Returns %TRUE if tests are run in slow mode.
267 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
268 * there is no "medium speed".
270 * By default, tests are run in quick mode. In tests that use
271 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
272 * can be used to change this.
274 * Returns: the opposite of g_test_quick()
278 * g_test_thorough:
280 * Returns %TRUE if tests are run in thorough mode, equivalent to
281 * g_test_slow().
283 * By default, tests are run in quick mode. In tests that use
284 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
285 * can be used to change this.
287 * Returns: the same thing as g_test_slow()
291 * g_test_perf:
293 * Returns %TRUE if tests are run in performance mode.
295 * By default, tests are run in quick mode. In tests that use
296 * g_test_init(), the option `-m perf` enables performance tests, while
297 * `-m quick` disables them.
299 * Returns: %TRUE if in performance mode
303 * g_test_undefined:
305 * Returns %TRUE if tests may provoke assertions and other formally-undefined
306 * behaviour, to verify that appropriate warnings are given. It might, in some
307 * cases, be useful to turn this off with if running tests under valgrind;
308 * in tests that use g_test_init(), the option `-m no-undefined` disables
309 * those tests, while `-m undefined` explicitly enables them (the default
310 * behaviour).
312 * Returns: %TRUE if tests may provoke programming errors
316 * g_test_verbose:
318 * Returns %TRUE if tests are run in verbose mode.
319 * In tests that use g_test_init(), the option `--verbose` enables this,
320 * while `-q` or `--quiet` disables it.
321 * The default is neither g_test_verbose() nor g_test_quiet().
323 * Returns: %TRUE if in verbose mode
327 * g_test_quiet:
329 * Returns %TRUE if tests are run in quiet mode.
330 * In tests that use g_test_init(), the option `-q` or `--quiet` enables
331 * this, while `--verbose` disables it.
332 * The default is neither g_test_verbose() nor g_test_quiet().
334 * Returns: %TRUE if in quiet mode
338 * g_test_queue_unref:
339 * @gobject: the object to unref
341 * Enqueue an object to be released with g_object_unref() during
342 * the next teardown phase. This is equivalent to calling
343 * g_test_queue_destroy() with a destroy callback of g_object_unref().
345 * Since: 2.16
349 * GTestTrapFlags:
350 * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout 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_stdout().
354 * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
355 * `/dev/null` so it cannot be observed on the console during test
356 * runs. The actual output is still captured though to allow later
357 * tests with g_test_trap_assert_stderr().
358 * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
359 * child process is shared with stdin of its parent process.
360 * It is redirected to `/dev/null` otherwise.
362 * Test traps are guards around forked tests.
363 * These flags determine what traps to set.
365 * Deprecated: #GTestTrapFlags is used only with g_test_trap_fork(),
366 * which is deprecated. g_test_trap_subprocess() uses
367 * #GTestSubprocessFlags.
371 * GTestSubprocessFlags:
372 * @G_TEST_SUBPROCESS_INHERIT_STDIN: If this flag is given, the child
373 * process will inherit the parent's stdin. Otherwise, the child's
374 * stdin is redirected to `/dev/null`.
375 * @G_TEST_SUBPROCESS_INHERIT_STDOUT: If this flag is given, the child
376 * process will inherit the parent's stdout. Otherwise, the child's
377 * stdout will not be visible, but it will be captured to allow
378 * later tests with g_test_trap_assert_stdout().
379 * @G_TEST_SUBPROCESS_INHERIT_STDERR: If this flag is given, the child
380 * process will inherit the parent's stderr. Otherwise, the child's
381 * stderr will not be visible, but it will be captured to allow
382 * later tests with g_test_trap_assert_stderr().
384 * Flags to pass to g_test_trap_subprocess() to control input and output.
386 * Note that in contrast with g_test_trap_fork(), the default is to
387 * not show stdout and stderr.
391 * g_test_trap_assert_passed:
393 * Assert that the last test subprocess passed.
394 * See g_test_trap_subprocess().
396 * Since: 2.16
400 * g_test_trap_assert_failed:
402 * Assert that the last test subprocess failed.
403 * See g_test_trap_subprocess().
405 * This is sometimes used to test situations that are formally considered to
406 * be undefined behaviour, like inputs that fail a g_return_if_fail()
407 * check. In these situations you should skip the entire test, including the
408 * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
409 * to indicate that undefined behaviour may be tested.
411 * Since: 2.16
415 * g_test_trap_assert_stdout:
416 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
418 * Assert that the stdout output of the last test subprocess matches
419 * @soutpattern. See g_test_trap_subprocess().
421 * Since: 2.16
425 * g_test_trap_assert_stdout_unmatched:
426 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
428 * Assert that the stdout output of the last test subprocess
429 * does not match @soutpattern. See g_test_trap_subprocess().
431 * Since: 2.16
435 * g_test_trap_assert_stderr:
436 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
438 * Assert that the stderr output of the last test subprocess
439 * matches @serrpattern. See g_test_trap_subprocess().
441 * This is sometimes used to test situations that are formally
442 * considered to be undefined behaviour, like code that hits a
443 * g_assert() or g_error(). In these situations you should skip the
444 * entire test, including the call to g_test_trap_subprocess(), unless
445 * g_test_undefined() returns %TRUE to indicate that undefined
446 * behaviour may be tested.
448 * Since: 2.16
452 * g_test_trap_assert_stderr_unmatched:
453 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
455 * Assert that the stderr output of the last test subprocess
456 * does not match @serrpattern. See g_test_trap_subprocess().
458 * Since: 2.16
462 * g_test_rand_bit:
464 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
465 * for details on test case random numbers.
467 * Since: 2.16
471 * g_assert:
472 * @expr: the expression to check
474 * Debugging macro to terminate the application if the assertion
475 * fails. If the assertion fails (i.e. the expression is not true),
476 * an error message is logged and the application is terminated.
478 * The macro can be turned off in final releases of code by defining
479 * `G_DISABLE_ASSERT` when compiling the application, so code must
480 * not depend on any side effects from @expr. Similarly, it must not be used
481 * in unit tests, otherwise the unit tests will be ineffective if compiled with
482 * `G_DISABLE_ASSERT`. Use g_assert_true() and related macros in unit tests
483 * instead.
487 * g_assert_not_reached:
489 * Debugging macro to terminate the application if it is ever
490 * reached. If it is reached, an error message is logged and the
491 * application is terminated.
493 * The macro can be turned off in final releases of code by defining
494 * `G_DISABLE_ASSERT` when compiling the application. Hence, it should not be
495 * used in unit tests, where assertions should always be effective.
499 * g_assert_true:
500 * @expr: the expression to check
502 * Debugging macro to check that an expression is true.
504 * If the assertion fails (i.e. the expression is not true),
505 * an error message is logged and the application is either
506 * terminated or the testcase marked as failed.
508 * Note that unlike g_assert(), this macro is unaffected by whether
509 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
510 * conversely, g_assert() should not be used in tests.
512 * See g_test_set_nonfatal_assertions().
514 * Since: 2.38
518 * g_assert_false:
519 * @expr: the expression to check
521 * Debugging macro to check an expression is false.
523 * If the assertion fails (i.e. the expression is not false),
524 * an error message is logged and the application is either
525 * terminated or the testcase marked as failed.
527 * Note that unlike g_assert(), this macro is unaffected by whether
528 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
529 * conversely, g_assert() should not be used in tests.
531 * See g_test_set_nonfatal_assertions().
533 * Since: 2.38
537 * g_assert_null:
538 * @expr: the expression to check
540 * Debugging macro to check an expression is %NULL.
542 * If the assertion fails (i.e. the expression is not %NULL),
543 * an error message is logged and the application is either
544 * terminated or the testcase marked as failed.
546 * Note that unlike g_assert(), this macro is unaffected by whether
547 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
548 * conversely, g_assert() should not be used in tests.
550 * See g_test_set_nonfatal_assertions().
552 * Since: 2.38
556 * g_assert_nonnull:
557 * @expr: the expression to check
559 * Debugging macro to check an expression is not %NULL.
561 * If the assertion fails (i.e. the expression is %NULL),
562 * an error message is logged and the application is either
563 * terminated or the testcase marked as failed.
565 * Note that unlike g_assert(), this macro is unaffected by whether
566 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
567 * conversely, g_assert() should not be used in tests.
569 * See g_test_set_nonfatal_assertions().
571 * Since: 2.40
575 * g_assert_cmpstr:
576 * @s1: a string (may be %NULL)
577 * @cmp: The comparison operator to use.
578 * One of ==, !=, <, >, <=, >=.
579 * @s2: another string (may be %NULL)
581 * Debugging macro to compare two strings. If the comparison fails,
582 * an error message is logged and the application is either terminated
583 * or the testcase marked as failed.
584 * The strings are compared using g_strcmp0().
586 * The effect of `g_assert_cmpstr (s1, op, s2)` is
587 * the same as `g_assert_true (g_strcmp0 (s1, s2) op 0)`.
588 * The advantage of this macro is that it can produce a message that
589 * includes the actual values of @s1 and @s2.
591 * |[<!-- language="C" -->
592 * g_assert_cmpstr (mystring, ==, "fubar");
593 * ]|
595 * Since: 2.16
599 * g_assert_cmpint:
600 * @n1: an integer
601 * @cmp: The comparison operator to use.
602 * One of ==, !=, <, >, <=, >=.
603 * @n2: another integer
605 * Debugging macro to compare two integers.
607 * The effect of `g_assert_cmpint (n1, op, n2)` is
608 * the same as `g_assert_true (n1 op n2)`. The advantage
609 * of this macro is that it can produce a message that includes the
610 * actual values of @n1 and @n2.
612 * Since: 2.16
616 * g_assert_cmpuint:
617 * @n1: an unsigned integer
618 * @cmp: The comparison operator to use.
619 * One of ==, !=, <, >, <=, >=.
620 * @n2: another unsigned integer
622 * Debugging macro to compare two unsigned integers.
624 * The effect of `g_assert_cmpuint (n1, op, n2)` is
625 * the same as `g_assert_true (n1 op n2)`. The advantage
626 * of this macro is that it can produce a message that includes the
627 * actual values of @n1 and @n2.
629 * Since: 2.16
633 * g_assert_cmphex:
634 * @n1: an unsigned integer
635 * @cmp: The comparison operator to use.
636 * One of ==, !=, <, >, <=, >=.
637 * @n2: another unsigned integer
639 * Debugging macro to compare to unsigned integers.
641 * This is a variant of g_assert_cmpuint() that displays the numbers
642 * in hexadecimal notation in the message.
644 * Since: 2.16
648 * g_assert_cmpfloat:
649 * @n1: an floating point number
650 * @cmp: The comparison operator to use.
651 * One of ==, !=, <, >, <=, >=.
652 * @n2: another floating point number
654 * Debugging macro to compare two floating point numbers.
656 * The effect of `g_assert_cmpfloat (n1, op, n2)` is
657 * the same as `g_assert_true (n1 op n2)`. The advantage
658 * of this macro is that it can produce a message that includes the
659 * actual values of @n1 and @n2.
661 * Since: 2.16
665 * g_assert_cmpfloat_with_epsilon:
666 * @n1: an floating point number
667 * @n2: another floating point number
668 * @epsilon: a numeric value that expresses the expected tolerance
669 * between @n1 and @n2
671 * Debugging macro to compare two floating point numbers within an epsilon.
673 * The effect of `g_assert_cmpfloat_with_epsilon (n1, n2, epsilon)` is
674 * the same as `g_assert_true (abs (n1 - n2) < epsilon)`. The advantage
675 * of this macro is that it can produce a message that includes the
676 * actual values of @n1 and @n2.
678 * Since: 2.58
682 * g_assert_cmpmem:
683 * @m1: pointer to a buffer
684 * @l1: length of @m1
685 * @m2: pointer to another buffer
686 * @l2: length of @m2
688 * Debugging macro to compare memory regions. If the comparison fails,
689 * an error message is logged and the application is either terminated
690 * or the testcase marked as failed.
692 * The effect of `g_assert_cmpmem (m1, l1, m2, l2)` is
693 * the same as `g_assert_true (l1 == l2 && memcmp (m1, m2, l1) == 0)`.
694 * The advantage of this macro is that it can produce a message that
695 * includes the actual values of @l1 and @l2.
697 * |[<!-- language="C" -->
698 * g_assert_cmpmem (buf->data, buf->len, expected, sizeof (expected));
699 * ]|
701 * Since: 2.46
705 * g_assert_no_error:
706 * @err: a #GError, possibly %NULL
708 * Debugging macro to check that a #GError is not set.
710 * The effect of `g_assert_no_error (err)` is
711 * the same as `g_assert_true (err == NULL)`. The advantage
712 * of this macro is that it can produce a message that includes
713 * the error message and code.
715 * Since: 2.20
719 * g_assert_error:
720 * @err: a #GError, possibly %NULL
721 * @dom: the expected error domain (a #GQuark)
722 * @c: the expected error code
724 * Debugging macro to check that a method has returned
725 * the correct #GError.
727 * The effect of `g_assert_error (err, dom, c)` is
728 * the same as `g_assert_true (err != NULL && err->domain
729 * == dom && err->code == c)`. The advantage of this
730 * macro is that it can produce a message that includes the incorrect
731 * error message and code.
733 * This can only be used to test for a specific error. If you want to
734 * test that @err is set, but don't care what it's set to, just use
735 * `g_assert (err != NULL)`
737 * Since: 2.20
741 * GTestCase:
743 * An opaque structure representing a test case.
747 * GTestSuite:
749 * An opaque structure representing a test suite.
753 /* Global variable for storing assertion messages; this is the counterpart to
754 * glibc's (private) __abort_msg variable, and allows developers and crash
755 * analysis systems like Apport and ABRT to fish out assertion messages from
756 * core dumps, instead of having to catch them on screen output.
758 GLIB_VAR char *__glib_assert_msg;
759 char *__glib_assert_msg = NULL;
761 /* --- constants --- */
762 #define G_TEST_STATUS_TIMED_OUT 1024
764 /* --- structures --- */
765 struct GTestCase
767 gchar *name;
768 guint fixture_size;
769 void (*fixture_setup) (void*, gconstpointer);
770 void (*fixture_test) (void*, gconstpointer);
771 void (*fixture_teardown) (void*, gconstpointer);
772 gpointer test_data;
774 struct GTestSuite
776 gchar *name;
777 GSList *suites;
778 GSList *cases;
780 typedef struct DestroyEntry DestroyEntry;
781 struct DestroyEntry
783 DestroyEntry *next;
784 GDestroyNotify destroy_func;
785 gpointer destroy_data;
788 /* --- prototypes --- */
789 static void test_run_seed (const gchar *rseed);
790 static void test_trap_clear (void);
791 static guint8* g_test_log_dump (GTestLogMsg *msg,
792 guint *len);
793 static void gtest_default_log_handler (const gchar *log_domain,
794 GLogLevelFlags log_level,
795 const gchar *message,
796 gpointer unused_data);
799 static const char * const g_test_result_names[] = {
800 "OK",
801 "SKIP",
802 "FAIL",
803 "TODO"
806 /* --- variables --- */
807 static int test_log_fd = -1;
808 static gboolean test_mode_fatal = TRUE;
809 static gboolean g_test_run_once = TRUE;
810 static gboolean test_run_list = FALSE;
811 static gchar *test_run_seedstr = NULL;
812 static GRand *test_run_rand = NULL;
813 static gchar *test_run_name = "";
814 static GSList **test_filename_free_list;
815 static guint test_run_forks = 0;
816 static guint test_run_count = 0;
817 static guint test_count = 0;
818 static guint test_skipped_count = 0;
819 static GTestResult test_run_success = G_TEST_RUN_FAILURE;
820 static gchar *test_run_msg = NULL;
821 static guint test_startup_skip_count = 0;
822 static GTimer *test_user_timer = NULL;
823 static double test_user_stamp = 0;
824 static GSList *test_paths = NULL;
825 static GSList *test_paths_skipped = NULL;
826 static GTestSuite *test_suite_root = NULL;
827 static int test_trap_last_status = 0; /* unmodified platform-specific status */
828 static GPid test_trap_last_pid = 0;
829 static char *test_trap_last_subprocess = NULL;
830 static char *test_trap_last_stdout = NULL;
831 static char *test_trap_last_stderr = NULL;
832 static char *test_uri_base = NULL;
833 static gboolean test_debug_log = FALSE;
834 static gboolean test_tap_log = FALSE;
835 static gboolean test_nonfatal_assertions = FALSE;
836 static DestroyEntry *test_destroy_queue = NULL;
837 static char *test_argv0 = NULL;
838 static char *test_argv0_dirname;
839 static const char *test_disted_files_dir;
840 static const char *test_built_files_dir;
841 static char *test_initial_cwd = NULL;
842 static gboolean test_in_forked_child = FALSE;
843 static gboolean test_in_subprocess = FALSE;
844 static GTestConfig mutable_test_config_vars = {
845 FALSE, /* test_initialized */
846 TRUE, /* test_quick */
847 FALSE, /* test_perf */
848 FALSE, /* test_verbose */
849 FALSE, /* test_quiet */
850 TRUE, /* test_undefined */
852 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
853 static gboolean no_g_set_prgname = FALSE;
855 /* --- functions --- */
856 const char*
857 g_test_log_type_name (GTestLogType log_type)
859 switch (log_type)
861 case G_TEST_LOG_NONE: return "none";
862 case G_TEST_LOG_ERROR: return "error";
863 case G_TEST_LOG_START_BINARY: return "binary";
864 case G_TEST_LOG_LIST_CASE: return "list";
865 case G_TEST_LOG_SKIP_CASE: return "skip";
866 case G_TEST_LOG_START_CASE: return "start";
867 case G_TEST_LOG_STOP_CASE: return "stop";
868 case G_TEST_LOG_MIN_RESULT: return "minperf";
869 case G_TEST_LOG_MAX_RESULT: return "maxperf";
870 case G_TEST_LOG_MESSAGE: return "message";
871 case G_TEST_LOG_START_SUITE: return "start suite";
872 case G_TEST_LOG_STOP_SUITE: return "stop suite";
874 return "???";
877 static void
878 g_test_log_send (guint n_bytes,
879 const guint8 *buffer)
881 if (test_log_fd >= 0)
883 int r;
885 r = write (test_log_fd, buffer, n_bytes);
886 while (r < 0 && errno == EINTR);
888 if (test_debug_log)
890 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
891 GTestLogMsg *msg;
892 guint ui;
893 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
894 msg = g_test_log_buffer_pop (lbuffer);
895 g_warn_if_fail (msg != NULL);
896 g_warn_if_fail (lbuffer->data->len == 0);
897 g_test_log_buffer_free (lbuffer);
898 /* print message */
899 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
900 for (ui = 0; ui < msg->n_strings; ui++)
901 g_printerr (":{%s}", msg->strings[ui]);
902 if (msg->n_nums)
904 g_printerr (":(");
905 for (ui = 0; ui < msg->n_nums; ui++)
907 if ((long double) (long) msg->nums[ui] == msg->nums[ui])
908 g_printerr ("%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
909 else
910 g_printerr ("%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
912 g_printerr (")");
914 g_printerr (":LOG*}\n");
915 g_test_log_msg_free (msg);
919 static void
920 g_test_log (GTestLogType lbit,
921 const gchar *string1,
922 const gchar *string2,
923 guint n_args,
924 long double *largs)
926 GTestResult result;
927 gboolean fail;
928 GTestLogMsg msg;
929 gchar *astrings[3] = { NULL, NULL, NULL };
930 guint8 *dbuffer;
931 guint32 dbufferlen;
933 switch (lbit)
935 case G_TEST_LOG_START_BINARY:
936 if (test_tap_log)
937 g_print ("# random seed: %s\n", string2);
938 else if (g_test_verbose ())
939 g_print ("GTest: random seed: %s\n", string2);
940 break;
941 case G_TEST_LOG_START_SUITE:
942 if (test_tap_log)
944 if (string1[0] != 0)
945 g_print ("# Start of %s tests\n", string1);
946 else
947 g_print ("1..%d\n", test_count);
949 break;
950 case G_TEST_LOG_STOP_SUITE:
951 if (test_tap_log)
953 if (string1[0] != 0)
954 g_print ("# End of %s tests\n", string1);
956 break;
957 case G_TEST_LOG_STOP_CASE:
958 result = largs[0];
959 fail = result == G_TEST_RUN_FAILURE;
960 if (test_tap_log)
962 g_print ("%s %d %s", fail ? "not ok" : "ok", test_run_count, string1);
963 if (result == G_TEST_RUN_INCOMPLETE)
964 g_print (" # TODO %s\n", string2 ? string2 : "");
965 else if (result == G_TEST_RUN_SKIPPED)
966 g_print (" # SKIP %s\n", string2 ? string2 : "");
967 else
968 g_print ("\n");
970 else if (g_test_verbose ())
971 g_print ("GTest: result: %s\n", g_test_result_names[result]);
972 else if (!g_test_quiet ())
973 g_print ("%s\n", g_test_result_names[result]);
974 if (fail && test_mode_fatal)
976 if (test_tap_log)
977 g_print ("Bail out!\n");
978 g_abort ();
980 if (result == G_TEST_RUN_SKIPPED)
981 test_skipped_count++;
982 break;
983 case G_TEST_LOG_MIN_RESULT:
984 if (test_tap_log)
985 g_print ("# min perf: %s\n", string1);
986 else if (g_test_verbose ())
987 g_print ("(MINPERF:%s)\n", string1);
988 break;
989 case G_TEST_LOG_MAX_RESULT:
990 if (test_tap_log)
991 g_print ("# max perf: %s\n", string1);
992 else if (g_test_verbose ())
993 g_print ("(MAXPERF:%s)\n", string1);
994 break;
995 case G_TEST_LOG_MESSAGE:
996 if (test_tap_log)
997 g_print ("# %s\n", string1);
998 else if (g_test_verbose ())
999 g_print ("(MSG: %s)\n", string1);
1000 break;
1001 case G_TEST_LOG_ERROR:
1002 if (test_tap_log)
1003 g_print ("Bail out! %s\n", string1);
1004 else if (g_test_verbose ())
1005 g_print ("(ERROR: %s)\n", string1);
1006 break;
1007 default: ;
1010 msg.log_type = lbit;
1011 msg.n_strings = (string1 != NULL) + (string1 && string2);
1012 msg.strings = astrings;
1013 astrings[0] = (gchar*) string1;
1014 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
1015 msg.n_nums = n_args;
1016 msg.nums = largs;
1017 dbuffer = g_test_log_dump (&msg, &dbufferlen);
1018 g_test_log_send (dbufferlen, dbuffer);
1019 g_free (dbuffer);
1021 switch (lbit)
1023 case G_TEST_LOG_START_CASE:
1024 if (test_tap_log)
1026 else if (g_test_verbose ())
1027 g_print ("GTest: run: %s\n", string1);
1028 else if (!g_test_quiet ())
1029 g_print ("%s: ", string1);
1030 break;
1031 default: ;
1035 /* We intentionally parse the command line without GOptionContext
1036 * because otherwise you would never be able to test it.
1038 static void
1039 parse_args (gint *argc_p,
1040 gchar ***argv_p)
1042 guint argc = *argc_p;
1043 gchar **argv = *argv_p;
1044 guint i, e;
1046 test_argv0 = argv[0];
1047 test_initial_cwd = g_get_current_dir ();
1049 /* parse known args */
1050 for (i = 1; i < argc; i++)
1052 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
1054 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1055 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1056 g_log_set_always_fatal (fatal_mask);
1057 argv[i] = NULL;
1059 else if (strcmp (argv[i], "--keep-going") == 0 ||
1060 strcmp (argv[i], "-k") == 0)
1062 test_mode_fatal = FALSE;
1063 argv[i] = NULL;
1065 else if (strcmp (argv[i], "--debug-log") == 0)
1067 test_debug_log = TRUE;
1068 argv[i] = NULL;
1070 else if (strcmp (argv[i], "--tap") == 0)
1072 test_tap_log = TRUE;
1073 argv[i] = NULL;
1075 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
1077 gchar *equal = argv[i] + 12;
1078 if (*equal == '=')
1079 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
1080 else if (i + 1 < argc)
1082 argv[i++] = NULL;
1083 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
1085 argv[i] = NULL;
1087 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
1089 gchar *equal = argv[i] + 16;
1090 if (*equal == '=')
1091 test_startup_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
1092 else if (i + 1 < argc)
1094 argv[i++] = NULL;
1095 test_startup_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
1097 argv[i] = NULL;
1099 else if (strcmp ("--GTestSubprocess", argv[i]) == 0)
1101 test_in_subprocess = TRUE;
1102 /* We typically expect these child processes to crash, and some
1103 * tests spawn a *lot* of them. Avoid spamming system crash
1104 * collection programs such as systemd-coredump and abrt.
1106 #ifdef HAVE_SYS_RESOURCE_H
1108 struct rlimit limit = { 0, 0 };
1109 (void) setrlimit (RLIMIT_CORE, &limit);
1111 #endif
1112 argv[i] = NULL;
1114 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
1116 gchar *equal = argv[i] + 2;
1117 if (*equal == '=')
1118 test_paths = g_slist_prepend (test_paths, equal + 1);
1119 else if (i + 1 < argc)
1121 argv[i++] = NULL;
1122 test_paths = g_slist_prepend (test_paths, argv[i]);
1124 argv[i] = NULL;
1126 else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
1128 gchar *equal = argv[i] + 2;
1129 if (*equal == '=')
1130 test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
1131 else if (i + 1 < argc)
1133 argv[i++] = NULL;
1134 test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
1136 argv[i] = NULL;
1138 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
1140 gchar *equal = argv[i] + 2;
1141 const gchar *mode = "";
1142 if (*equal == '=')
1143 mode = equal + 1;
1144 else if (i + 1 < argc)
1146 argv[i++] = NULL;
1147 mode = argv[i];
1149 if (strcmp (mode, "perf") == 0)
1150 mutable_test_config_vars.test_perf = TRUE;
1151 else if (strcmp (mode, "slow") == 0)
1152 mutable_test_config_vars.test_quick = FALSE;
1153 else if (strcmp (mode, "thorough") == 0)
1154 mutable_test_config_vars.test_quick = FALSE;
1155 else if (strcmp (mode, "quick") == 0)
1157 mutable_test_config_vars.test_quick = TRUE;
1158 mutable_test_config_vars.test_perf = FALSE;
1160 else if (strcmp (mode, "undefined") == 0)
1161 mutable_test_config_vars.test_undefined = TRUE;
1162 else if (strcmp (mode, "no-undefined") == 0)
1163 mutable_test_config_vars.test_undefined = FALSE;
1164 else
1165 g_error ("unknown test mode: -m %s", mode);
1166 argv[i] = NULL;
1168 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
1170 mutable_test_config_vars.test_quiet = TRUE;
1171 mutable_test_config_vars.test_verbose = FALSE;
1172 argv[i] = NULL;
1174 else if (strcmp ("--verbose", argv[i]) == 0)
1176 mutable_test_config_vars.test_quiet = FALSE;
1177 mutable_test_config_vars.test_verbose = TRUE;
1178 argv[i] = NULL;
1180 else if (strcmp ("-l", argv[i]) == 0)
1182 test_run_list = TRUE;
1183 argv[i] = NULL;
1185 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
1187 gchar *equal = argv[i] + 6;
1188 if (*equal == '=')
1189 test_run_seedstr = equal + 1;
1190 else if (i + 1 < argc)
1192 argv[i++] = NULL;
1193 test_run_seedstr = argv[i];
1195 argv[i] = NULL;
1197 else if (strcmp ("-?", argv[i]) == 0 ||
1198 strcmp ("-h", argv[i]) == 0 ||
1199 strcmp ("--help", argv[i]) == 0)
1201 printf ("Usage:\n"
1202 " %s [OPTION...]\n\n"
1203 "Help Options:\n"
1204 " -h, --help Show help options\n\n"
1205 "Test Options:\n"
1206 " --g-fatal-warnings Make all warnings fatal\n"
1207 " -l List test cases available in a test executable\n"
1208 " -m {perf|slow|thorough|quick} Execute tests according to mode\n"
1209 " -m {undefined|no-undefined} Execute tests according to mode\n"
1210 " -p TESTPATH Only start test cases matching TESTPATH\n"
1211 " -s TESTPATH Skip all tests matching TESTPATH\n"
1212 " --seed=SEEDSTRING Start tests with random seed SEEDSTRING\n"
1213 " --debug-log debug test logging output\n"
1214 " -q, --quiet Run tests quietly\n"
1215 " --verbose Run tests verbosely\n",
1216 argv[0]);
1217 exit (0);
1220 /* collapse argv */
1221 e = 1;
1222 for (i = 1; i < argc; i++)
1223 if (argv[i])
1225 argv[e++] = argv[i];
1226 if (i >= e)
1227 argv[i] = NULL;
1229 *argc_p = e;
1233 * g_test_init:
1234 * @argc: Address of the @argc parameter of the main() function.
1235 * Changed if any arguments were handled.
1236 * @argv: Address of the @argv parameter of main().
1237 * Any parameters understood by g_test_init() stripped before return.
1238 * @...: %NULL-terminated list of special options. Currently the only
1239 * defined option is `"no_g_set_prgname"`, which
1240 * will cause g_test_init() to not call g_set_prgname().
1242 * Initialize the GLib testing framework, e.g. by seeding the
1243 * test random number generator, the name for g_get_prgname()
1244 * and parsing test related command line args.
1246 * So far, the following arguments are understood:
1248 * - `-l`: List test cases available in a test executable.
1249 * - `--seed=SEED`: Provide a random seed to reproduce test
1250 * runs using random numbers.
1251 * - `--verbose`: Run tests verbosely.
1252 * - `-q`, `--quiet`: Run tests quietly.
1253 * - `-p PATH`: Execute all tests matching the given path.
1254 * - `-s PATH`: Skip all tests matching the given path.
1255 * This can also be used to force a test to run that would otherwise
1256 * be skipped (ie, a test whose name contains "/subprocess").
1257 * - `-m {perf|slow|thorough|quick|undefined|no-undefined}`: Execute tests according to these test modes:
1259 * `perf`: Performance tests, may take long and report results (off by default).
1261 * `slow`, `thorough`: Slow and thorough tests, may take quite long and maximize coverage
1262 * (off by default).
1264 * `quick`: Quick tests, should run really quickly and give good coverage (the default).
1266 * `undefined`: Tests for undefined behaviour, may provoke programming errors
1267 * under g_test_trap_subprocess() or g_test_expect_message() to check
1268 * that appropriate assertions or warnings are given (the default).
1270 * `no-undefined`: Avoid tests for undefined behaviour
1272 * - `--debug-log`: Debug test logging output.
1274 * Since: 2.16
1276 void
1277 (g_test_init) (int *argc,
1278 char ***argv,
1279 ...)
1281 static char seedstr[4 + 4 * 8 + 1];
1282 va_list args;
1283 gpointer option;
1284 /* make warnings and criticals fatal for all test programs */
1285 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1287 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1288 g_log_set_always_fatal (fatal_mask);
1289 /* check caller args */
1290 g_return_if_fail (argc != NULL);
1291 g_return_if_fail (argv != NULL);
1292 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
1293 mutable_test_config_vars.test_initialized = TRUE;
1295 va_start (args, argv);
1296 while ((option = va_arg (args, char *)))
1298 if (g_strcmp0 (option, "no_g_set_prgname") == 0)
1299 no_g_set_prgname = TRUE;
1301 va_end (args);
1303 /* setup random seed string */
1304 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
1305 test_run_seedstr = seedstr;
1307 /* parse args, sets up mode, changes seed, etc. */
1308 parse_args (argc, argv);
1310 if (!g_get_prgname() && !no_g_set_prgname)
1311 g_set_prgname ((*argv)[0]);
1313 /* sanity check */
1314 if (test_tap_log)
1316 if (test_paths || test_startup_skip_count)
1318 /* Not invoking every test (even if SKIPped) breaks the "1..XX" plan */
1319 g_printerr ("%s: -p and --GTestSkipCount options are incompatible with --tap\n",
1320 (*argv)[0]);
1321 exit (1);
1325 /* verify GRand reliability, needed for reliable seeds */
1326 if (1)
1328 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
1329 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
1330 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
1331 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
1332 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
1333 g_rand_free (rg);
1336 /* check rand seed */
1337 test_run_seed (test_run_seedstr);
1339 /* report program start */
1340 g_log_set_default_handler (gtest_default_log_handler, NULL);
1341 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
1343 test_argv0_dirname = g_path_get_dirname (test_argv0);
1345 /* Make sure we get the real dirname that the test was run from */
1346 if (g_str_has_suffix (test_argv0_dirname, "/.libs"))
1348 gchar *tmp;
1349 tmp = g_path_get_dirname (test_argv0_dirname);
1350 g_free (test_argv0_dirname);
1351 test_argv0_dirname = tmp;
1354 test_disted_files_dir = g_getenv ("G_TEST_SRCDIR");
1355 if (!test_disted_files_dir)
1356 test_disted_files_dir = test_argv0_dirname;
1358 test_built_files_dir = g_getenv ("G_TEST_BUILDDIR");
1359 if (!test_built_files_dir)
1360 test_built_files_dir = test_argv0_dirname;
1363 static void
1364 test_run_seed (const gchar *rseed)
1366 guint seed_failed = 0;
1367 if (test_run_rand)
1368 g_rand_free (test_run_rand);
1369 test_run_rand = NULL;
1370 while (strchr (" \t\v\r\n\f", *rseed))
1371 rseed++;
1372 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
1374 const char *s = rseed + 4;
1375 if (strlen (s) >= 32) /* require 4 * 8 chars */
1377 guint32 seedarray[4];
1378 gchar *p, hexbuf[9] = { 0, };
1379 memcpy (hexbuf, s + 0, 8);
1380 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
1381 seed_failed += p != NULL && *p != 0;
1382 memcpy (hexbuf, s + 8, 8);
1383 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
1384 seed_failed += p != NULL && *p != 0;
1385 memcpy (hexbuf, s + 16, 8);
1386 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
1387 seed_failed += p != NULL && *p != 0;
1388 memcpy (hexbuf, s + 24, 8);
1389 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
1390 seed_failed += p != NULL && *p != 0;
1391 if (!seed_failed)
1393 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
1394 return;
1398 g_error ("Unknown or invalid random seed: %s", rseed);
1402 * g_test_rand_int:
1404 * Get a reproducible random integer number.
1406 * The random numbers generated by the g_test_rand_*() family of functions
1407 * change with every new test program start, unless the --seed option is
1408 * given when starting test programs.
1410 * For individual test cases however, the random number generator is
1411 * reseeded, to avoid dependencies between tests and to make --seed
1412 * effective for all test cases.
1414 * Returns: a random number from the seeded random number generator.
1416 * Since: 2.16
1418 gint32
1419 g_test_rand_int (void)
1421 return g_rand_int (test_run_rand);
1425 * g_test_rand_int_range:
1426 * @begin: the minimum value returned by this function
1427 * @end: the smallest value not to be returned by this function
1429 * Get a reproducible random integer number out of a specified range,
1430 * see g_test_rand_int() for details on test case random numbers.
1432 * Returns: a number with @begin <= number < @end.
1434 * Since: 2.16
1436 gint32
1437 g_test_rand_int_range (gint32 begin,
1438 gint32 end)
1440 return g_rand_int_range (test_run_rand, begin, end);
1444 * g_test_rand_double:
1446 * Get a reproducible random floating point number,
1447 * see g_test_rand_int() for details on test case random numbers.
1449 * Returns: a random number from the seeded random number generator.
1451 * Since: 2.16
1453 double
1454 g_test_rand_double (void)
1456 return g_rand_double (test_run_rand);
1460 * g_test_rand_double_range:
1461 * @range_start: the minimum value returned by this function
1462 * @range_end: the minimum value not returned by this function
1464 * Get a reproducible random floating pointer number out of a specified range,
1465 * see g_test_rand_int() for details on test case random numbers.
1467 * Returns: a number with @range_start <= number < @range_end.
1469 * Since: 2.16
1471 double
1472 g_test_rand_double_range (double range_start,
1473 double range_end)
1475 return g_rand_double_range (test_run_rand, range_start, range_end);
1479 * g_test_timer_start:
1481 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1482 * to be done. Call this function again to restart the timer.
1484 * Since: 2.16
1486 void
1487 g_test_timer_start (void)
1489 if (!test_user_timer)
1490 test_user_timer = g_timer_new();
1491 test_user_stamp = 0;
1492 g_timer_start (test_user_timer);
1496 * g_test_timer_elapsed:
1498 * Get the time since the last start of the timer with g_test_timer_start().
1500 * Returns: the time since the last start of the timer, as a double
1502 * Since: 2.16
1504 double
1505 g_test_timer_elapsed (void)
1507 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1508 return test_user_stamp;
1512 * g_test_timer_last:
1514 * Report the last result of g_test_timer_elapsed().
1516 * Returns: the last result of g_test_timer_elapsed(), as a double
1518 * Since: 2.16
1520 double
1521 g_test_timer_last (void)
1523 return test_user_stamp;
1527 * g_test_minimized_result:
1528 * @minimized_quantity: the reported value
1529 * @format: the format string of the report message
1530 * @...: arguments to pass to the printf() function
1532 * Report the result of a performance or measurement test.
1533 * The test should generally strive to minimize the reported
1534 * quantities (smaller values are better than larger ones),
1535 * this and @minimized_quantity can determine sorting
1536 * order for test result reports.
1538 * Since: 2.16
1540 void
1541 g_test_minimized_result (double minimized_quantity,
1542 const char *format,
1543 ...)
1545 long double largs = minimized_quantity;
1546 gchar *buffer;
1547 va_list args;
1549 va_start (args, format);
1550 buffer = g_strdup_vprintf (format, args);
1551 va_end (args);
1553 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1554 g_free (buffer);
1558 * g_test_maximized_result:
1559 * @maximized_quantity: the reported value
1560 * @format: the format string of the report message
1561 * @...: arguments to pass to the printf() function
1563 * Report the result of a performance or measurement test.
1564 * The test should generally strive to maximize the reported
1565 * quantities (larger values are better than smaller ones),
1566 * this and @maximized_quantity can determine sorting
1567 * order for test result reports.
1569 * Since: 2.16
1571 void
1572 g_test_maximized_result (double maximized_quantity,
1573 const char *format,
1574 ...)
1576 long double largs = maximized_quantity;
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_MAX_RESULT, buffer, NULL, 1, &largs);
1585 g_free (buffer);
1589 * g_test_message:
1590 * @format: the format string
1591 * @...: printf-like arguments to @format
1593 * Add a message to the test report.
1595 * Since: 2.16
1597 void
1598 g_test_message (const char *format,
1599 ...)
1601 gchar *buffer;
1602 va_list args;
1604 va_start (args, format);
1605 buffer = g_strdup_vprintf (format, args);
1606 va_end (args);
1608 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1609 g_free (buffer);
1613 * g_test_bug_base:
1614 * @uri_pattern: the base pattern for bug URIs
1616 * Specify the base URI for bug reports.
1618 * The base URI is used to construct bug report messages for
1619 * g_test_message() when g_test_bug() is called.
1620 * Calling this function outside of a test case sets the
1621 * default base URI for all test cases. Calling it from within
1622 * a test case changes the base URI for the scope of the test
1623 * case only.
1624 * Bug URIs are constructed by appending a bug specific URI
1625 * portion to @uri_pattern, or by replacing the special string
1626 * '\%s' within @uri_pattern if that is present.
1628 * Since: 2.16
1630 void
1631 g_test_bug_base (const char *uri_pattern)
1633 g_free (test_uri_base);
1634 test_uri_base = g_strdup (uri_pattern);
1638 * g_test_bug:
1639 * @bug_uri_snippet: Bug specific bug tracker URI portion.
1641 * This function adds a message to test reports that
1642 * associates a bug URI with a test case.
1643 * Bug URIs are constructed from a base URI set with g_test_bug_base()
1644 * and @bug_uri_snippet.
1646 * Since: 2.16
1648 void
1649 g_test_bug (const char *bug_uri_snippet)
1651 char *c;
1653 g_return_if_fail (test_uri_base != NULL);
1654 g_return_if_fail (bug_uri_snippet != NULL);
1656 c = strstr (test_uri_base, "%s");
1657 if (c)
1659 char *b = g_strndup (test_uri_base, c - test_uri_base);
1660 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1661 g_free (b);
1662 g_test_message ("Bug Reference: %s", s);
1663 g_free (s);
1665 else
1666 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1670 * g_test_get_root:
1672 * Get the toplevel test suite for the test path API.
1674 * Returns: the toplevel #GTestSuite
1676 * Since: 2.16
1678 GTestSuite*
1679 g_test_get_root (void)
1681 if (!test_suite_root)
1683 test_suite_root = g_test_create_suite ("root");
1684 g_free (test_suite_root->name);
1685 test_suite_root->name = g_strdup ("");
1688 return test_suite_root;
1692 * g_test_run:
1694 * Runs all tests under the toplevel suite which can be retrieved
1695 * with g_test_get_root(). Similar to g_test_run_suite(), the test
1696 * cases to be run are filtered according to test path arguments
1697 * (`-p testpath` and `-s testpath`) as parsed by g_test_init().
1698 * g_test_run_suite() or g_test_run() may only be called once in a
1699 * program.
1701 * In general, the tests and sub-suites within each suite are run in
1702 * the order in which they are defined. However, note that prior to
1703 * GLib 2.36, there was a bug in the `g_test_add_*`
1704 * functions which caused them to create multiple suites with the same
1705 * name, meaning that if you created tests "/foo/simple",
1706 * "/bar/simple", and "/foo/using-bar" in that order, they would get
1707 * run in that order (since g_test_run() would run the first "/foo"
1708 * suite, then the "/bar" suite, then the second "/foo" suite). As of
1709 * 2.36, this bug is fixed, and adding the tests in that order would
1710 * result in a running order of "/foo/simple", "/foo/using-bar",
1711 * "/bar/simple". If this new ordering is sub-optimal (because it puts
1712 * more-complicated tests before simpler ones, making it harder to
1713 * figure out exactly what has failed), you can fix it by changing the
1714 * test paths to group tests by suite in a way that will result in the
1715 * desired running order. Eg, "/simple/foo", "/simple/bar",
1716 * "/complex/foo-using-bar".
1718 * However, you should never make the actual result of a test depend
1719 * on the order that tests are run in. If you need to ensure that some
1720 * particular code runs before or after a given test case, use
1721 * g_test_add(), which lets you specify setup and teardown functions.
1723 * If all tests are skipped, this function will return 0 if
1724 * producing TAP output, or 77 (treated as "skip test" by Automake) otherwise.
1726 * Returns: 0 on success, 1 on failure (assuming it returns at all),
1727 * 0 or 77 if all tests were skipped with g_test_skip()
1729 * Since: 2.16
1732 g_test_run (void)
1734 if (g_test_run_suite (g_test_get_root()) != 0)
1735 return 1;
1737 /* 77 is special to Automake's default driver, but not Automake's TAP driver
1738 * or Perl's prove(1) TAP driver. */
1739 if (test_tap_log)
1740 return 0;
1742 if (test_run_count > 0 && test_run_count == test_skipped_count)
1743 return 77;
1744 else
1745 return 0;
1749 * g_test_create_case:
1750 * @test_name: the name for the test case
1751 * @data_size: the size of the fixture data structure
1752 * @test_data: test data argument for the test functions
1753 * @data_setup: (scope async): the function to set up the fixture data
1754 * @data_test: (scope async): the actual test function
1755 * @data_teardown: (scope async): the function to teardown the fixture data
1757 * Create a new #GTestCase, named @test_name, this API is fairly
1758 * low level, calling g_test_add() or g_test_add_func() is preferable.
1759 * When this test is executed, a fixture structure of size @data_size
1760 * will be automatically allocated and filled with zeros. Then @data_setup is
1761 * called to initialize the fixture. After fixture setup, the actual test
1762 * function @data_test is called. Once the test run completes, the
1763 * fixture structure is torn down by calling @data_teardown and
1764 * after that the memory is automatically released by the test framework.
1766 * Splitting up a test run into fixture setup, test function and
1767 * fixture teardown is most useful if the same fixture is used for
1768 * multiple tests. In this cases, g_test_create_case() will be
1769 * called with the same fixture, but varying @test_name and
1770 * @data_test arguments.
1772 * Returns: a newly allocated #GTestCase.
1774 * Since: 2.16
1776 GTestCase*
1777 g_test_create_case (const char *test_name,
1778 gsize data_size,
1779 gconstpointer test_data,
1780 GTestFixtureFunc data_setup,
1781 GTestFixtureFunc data_test,
1782 GTestFixtureFunc data_teardown)
1784 GTestCase *tc;
1786 g_return_val_if_fail (test_name != NULL, NULL);
1787 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1788 g_return_val_if_fail (test_name[0] != 0, NULL);
1789 g_return_val_if_fail (data_test != NULL, NULL);
1791 tc = g_slice_new0 (GTestCase);
1792 tc->name = g_strdup (test_name);
1793 tc->test_data = (gpointer) test_data;
1794 tc->fixture_size = data_size;
1795 tc->fixture_setup = (void*) data_setup;
1796 tc->fixture_test = (void*) data_test;
1797 tc->fixture_teardown = (void*) data_teardown;
1799 return tc;
1802 static gint
1803 find_suite (gconstpointer l, gconstpointer s)
1805 const GTestSuite *suite = l;
1806 const gchar *str = s;
1808 return strcmp (suite->name, str);
1811 static gint
1812 find_case (gconstpointer l, gconstpointer s)
1814 const GTestCase *tc = l;
1815 const gchar *str = s;
1817 return strcmp (tc->name, str);
1821 * GTestFixtureFunc:
1822 * @fixture: (not nullable): the test fixture
1823 * @user_data: the data provided when registering the test
1825 * The type used for functions that operate on test fixtures. This is
1826 * used for the fixture setup and teardown functions as well as for the
1827 * testcases themselves.
1829 * @user_data is a pointer to the data that was given when registering
1830 * the test case.
1832 * @fixture will be a pointer to the area of memory allocated by the
1833 * test framework, of the size requested. If the requested size was
1834 * zero then @fixture will be equal to @user_data.
1836 * Since: 2.28
1838 void
1839 g_test_add_vtable (const char *testpath,
1840 gsize data_size,
1841 gconstpointer test_data,
1842 GTestFixtureFunc data_setup,
1843 GTestFixtureFunc fixture_test_func,
1844 GTestFixtureFunc data_teardown)
1846 gchar **segments;
1847 guint ui;
1848 GTestSuite *suite;
1850 g_return_if_fail (testpath != NULL);
1851 g_return_if_fail (g_path_is_absolute (testpath));
1852 g_return_if_fail (fixture_test_func != NULL);
1854 suite = g_test_get_root();
1855 segments = g_strsplit (testpath, "/", -1);
1856 for (ui = 0; segments[ui] != NULL; ui++)
1858 const char *seg = segments[ui];
1859 gboolean islast = segments[ui + 1] == NULL;
1860 if (islast && !seg[0])
1861 g_error ("invalid test case path: %s", testpath);
1862 else if (!seg[0])
1863 continue; /* initial or duplicate slash */
1864 else if (!islast)
1866 GSList *l;
1867 GTestSuite *csuite;
1868 l = g_slist_find_custom (suite->suites, seg, find_suite);
1869 if (l)
1871 csuite = l->data;
1873 else
1875 csuite = g_test_create_suite (seg);
1876 g_test_suite_add_suite (suite, csuite);
1878 suite = csuite;
1880 else /* islast */
1882 GTestCase *tc;
1884 if (g_slist_find_custom (suite->cases, seg, find_case))
1885 g_error ("duplicate test case path: %s", testpath);
1887 tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1888 g_test_suite_add (suite, tc);
1891 g_strfreev (segments);
1895 * g_test_fail:
1897 * Indicates that a test failed. This function can be called
1898 * multiple times from the same test. You can use this function
1899 * if your test failed in a recoverable way.
1901 * Do not use this function if the failure of a test could cause
1902 * other tests to malfunction.
1904 * Calling this function will not stop the test from running, you
1905 * need to return from the test function yourself. So you can
1906 * produce additional diagnostic messages or even continue running
1907 * the test.
1909 * If not called from inside a test, this function does nothing.
1911 * Since: 2.30
1913 void
1914 g_test_fail (void)
1916 test_run_success = G_TEST_RUN_FAILURE;
1920 * g_test_incomplete:
1921 * @msg: (nullable): explanation
1923 * Indicates that a test failed because of some incomplete
1924 * functionality. This function can be called multiple times
1925 * from the same test.
1927 * Calling this function will not stop the test from running, you
1928 * need to return from the test function yourself. So you can
1929 * produce additional diagnostic messages or even continue running
1930 * the test.
1932 * If not called from inside a test, this function does nothing.
1934 * Since: 2.38
1936 void
1937 g_test_incomplete (const gchar *msg)
1939 test_run_success = G_TEST_RUN_INCOMPLETE;
1940 g_free (test_run_msg);
1941 test_run_msg = g_strdup (msg);
1945 * g_test_skip:
1946 * @msg: (nullable): explanation
1948 * Indicates that a test was skipped.
1950 * Calling this function will not stop the test from running, you
1951 * need to return from the test function yourself. So you can
1952 * produce additional diagnostic messages or even continue running
1953 * the test.
1955 * If not called from inside a test, this function does nothing.
1957 * Since: 2.38
1959 void
1960 g_test_skip (const gchar *msg)
1962 test_run_success = G_TEST_RUN_SKIPPED;
1963 g_free (test_run_msg);
1964 test_run_msg = g_strdup (msg);
1968 * g_test_failed:
1970 * Returns whether a test has already failed. This will
1971 * be the case when g_test_fail(), g_test_incomplete()
1972 * or g_test_skip() have been called, but also if an
1973 * assertion has failed.
1975 * This can be useful to return early from a test if
1976 * continuing after a failed assertion might be harmful.
1978 * The return value of this function is only meaningful
1979 * if it is called from inside a test function.
1981 * Returns: %TRUE if the test has failed
1983 * Since: 2.38
1985 gboolean
1986 g_test_failed (void)
1988 return test_run_success != G_TEST_RUN_SUCCESS;
1992 * g_test_set_nonfatal_assertions:
1994 * Changes the behaviour of g_assert_cmpstr(), g_assert_cmpint(),
1995 * g_assert_cmpuint(), g_assert_cmphex(), g_assert_cmpfloat(),
1996 * g_assert_true(), g_assert_false(), g_assert_null(), g_assert_no_error(),
1997 * g_assert_error(), g_test_assert_expected_messages() and the various
1998 * g_test_trap_assert_*() macros to not abort to program, but instead
1999 * call g_test_fail() and continue. (This also changes the behavior of
2000 * g_test_fail() so that it will not cause the test program to abort
2001 * after completing the failed test.)
2003 * Note that the g_assert_not_reached() and g_assert() are not
2004 * affected by this.
2006 * This function can only be called after g_test_init().
2008 * Since: 2.38
2010 void
2011 g_test_set_nonfatal_assertions (void)
2013 if (!g_test_config_vars->test_initialized)
2014 g_error ("g_test_set_nonfatal_assertions called without g_test_init");
2015 test_nonfatal_assertions = TRUE;
2016 test_mode_fatal = FALSE;
2020 * GTestFunc:
2022 * The type used for test case functions.
2024 * Since: 2.28
2028 * g_test_add_func:
2029 * @testpath: /-separated test case path name for the test.
2030 * @test_func: (scope async): The test function to invoke for this test.
2032 * Create a new test case, similar to g_test_create_case(). However
2033 * the test is assumed to use no fixture, and test suites are automatically
2034 * created on the fly and added to the root fixture, based on the
2035 * slash-separated portions of @testpath.
2037 * If @testpath includes the component "subprocess" anywhere in it,
2038 * the test will be skipped by default, and only run if explicitly
2039 * required via the `-p` command-line option or g_test_trap_subprocess().
2041 * Since: 2.16
2043 void
2044 g_test_add_func (const char *testpath,
2045 GTestFunc test_func)
2047 g_return_if_fail (testpath != NULL);
2048 g_return_if_fail (testpath[0] == '/');
2049 g_return_if_fail (test_func != NULL);
2050 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
2054 * GTestDataFunc:
2055 * @user_data: the data provided when registering the test
2057 * The type used for test case functions that take an extra pointer
2058 * argument.
2060 * Since: 2.28
2064 * g_test_add_data_func:
2065 * @testpath: /-separated test case path name for the test.
2066 * @test_data: Test data argument for the test function.
2067 * @test_func: (scope async): The test function to invoke for this test.
2069 * Create a new test case, similar to g_test_create_case(). However
2070 * the test is assumed to use no fixture, and test suites are automatically
2071 * created on the fly and added to the root fixture, based on the
2072 * slash-separated portions of @testpath. The @test_data argument
2073 * will be passed as first argument to @test_func.
2075 * If @testpath includes the component "subprocess" anywhere in it,
2076 * the test will be skipped by default, and only run if explicitly
2077 * required via the `-p` command-line option or g_test_trap_subprocess().
2079 * Since: 2.16
2081 void
2082 g_test_add_data_func (const char *testpath,
2083 gconstpointer test_data,
2084 GTestDataFunc test_func)
2086 g_return_if_fail (testpath != NULL);
2087 g_return_if_fail (testpath[0] == '/');
2088 g_return_if_fail (test_func != NULL);
2090 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
2094 * g_test_add_data_func_full:
2095 * @testpath: /-separated test case path name for the test.
2096 * @test_data: Test data argument for the test function.
2097 * @test_func: The test function to invoke for this test.
2098 * @data_free_func: #GDestroyNotify for @test_data.
2100 * Create a new test case, as with g_test_add_data_func(), but freeing
2101 * @test_data after the test run is complete.
2103 * Since: 2.34
2105 void
2106 g_test_add_data_func_full (const char *testpath,
2107 gpointer test_data,
2108 GTestDataFunc test_func,
2109 GDestroyNotify data_free_func)
2111 g_return_if_fail (testpath != NULL);
2112 g_return_if_fail (testpath[0] == '/');
2113 g_return_if_fail (test_func != NULL);
2115 g_test_add_vtable (testpath, 0, test_data, NULL,
2116 (GTestFixtureFunc) test_func,
2117 (GTestFixtureFunc) data_free_func);
2120 static gboolean
2121 g_test_suite_case_exists (GTestSuite *suite,
2122 const char *test_path)
2124 GSList *iter;
2125 char *slash;
2126 GTestCase *tc;
2128 test_path++;
2129 slash = strchr (test_path, '/');
2131 if (slash)
2133 for (iter = suite->suites; iter; iter = iter->next)
2135 GTestSuite *child_suite = iter->data;
2137 if (!strncmp (child_suite->name, test_path, slash - test_path))
2138 if (g_test_suite_case_exists (child_suite, slash))
2139 return TRUE;
2142 else
2144 for (iter = suite->cases; iter; iter = iter->next)
2146 tc = iter->data;
2147 if (!strcmp (tc->name, test_path))
2148 return TRUE;
2152 return FALSE;
2156 * g_test_create_suite:
2157 * @suite_name: a name for the suite
2159 * Create a new test suite with the name @suite_name.
2161 * Returns: A newly allocated #GTestSuite instance.
2163 * Since: 2.16
2165 GTestSuite*
2166 g_test_create_suite (const char *suite_name)
2168 GTestSuite *ts;
2169 g_return_val_if_fail (suite_name != NULL, NULL);
2170 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
2171 g_return_val_if_fail (suite_name[0] != 0, NULL);
2172 ts = g_slice_new0 (GTestSuite);
2173 ts->name = g_strdup (suite_name);
2174 return ts;
2178 * g_test_suite_add:
2179 * @suite: a #GTestSuite
2180 * @test_case: a #GTestCase
2182 * Adds @test_case to @suite.
2184 * Since: 2.16
2186 void
2187 g_test_suite_add (GTestSuite *suite,
2188 GTestCase *test_case)
2190 g_return_if_fail (suite != NULL);
2191 g_return_if_fail (test_case != NULL);
2193 suite->cases = g_slist_append (suite->cases, test_case);
2197 * g_test_suite_add_suite:
2198 * @suite: a #GTestSuite
2199 * @nestedsuite: another #GTestSuite
2201 * Adds @nestedsuite to @suite.
2203 * Since: 2.16
2205 void
2206 g_test_suite_add_suite (GTestSuite *suite,
2207 GTestSuite *nestedsuite)
2209 g_return_if_fail (suite != NULL);
2210 g_return_if_fail (nestedsuite != NULL);
2212 suite->suites = g_slist_append (suite->suites, nestedsuite);
2216 * g_test_queue_free:
2217 * @gfree_pointer: the pointer to be stored.
2219 * Enqueue a pointer to be released with g_free() during the next
2220 * teardown phase. This is equivalent to calling g_test_queue_destroy()
2221 * with a destroy callback of g_free().
2223 * Since: 2.16
2225 void
2226 g_test_queue_free (gpointer gfree_pointer)
2228 if (gfree_pointer)
2229 g_test_queue_destroy (g_free, gfree_pointer);
2233 * g_test_queue_destroy:
2234 * @destroy_func: Destroy callback for teardown phase.
2235 * @destroy_data: Destroy callback data.
2237 * This function enqueus a callback @destroy_func to be executed
2238 * during the next test case teardown phase. This is most useful
2239 * to auto destruct allocated test resources at the end of a test run.
2240 * Resources are released in reverse queue order, that means enqueueing
2241 * callback A before callback B will cause B() to be called before
2242 * A() during teardown.
2244 * Since: 2.16
2246 void
2247 g_test_queue_destroy (GDestroyNotify destroy_func,
2248 gpointer destroy_data)
2250 DestroyEntry *dentry;
2252 g_return_if_fail (destroy_func != NULL);
2254 dentry = g_slice_new0 (DestroyEntry);
2255 dentry->destroy_func = destroy_func;
2256 dentry->destroy_data = destroy_data;
2257 dentry->next = test_destroy_queue;
2258 test_destroy_queue = dentry;
2261 static gboolean
2262 test_case_run (GTestCase *tc)
2264 gchar *old_base = g_strdup (test_uri_base);
2265 GSList **old_free_list, *filename_free_list = NULL;
2266 gboolean success = G_TEST_RUN_SUCCESS;
2268 old_free_list = test_filename_free_list;
2269 test_filename_free_list = &filename_free_list;
2271 if (++test_run_count <= test_startup_skip_count)
2272 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
2273 else if (test_run_list)
2275 g_print ("%s\n", test_run_name);
2276 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
2278 else
2280 GTimer *test_run_timer = g_timer_new();
2281 long double largs[3];
2282 void *fixture;
2283 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
2284 test_run_forks = 0;
2285 test_run_success = G_TEST_RUN_SUCCESS;
2286 g_clear_pointer (&test_run_msg, g_free);
2287 g_test_log_set_fatal_handler (NULL, NULL);
2288 if (test_paths_skipped && g_slist_find_custom (test_paths_skipped, test_run_name, (GCompareFunc)g_strcmp0))
2289 g_test_skip ("by request (-s option)");
2290 else
2292 g_timer_start (test_run_timer);
2293 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
2294 test_run_seed (test_run_seedstr);
2295 if (tc->fixture_setup)
2296 tc->fixture_setup (fixture, tc->test_data);
2297 tc->fixture_test (fixture, tc->test_data);
2298 test_trap_clear();
2299 while (test_destroy_queue)
2301 DestroyEntry *dentry = test_destroy_queue;
2302 test_destroy_queue = dentry->next;
2303 dentry->destroy_func (dentry->destroy_data);
2304 g_slice_free (DestroyEntry, dentry);
2306 if (tc->fixture_teardown)
2307 tc->fixture_teardown (fixture, tc->test_data);
2308 if (tc->fixture_size)
2309 g_free (fixture);
2310 g_timer_stop (test_run_timer);
2312 success = test_run_success;
2313 test_run_success = G_TEST_RUN_FAILURE;
2314 largs[0] = success; /* OK */
2315 largs[1] = test_run_forks;
2316 largs[2] = g_timer_elapsed (test_run_timer, NULL);
2317 g_test_log (G_TEST_LOG_STOP_CASE, test_run_name, test_run_msg, G_N_ELEMENTS (largs), largs);
2318 g_clear_pointer (&test_run_msg, g_free);
2319 g_timer_destroy (test_run_timer);
2322 g_slist_free_full (filename_free_list, g_free);
2323 test_filename_free_list = old_free_list;
2324 g_free (test_uri_base);
2325 test_uri_base = old_base;
2327 return (success == G_TEST_RUN_SUCCESS ||
2328 success == G_TEST_RUN_SKIPPED);
2331 static gboolean
2332 path_has_prefix (const char *path,
2333 const char *prefix)
2335 int prefix_len = strlen (prefix);
2337 return (strncmp (path, prefix, prefix_len) == 0 &&
2338 (path[prefix_len] == '\0' ||
2339 path[prefix_len] == '/'));
2342 static gboolean
2343 test_should_run (const char *test_path,
2344 const char *cmp_path)
2346 if (strstr (test_run_name, "/subprocess"))
2348 if (g_strcmp0 (test_path, cmp_path) == 0)
2349 return TRUE;
2351 if (g_test_verbose ())
2352 g_print ("GTest: skipping: %s\n", test_run_name);
2353 return FALSE;
2356 return !cmp_path || path_has_prefix (test_path, cmp_path);
2359 /* Recurse through @suite, running tests matching @path (or all tests
2360 * if @path is %NULL).
2362 static int
2363 g_test_run_suite_internal (GTestSuite *suite,
2364 const char *path)
2366 guint n_bad = 0;
2367 gchar *old_name = test_run_name;
2368 GSList *iter;
2370 g_return_val_if_fail (suite != NULL, -1);
2372 g_test_log (G_TEST_LOG_START_SUITE, suite->name, NULL, 0, NULL);
2374 for (iter = suite->cases; iter; iter = iter->next)
2376 GTestCase *tc = iter->data;
2378 test_run_name = g_build_path ("/", old_name, tc->name, NULL);
2379 if (test_should_run (test_run_name, path))
2381 if (!test_case_run (tc))
2382 n_bad++;
2384 g_free (test_run_name);
2387 for (iter = suite->suites; iter; iter = iter->next)
2389 GTestSuite *ts = iter->data;
2391 test_run_name = g_build_path ("/", old_name, ts->name, NULL);
2392 if (!path || path_has_prefix (path, test_run_name))
2393 n_bad += g_test_run_suite_internal (ts, path);
2394 g_free (test_run_name);
2397 test_run_name = old_name;
2399 g_test_log (G_TEST_LOG_STOP_SUITE, suite->name, NULL, 0, NULL);
2401 return n_bad;
2404 static int
2405 g_test_suite_count (GTestSuite *suite)
2407 int n = 0;
2408 GSList *iter;
2410 g_return_val_if_fail (suite != NULL, -1);
2412 for (iter = suite->cases; iter; iter = iter->next)
2414 GTestCase *tc = iter->data;
2416 if (strcmp (tc->name, "subprocess") != 0)
2417 n++;
2420 for (iter = suite->suites; iter; iter = iter->next)
2422 GTestSuite *ts = iter->data;
2424 if (strcmp (ts->name, "subprocess") != 0)
2425 n += g_test_suite_count (ts);
2428 return n;
2432 * g_test_run_suite:
2433 * @suite: a #GTestSuite
2435 * Execute the tests within @suite and all nested #GTestSuites.
2436 * The test suites to be executed are filtered according to
2437 * test path arguments (`-p testpath` and `-s testpath`) as parsed by
2438 * g_test_init(). See the g_test_run() documentation for more
2439 * information on the order that tests are run in.
2441 * g_test_run_suite() or g_test_run() may only be called once
2442 * in a program.
2444 * Returns: 0 on success
2446 * Since: 2.16
2449 g_test_run_suite (GTestSuite *suite)
2451 int n_bad = 0;
2453 g_return_val_if_fail (g_test_run_once == TRUE, -1);
2455 g_test_run_once = FALSE;
2456 test_count = g_test_suite_count (suite);
2458 test_run_name = g_strdup_printf ("/%s", suite->name);
2460 if (test_paths)
2462 GSList *iter;
2464 for (iter = test_paths; iter; iter = iter->next)
2465 n_bad += g_test_run_suite_internal (suite, iter->data);
2467 else
2468 n_bad = g_test_run_suite_internal (suite, NULL);
2470 g_free (test_run_name);
2471 test_run_name = NULL;
2473 return n_bad;
2476 static void
2477 gtest_default_log_handler (const gchar *log_domain,
2478 GLogLevelFlags log_level,
2479 const gchar *message,
2480 gpointer unused_data)
2482 const gchar *strv[16];
2483 gboolean fatal = FALSE;
2484 gchar *msg;
2485 guint i = 0;
2487 if (log_domain)
2489 strv[i++] = log_domain;
2490 strv[i++] = "-";
2492 if (log_level & G_LOG_FLAG_FATAL)
2494 strv[i++] = "FATAL-";
2495 fatal = TRUE;
2497 if (log_level & G_LOG_FLAG_RECURSION)
2498 strv[i++] = "RECURSIVE-";
2499 if (log_level & G_LOG_LEVEL_ERROR)
2500 strv[i++] = "ERROR";
2501 if (log_level & G_LOG_LEVEL_CRITICAL)
2502 strv[i++] = "CRITICAL";
2503 if (log_level & G_LOG_LEVEL_WARNING)
2504 strv[i++] = "WARNING";
2505 if (log_level & G_LOG_LEVEL_MESSAGE)
2506 strv[i++] = "MESSAGE";
2507 if (log_level & G_LOG_LEVEL_INFO)
2508 strv[i++] = "INFO";
2509 if (log_level & G_LOG_LEVEL_DEBUG)
2510 strv[i++] = "DEBUG";
2511 strv[i++] = ": ";
2512 strv[i++] = message;
2513 strv[i++] = NULL;
2515 msg = g_strjoinv ("", (gchar**) strv);
2516 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
2517 g_log_default_handler (log_domain, log_level, message, unused_data);
2519 g_free (msg);
2522 void
2523 g_assertion_message (const char *domain,
2524 const char *file,
2525 int line,
2526 const char *func,
2527 const char *message)
2529 char lstr[32];
2530 char *s;
2532 if (!message)
2533 message = "code should not be reached";
2534 g_snprintf (lstr, 32, "%d", line);
2535 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
2536 "ERROR:", file, ":", lstr, ":",
2537 func, func[0] ? ":" : "",
2538 " ", message, NULL);
2539 g_printerr ("**\n%s\n", s);
2541 /* Don't print a fatal error indication if assertions are non-fatal, or
2542 * if we are a child process that might be sharing the parent's stdout. */
2543 if (test_nonfatal_assertions || test_in_subprocess || test_in_forked_child)
2544 g_test_log (G_TEST_LOG_MESSAGE, s, NULL, 0, NULL);
2545 else
2546 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
2548 if (test_nonfatal_assertions)
2550 g_free (s);
2551 g_test_fail ();
2552 return;
2555 /* store assertion message in global variable, so that it can be found in a
2556 * core dump */
2557 if (__glib_assert_msg != NULL)
2558 /* free the old one */
2559 free (__glib_assert_msg);
2560 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
2561 strcpy (__glib_assert_msg, s);
2563 g_free (s);
2565 if (test_in_subprocess)
2567 /* If this is a test case subprocess then it probably hit this
2568 * assertion on purpose, so just exit() rather than abort()ing,
2569 * to avoid triggering any system crash-reporting daemon.
2571 _exit (1);
2573 else
2574 g_abort ();
2578 * g_assertion_message_expr: (skip)
2579 * @domain: (nullable):
2580 * @file:
2581 * @line:
2582 * @func:
2583 * @expr: (nullable):
2585 void
2586 g_assertion_message_expr (const char *domain,
2587 const char *file,
2588 int line,
2589 const char *func,
2590 const char *expr)
2592 char *s;
2593 if (!expr)
2594 s = g_strdup ("code should not be reached");
2595 else
2596 s = g_strconcat ("assertion failed: (", expr, ")", NULL);
2597 g_assertion_message (domain, file, line, func, s);
2598 g_free (s);
2600 /* Normally g_assertion_message() won't return, but we need this for
2601 * when test_nonfatal_assertions is set, since
2602 * g_assertion_message_expr() is used for always-fatal assertions.
2604 if (test_in_subprocess)
2605 _exit (1);
2606 else
2607 g_abort ();
2610 void
2611 g_assertion_message_cmpnum (const char *domain,
2612 const char *file,
2613 int line,
2614 const char *func,
2615 const char *expr,
2616 long double arg1,
2617 const char *cmp,
2618 long double arg2,
2619 char numtype)
2621 char *s = NULL;
2623 switch (numtype)
2625 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;
2626 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;
2627 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr, (double) arg1, cmp, (double) arg2); break;
2628 /* ideally use: floats=%.7g double=%.17g */
2630 g_assertion_message (domain, file, line, func, s);
2631 g_free (s);
2634 void
2635 g_assertion_message_cmpstr (const char *domain,
2636 const char *file,
2637 int line,
2638 const char *func,
2639 const char *expr,
2640 const char *arg1,
2641 const char *cmp,
2642 const char *arg2)
2644 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
2645 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
2646 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
2647 g_free (t1);
2648 g_free (t2);
2649 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
2650 g_free (a1);
2651 g_free (a2);
2652 g_assertion_message (domain, file, line, func, s);
2653 g_free (s);
2656 void
2657 g_assertion_message_error (const char *domain,
2658 const char *file,
2659 int line,
2660 const char *func,
2661 const char *expr,
2662 const GError *error,
2663 GQuark error_domain,
2664 int error_code)
2666 GString *gstring;
2668 /* This is used by both g_assert_error() and g_assert_no_error(), so there
2669 * are three cases: expected an error but got the wrong error, expected
2670 * an error but got no error, and expected no error but got an error.
2673 gstring = g_string_new ("assertion failed ");
2674 if (error_domain)
2675 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
2676 g_quark_to_string (error_domain), error_code);
2677 else
2678 g_string_append_printf (gstring, "(%s == NULL): ", expr);
2680 if (error)
2681 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
2682 g_quark_to_string (error->domain), error->code);
2683 else
2684 g_string_append_printf (gstring, "%s is NULL", expr);
2686 g_assertion_message (domain, file, line, func, gstring->str);
2687 g_string_free (gstring, TRUE);
2691 * g_strcmp0:
2692 * @str1: (nullable): a C string or %NULL
2693 * @str2: (nullable): another C string or %NULL
2695 * Compares @str1 and @str2 like strcmp(). Handles %NULL
2696 * gracefully by sorting it before non-%NULL strings.
2697 * Comparing two %NULL pointers returns 0.
2699 * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
2701 * Since: 2.16
2704 g_strcmp0 (const char *str1,
2705 const char *str2)
2707 if (!str1)
2708 return -(str1 != str2);
2709 if (!str2)
2710 return str1 != str2;
2711 return strcmp (str1, str2);
2714 static void
2715 test_trap_clear (void)
2717 test_trap_last_status = 0;
2718 test_trap_last_pid = 0;
2719 g_clear_pointer (&test_trap_last_subprocess, g_free);
2720 g_clear_pointer (&test_trap_last_stdout, g_free);
2721 g_clear_pointer (&test_trap_last_stderr, g_free);
2724 #ifdef G_OS_UNIX
2726 static int
2727 sane_dup2 (int fd1,
2728 int fd2)
2730 int ret;
2732 ret = dup2 (fd1, fd2);
2733 while (ret < 0 && errno == EINTR);
2734 return ret;
2737 #endif
2739 typedef struct {
2740 GPid pid;
2741 GMainLoop *loop;
2742 int child_status; /* unmodified platform-specific status */
2744 GIOChannel *stdout_io;
2745 gboolean echo_stdout;
2746 GString *stdout_str;
2748 GIOChannel *stderr_io;
2749 gboolean echo_stderr;
2750 GString *stderr_str;
2751 } WaitForChildData;
2753 static void
2754 check_complete (WaitForChildData *data)
2756 if (data->child_status != -1 && data->stdout_io == NULL && data->stderr_io == NULL)
2757 g_main_loop_quit (data->loop);
2760 static void
2761 child_exited (GPid pid,
2762 gint status,
2763 gpointer user_data)
2765 WaitForChildData *data = user_data;
2767 g_assert (status != -1);
2768 data->child_status = status;
2770 check_complete (data);
2773 static gboolean
2774 child_timeout (gpointer user_data)
2776 WaitForChildData *data = user_data;
2778 #ifdef G_OS_WIN32
2779 TerminateProcess (data->pid, G_TEST_STATUS_TIMED_OUT);
2780 #else
2781 kill (data->pid, SIGALRM);
2782 #endif
2784 return FALSE;
2787 static gboolean
2788 child_read (GIOChannel *io, GIOCondition cond, gpointer user_data)
2790 WaitForChildData *data = user_data;
2791 GIOStatus status;
2792 gsize nread, nwrote, total;
2793 gchar buf[4096];
2794 FILE *echo_file = NULL;
2796 status = g_io_channel_read_chars (io, buf, sizeof (buf), &nread, NULL);
2797 if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF)
2799 // FIXME data->error = (status == G_IO_STATUS_ERROR);
2800 if (io == data->stdout_io)
2801 g_clear_pointer (&data->stdout_io, g_io_channel_unref);
2802 else
2803 g_clear_pointer (&data->stderr_io, g_io_channel_unref);
2805 check_complete (data);
2806 return FALSE;
2808 else if (status == G_IO_STATUS_AGAIN)
2809 return TRUE;
2811 if (io == data->stdout_io)
2813 g_string_append_len (data->stdout_str, buf, nread);
2814 if (data->echo_stdout)
2815 echo_file = stdout;
2817 else
2819 g_string_append_len (data->stderr_str, buf, nread);
2820 if (data->echo_stderr)
2821 echo_file = stderr;
2824 if (echo_file)
2826 for (total = 0; total < nread; total += nwrote)
2828 int errsv;
2830 nwrote = fwrite (buf + total, 1, nread - total, echo_file);
2831 errsv = errno;
2832 if (nwrote == 0)
2833 g_error ("write failed: %s", g_strerror (errsv));
2837 return TRUE;
2840 static void
2841 wait_for_child (GPid pid,
2842 int stdout_fd, gboolean echo_stdout,
2843 int stderr_fd, gboolean echo_stderr,
2844 guint64 timeout)
2846 WaitForChildData data;
2847 GMainContext *context;
2848 GSource *source;
2850 data.pid = pid;
2851 data.child_status = -1;
2853 context = g_main_context_new ();
2854 data.loop = g_main_loop_new (context, FALSE);
2856 source = g_child_watch_source_new (pid);
2857 g_source_set_callback (source, (GSourceFunc) child_exited, &data, NULL);
2858 g_source_attach (source, context);
2859 g_source_unref (source);
2861 data.echo_stdout = echo_stdout;
2862 data.stdout_str = g_string_new (NULL);
2863 data.stdout_io = g_io_channel_unix_new (stdout_fd);
2864 g_io_channel_set_close_on_unref (data.stdout_io, TRUE);
2865 g_io_channel_set_encoding (data.stdout_io, NULL, NULL);
2866 g_io_channel_set_buffered (data.stdout_io, FALSE);
2867 source = g_io_create_watch (data.stdout_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2868 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2869 g_source_attach (source, context);
2870 g_source_unref (source);
2872 data.echo_stderr = echo_stderr;
2873 data.stderr_str = g_string_new (NULL);
2874 data.stderr_io = g_io_channel_unix_new (stderr_fd);
2875 g_io_channel_set_close_on_unref (data.stderr_io, TRUE);
2876 g_io_channel_set_encoding (data.stderr_io, NULL, NULL);
2877 g_io_channel_set_buffered (data.stderr_io, FALSE);
2878 source = g_io_create_watch (data.stderr_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2879 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2880 g_source_attach (source, context);
2881 g_source_unref (source);
2883 if (timeout)
2885 source = g_timeout_source_new (0);
2886 g_source_set_ready_time (source, g_get_monotonic_time () + timeout);
2887 g_source_set_callback (source, (GSourceFunc) child_timeout, &data, NULL);
2888 g_source_attach (source, context);
2889 g_source_unref (source);
2892 g_main_loop_run (data.loop);
2893 g_main_loop_unref (data.loop);
2894 g_main_context_unref (context);
2896 test_trap_last_pid = pid;
2897 test_trap_last_status = data.child_status;
2898 test_trap_last_stdout = g_string_free (data.stdout_str, FALSE);
2899 test_trap_last_stderr = g_string_free (data.stderr_str, FALSE);
2901 g_clear_pointer (&data.stdout_io, g_io_channel_unref);
2902 g_clear_pointer (&data.stderr_io, g_io_channel_unref);
2906 * g_test_trap_fork:
2907 * @usec_timeout: Timeout for the forked test in micro seconds.
2908 * @test_trap_flags: Flags to modify forking behaviour.
2910 * Fork the current test program to execute a test case that might
2911 * not return or that might abort.
2913 * If @usec_timeout is non-0, the forked test case is aborted and
2914 * considered failing if its run time exceeds it.
2916 * The forking behavior can be configured with the #GTestTrapFlags flags.
2918 * In the following example, the test code forks, the forked child
2919 * process produces some sample output and exits successfully.
2920 * The forking parent process then asserts successful child program
2921 * termination and validates child program outputs.
2923 * |[<!-- language="C" -->
2924 * static void
2925 * test_fork_patterns (void)
2927 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2929 * g_print ("some stdout text: somagic17\n");
2930 * g_printerr ("some stderr text: semagic43\n");
2931 * exit (0); // successful test run
2933 * g_test_trap_assert_passed ();
2934 * g_test_trap_assert_stdout ("*somagic17*");
2935 * g_test_trap_assert_stderr ("*semagic43*");
2937 * ]|
2939 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2941 * Since: 2.16
2943 * Deprecated: This function is implemented only on Unix platforms,
2944 * and is not always reliable due to problems inherent in
2945 * fork-without-exec. Use g_test_trap_subprocess() instead.
2947 gboolean
2948 g_test_trap_fork (guint64 usec_timeout,
2949 GTestTrapFlags test_trap_flags)
2951 #ifdef G_OS_UNIX
2952 int stdout_pipe[2] = { -1, -1 };
2953 int stderr_pipe[2] = { -1, -1 };
2954 int errsv;
2956 test_trap_clear();
2957 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0)
2959 errsv = errno;
2960 g_error ("failed to create pipes to fork test program: %s", g_strerror (errsv));
2962 test_trap_last_pid = fork ();
2963 errsv = errno;
2964 if (test_trap_last_pid < 0)
2965 g_error ("failed to fork test program: %s", g_strerror (errsv));
2966 if (test_trap_last_pid == 0) /* child */
2968 int fd0 = -1;
2969 test_in_forked_child = TRUE;
2970 close (stdout_pipe[0]);
2971 close (stderr_pipe[0]);
2972 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2974 fd0 = g_open ("/dev/null", O_RDONLY, 0);
2975 if (fd0 < 0)
2976 g_error ("failed to open /dev/null for stdin redirection");
2978 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2980 errsv = errno;
2981 g_error ("failed to dup2() in forked test program: %s", g_strerror (errsv));
2983 if (fd0 >= 3)
2984 close (fd0);
2985 if (stdout_pipe[1] >= 3)
2986 close (stdout_pipe[1]);
2987 if (stderr_pipe[1] >= 3)
2988 close (stderr_pipe[1]);
2989 return TRUE;
2991 else /* parent */
2993 test_run_forks++;
2994 close (stdout_pipe[1]);
2995 close (stderr_pipe[1]);
2997 wait_for_child (test_trap_last_pid,
2998 stdout_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT),
2999 stderr_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR),
3000 usec_timeout);
3001 return FALSE;
3003 #else
3004 g_message ("Not implemented: g_test_trap_fork");
3006 return FALSE;
3007 #endif
3011 * g_test_trap_subprocess:
3012 * @test_path: (nullable): Test to run in a subprocess
3013 * @usec_timeout: Timeout for the subprocess test in micro seconds.
3014 * @test_flags: Flags to modify subprocess behaviour.
3016 * Respawns the test program to run only @test_path in a subprocess.
3017 * This can be used for a test case that might not return, or that
3018 * might abort.
3020 * If @test_path is %NULL then the same test is re-run in a subprocess.
3021 * You can use g_test_subprocess() to determine whether the test is in
3022 * a subprocess or not.
3024 * @test_path can also be the name of the parent test, followed by
3025 * "`/subprocess/`" and then a name for the specific subtest (or just
3026 * ending with "`/subprocess`" if the test only has one child test);
3027 * tests with names of this form will automatically be skipped in the
3028 * parent process.
3030 * If @usec_timeout is non-0, the test subprocess is aborted and
3031 * considered failing if its run time exceeds it.
3033 * The subprocess behavior can be configured with the
3034 * #GTestSubprocessFlags flags.
3036 * You can use methods such as g_test_trap_assert_passed(),
3037 * g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to
3038 * check the results of the subprocess. (But note that
3039 * g_test_trap_assert_stdout() and g_test_trap_assert_stderr()
3040 * cannot be used if @test_flags specifies that the child should
3041 * inherit the parent stdout/stderr.)
3043 * If your `main ()` needs to behave differently in
3044 * the subprocess, you can call g_test_subprocess() (after calling
3045 * g_test_init()) to see whether you are in a subprocess.
3047 * The following example tests that calling
3048 * `my_object_new(1000000)` will abort with an error
3049 * message.
3051 * |[<!-- language="C" -->
3052 * static void
3053 * test_create_large_object (void)
3055 * if (g_test_subprocess ())
3057 * my_object_new (1000000);
3058 * return;
3061 * // Reruns this same test in a subprocess
3062 * g_test_trap_subprocess (NULL, 0, 0);
3063 * g_test_trap_assert_failed ();
3064 * g_test_trap_assert_stderr ("*ERROR*too large*");
3067 * int
3068 * main (int argc, char **argv)
3070 * g_test_init (&argc, &argv, NULL);
3072 * g_test_add_func ("/myobject/create_large_object",
3073 * test_create_large_object);
3074 * return g_test_run ();
3076 * ]|
3078 * Since: 2.38
3080 void
3081 g_test_trap_subprocess (const char *test_path,
3082 guint64 usec_timeout,
3083 GTestSubprocessFlags test_flags)
3085 GError *error = NULL;
3086 GPtrArray *argv;
3087 GSpawnFlags flags;
3088 int stdout_fd, stderr_fd;
3089 GPid pid;
3091 /* Sanity check that they used GTestSubprocessFlags, not GTestTrapFlags */
3092 g_assert ((test_flags & (G_TEST_TRAP_INHERIT_STDIN | G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR)) == 0);
3094 if (test_path)
3096 if (!g_test_suite_case_exists (g_test_get_root (), test_path))
3097 g_error ("g_test_trap_subprocess: test does not exist: %s", test_path);
3099 else
3101 test_path = test_run_name;
3104 if (g_test_verbose ())
3105 g_print ("GTest: subprocess: %s\n", test_path);
3107 test_trap_clear ();
3108 test_trap_last_subprocess = g_strdup (test_path);
3110 argv = g_ptr_array_new ();
3111 g_ptr_array_add (argv, test_argv0);
3112 g_ptr_array_add (argv, "-q");
3113 g_ptr_array_add (argv, "-p");
3114 g_ptr_array_add (argv, (char *)test_path);
3115 g_ptr_array_add (argv, "--GTestSubprocess");
3116 if (test_log_fd != -1)
3118 char log_fd_buf[128];
3120 g_ptr_array_add (argv, "--GTestLogFD");
3121 g_snprintf (log_fd_buf, sizeof (log_fd_buf), "%d", test_log_fd);
3122 g_ptr_array_add (argv, log_fd_buf);
3124 g_ptr_array_add (argv, NULL);
3126 flags = G_SPAWN_DO_NOT_REAP_CHILD;
3127 if (test_flags & G_TEST_TRAP_INHERIT_STDIN)
3128 flags |= G_SPAWN_CHILD_INHERITS_STDIN;
3130 if (!g_spawn_async_with_pipes (test_initial_cwd,
3131 (char **)argv->pdata,
3132 NULL, flags,
3133 NULL, NULL,
3134 &pid, NULL, &stdout_fd, &stderr_fd,
3135 &error))
3137 g_error ("g_test_trap_subprocess() failed: %s",
3138 error->message);
3140 g_ptr_array_free (argv, TRUE);
3142 wait_for_child (pid,
3143 stdout_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDOUT),
3144 stderr_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDERR),
3145 usec_timeout);
3149 * g_test_subprocess:
3151 * Returns %TRUE (after g_test_init() has been called) if the test
3152 * program is running under g_test_trap_subprocess().
3154 * Returns: %TRUE if the test program is running under
3155 * g_test_trap_subprocess().
3157 * Since: 2.38
3159 gboolean
3160 g_test_subprocess (void)
3162 return test_in_subprocess;
3166 * g_test_trap_has_passed:
3168 * Check the result of the last g_test_trap_subprocess() call.
3170 * Returns: %TRUE if the last test subprocess terminated successfully.
3172 * Since: 2.16
3174 gboolean
3175 g_test_trap_has_passed (void)
3177 #ifdef G_OS_UNIX
3178 return (WIFEXITED (test_trap_last_status) &&
3179 WEXITSTATUS (test_trap_last_status) == 0);
3180 #else
3181 return test_trap_last_status == 0;
3182 #endif
3186 * g_test_trap_reached_timeout:
3188 * Check the result of the last g_test_trap_subprocess() call.
3190 * Returns: %TRUE if the last test subprocess got killed due to a timeout.
3192 * Since: 2.16
3194 gboolean
3195 g_test_trap_reached_timeout (void)
3197 #ifdef G_OS_UNIX
3198 return (WIFSIGNALED (test_trap_last_status) &&
3199 WTERMSIG (test_trap_last_status) == SIGALRM);
3200 #else
3201 return test_trap_last_status == G_TEST_STATUS_TIMED_OUT;
3202 #endif
3205 static gboolean
3206 log_child_output (const gchar *process_id)
3208 gchar *escaped;
3210 #ifdef G_OS_UNIX
3211 if (WIFEXITED (test_trap_last_status)) /* normal exit */
3213 if (WEXITSTATUS (test_trap_last_status) == 0)
3214 g_test_message ("child process (%s) exit status: 0 (success)",
3215 process_id);
3216 else
3217 g_test_message ("child process (%s) exit status: %d (error)",
3218 process_id, WEXITSTATUS (test_trap_last_status));
3220 else if (WIFSIGNALED (test_trap_last_status) &&
3221 WTERMSIG (test_trap_last_status) == SIGALRM)
3223 g_test_message ("child process (%s) timed out", process_id);
3225 else if (WIFSIGNALED (test_trap_last_status))
3227 const gchar *maybe_dumped_core = "";
3229 #ifdef WCOREDUMP
3230 if (WCOREDUMP (test_trap_last_status))
3231 maybe_dumped_core = ", core dumped";
3232 #endif
3234 g_test_message ("child process (%s) killed by signal %d (%s)%s",
3235 process_id, WTERMSIG (test_trap_last_status),
3236 g_strsignal (WTERMSIG (test_trap_last_status)),
3237 maybe_dumped_core);
3239 else
3241 g_test_message ("child process (%s) unknown wait status %d",
3242 process_id, test_trap_last_status);
3244 #else
3245 if (test_trap_last_status == 0)
3246 g_test_message ("child process (%s) exit status: 0 (success)",
3247 process_id);
3248 else
3249 g_test_message ("child process (%s) exit status: %d (error)",
3250 process_id, test_trap_last_status);
3251 #endif
3253 escaped = g_strescape (test_trap_last_stdout, NULL);
3254 g_test_message ("child process (%s) stdout: \"%s\"", process_id, escaped);
3255 g_free (escaped);
3257 escaped = g_strescape (test_trap_last_stderr, NULL);
3258 g_test_message ("child process (%s) stderr: \"%s\"", process_id, escaped);
3259 g_free (escaped);
3261 /* so we can use short-circuiting:
3262 * logged_child_output = logged_child_output || log_child_output (...) */
3263 return TRUE;
3266 void
3267 g_test_trap_assertions (const char *domain,
3268 const char *file,
3269 int line,
3270 const char *func,
3271 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
3272 const char *pattern)
3274 gboolean must_pass = assertion_flags == 0;
3275 gboolean must_fail = assertion_flags == 1;
3276 gboolean match_result = 0 == (assertion_flags & 1);
3277 gboolean logged_child_output = FALSE;
3278 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
3279 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
3280 const char *match_error = match_result ? "failed to match" : "contains invalid match";
3281 char *process_id;
3283 #ifdef G_OS_UNIX
3284 if (test_trap_last_subprocess != NULL)
3286 process_id = g_strdup_printf ("%s [%d]", test_trap_last_subprocess,
3287 test_trap_last_pid);
3289 else if (test_trap_last_pid != 0)
3290 process_id = g_strdup_printf ("%d", test_trap_last_pid);
3291 #else
3292 if (test_trap_last_subprocess != NULL)
3293 process_id = g_strdup (test_trap_last_subprocess);
3294 #endif
3295 else
3296 g_error ("g_test_trap_ assertion with no trapped test");
3298 if (must_pass && !g_test_trap_has_passed())
3300 char *msg;
3302 logged_child_output = logged_child_output || log_child_output (process_id);
3304 msg = g_strdup_printf ("child process (%s) failed unexpectedly", process_id);
3305 g_assertion_message (domain, file, line, func, msg);
3306 g_free (msg);
3308 if (must_fail && g_test_trap_has_passed())
3310 char *msg;
3312 logged_child_output = logged_child_output || log_child_output (process_id);
3314 msg = g_strdup_printf ("child process (%s) did not fail as expected", process_id);
3315 g_assertion_message (domain, file, line, func, msg);
3316 g_free (msg);
3318 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
3320 char *msg;
3322 logged_child_output = logged_child_output || log_child_output (process_id);
3324 msg = g_strdup_printf ("stdout of child process (%s) %s: %s", process_id, match_error, stdout_pattern);
3325 g_assertion_message (domain, file, line, func, msg);
3326 g_free (msg);
3328 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
3330 char *msg;
3332 logged_child_output = logged_child_output || log_child_output (process_id);
3334 msg = g_strdup_printf ("stderr of child process (%s) %s: %s", process_id, match_error, stderr_pattern);
3335 g_assertion_message (domain, file, line, func, msg);
3336 g_free (msg);
3338 g_free (process_id);
3341 static void
3342 gstring_overwrite_int (GString *gstring,
3343 guint pos,
3344 guint32 vuint)
3346 vuint = g_htonl (vuint);
3347 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
3350 static void
3351 gstring_append_int (GString *gstring,
3352 guint32 vuint)
3354 vuint = g_htonl (vuint);
3355 g_string_append_len (gstring, (const gchar*) &vuint, 4);
3358 static void
3359 gstring_append_double (GString *gstring,
3360 double vdouble)
3362 union { double vdouble; guint64 vuint64; } u;
3363 u.vdouble = vdouble;
3364 u.vuint64 = GUINT64_TO_BE (u.vuint64);
3365 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
3368 static guint8*
3369 g_test_log_dump (GTestLogMsg *msg,
3370 guint *len)
3372 GString *gstring = g_string_sized_new (1024);
3373 guint ui;
3374 gstring_append_int (gstring, 0); /* message length */
3375 gstring_append_int (gstring, msg->log_type);
3376 gstring_append_int (gstring, msg->n_strings);
3377 gstring_append_int (gstring, msg->n_nums);
3378 gstring_append_int (gstring, 0); /* reserved */
3379 for (ui = 0; ui < msg->n_strings; ui++)
3381 guint l = strlen (msg->strings[ui]);
3382 gstring_append_int (gstring, l);
3383 g_string_append_len (gstring, msg->strings[ui], l);
3385 for (ui = 0; ui < msg->n_nums; ui++)
3386 gstring_append_double (gstring, msg->nums[ui]);
3387 *len = gstring->len;
3388 gstring_overwrite_int (gstring, 0, *len); /* message length */
3389 return (guint8*) g_string_free (gstring, FALSE);
3392 static inline long double
3393 net_double (const gchar **ipointer)
3395 union { guint64 vuint64; double vdouble; } u;
3396 guint64 aligned_int64;
3397 memcpy (&aligned_int64, *ipointer, 8);
3398 *ipointer += 8;
3399 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
3400 return u.vdouble;
3403 static inline guint32
3404 net_int (const gchar **ipointer)
3406 guint32 aligned_int;
3407 memcpy (&aligned_int, *ipointer, 4);
3408 *ipointer += 4;
3409 return g_ntohl (aligned_int);
3412 static gboolean
3413 g_test_log_extract (GTestLogBuffer *tbuffer)
3415 const gchar *p = tbuffer->data->str;
3416 GTestLogMsg msg;
3417 guint mlength;
3418 if (tbuffer->data->len < 4 * 5)
3419 return FALSE;
3420 mlength = net_int (&p);
3421 if (tbuffer->data->len < mlength)
3422 return FALSE;
3423 msg.log_type = net_int (&p);
3424 msg.n_strings = net_int (&p);
3425 msg.n_nums = net_int (&p);
3426 if (net_int (&p) == 0)
3428 guint ui;
3429 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
3430 msg.nums = g_new0 (long double, msg.n_nums);
3431 for (ui = 0; ui < msg.n_strings; ui++)
3433 guint sl = net_int (&p);
3434 msg.strings[ui] = g_strndup (p, sl);
3435 p += sl;
3437 for (ui = 0; ui < msg.n_nums; ui++)
3438 msg.nums[ui] = net_double (&p);
3439 if (p <= tbuffer->data->str + mlength)
3441 g_string_erase (tbuffer->data, 0, mlength);
3442 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
3443 return TRUE;
3446 g_free (msg.nums);
3447 g_strfreev (msg.strings);
3450 g_error ("corrupt log stream from test program");
3451 return FALSE;
3455 * g_test_log_buffer_new:
3457 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3459 GTestLogBuffer*
3460 g_test_log_buffer_new (void)
3462 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
3463 tb->data = g_string_sized_new (1024);
3464 return tb;
3468 * g_test_log_buffer_free:
3470 * Internal function for gtester to free test log messages, no ABI guarantees provided.
3472 void
3473 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
3475 g_return_if_fail (tbuffer != NULL);
3476 while (tbuffer->msgs)
3477 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
3478 g_string_free (tbuffer->data, TRUE);
3479 g_free (tbuffer);
3483 * g_test_log_buffer_push:
3485 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3487 void
3488 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
3489 guint n_bytes,
3490 const guint8 *bytes)
3492 g_return_if_fail (tbuffer != NULL);
3493 if (n_bytes)
3495 gboolean more_messages;
3496 g_return_if_fail (bytes != NULL);
3497 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
3499 more_messages = g_test_log_extract (tbuffer);
3500 while (more_messages);
3505 * g_test_log_buffer_pop:
3507 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
3509 GTestLogMsg*
3510 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
3512 GTestLogMsg *msg = NULL;
3513 g_return_val_if_fail (tbuffer != NULL, NULL);
3514 if (tbuffer->msgs)
3516 GSList *slist = g_slist_last (tbuffer->msgs);
3517 msg = slist->data;
3518 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
3520 return msg;
3524 * g_test_log_msg_free:
3526 * Internal function for gtester to free test log messages, no ABI guarantees provided.
3528 void
3529 g_test_log_msg_free (GTestLogMsg *tmsg)
3531 g_return_if_fail (tmsg != NULL);
3532 g_strfreev (tmsg->strings);
3533 g_free (tmsg->nums);
3534 g_free (tmsg);
3537 static gchar *
3538 g_test_build_filename_va (GTestFileType file_type,
3539 const gchar *first_path,
3540 va_list ap)
3542 const gchar *pathv[16];
3543 gint num_path_segments;
3545 if (file_type == G_TEST_DIST)
3546 pathv[0] = test_disted_files_dir;
3547 else if (file_type == G_TEST_BUILT)
3548 pathv[0] = test_built_files_dir;
3549 else
3550 g_assert_not_reached ();
3552 pathv[1] = first_path;
3554 for (num_path_segments = 2; num_path_segments < G_N_ELEMENTS (pathv); num_path_segments++)
3556 pathv[num_path_segments] = va_arg (ap, const char *);
3557 if (pathv[num_path_segments] == NULL)
3558 break;
3561 g_assert_cmpint (num_path_segments, <, G_N_ELEMENTS (pathv));
3563 return g_build_filenamev ((gchar **) pathv);
3567 * g_test_build_filename:
3568 * @file_type: the type of file (built vs. distributed)
3569 * @first_path: the first segment of the pathname
3570 * @...: %NULL-terminated additional path segments
3572 * Creates the pathname to a data file that is required for a test.
3574 * This function is conceptually similar to g_build_filename() except
3575 * that the first argument has been replaced with a #GTestFileType
3576 * argument.
3578 * The data file should either have been distributed with the module
3579 * containing the test (%G_TEST_DIST) or built as part of the build
3580 * system of that module (%G_TEST_BUILT).
3582 * In order for this function to work in srcdir != builddir situations,
3583 * the G_TEST_SRCDIR and G_TEST_BUILDDIR environment variables need to
3584 * have been defined. As of 2.38, this is done by the glib.mk
3585 * included in GLib. Please ensure that your copy is up to date before
3586 * using this function.
3588 * In case neither variable is set, this function will fall back to
3589 * using the dirname portion of argv[0], possibly removing ".libs".
3590 * This allows for casual running of tests directly from the commandline
3591 * in the srcdir == builddir case and should also support running of
3592 * installed tests, assuming the data files have been installed in the
3593 * same relative path as the test binary.
3595 * Returns: the path of the file, to be freed using g_free()
3597 * Since: 2.38
3600 * GTestFileType:
3601 * @G_TEST_DIST: a file that was included in the distribution tarball
3602 * @G_TEST_BUILT: a file that was built on the compiling machine
3604 * The type of file to return the filename for, when used with
3605 * g_test_build_filename().
3607 * These two options correspond rather directly to the 'dist' and
3608 * 'built' terminology that automake uses and are explicitly used to
3609 * distinguish between the 'srcdir' and 'builddir' being separate. All
3610 * files in your project should either be dist (in the
3611 * `EXTRA_DIST` or `dist_schema_DATA`
3612 * sense, in which case they will always be in the srcdir) or built (in
3613 * the `BUILT_SOURCES` sense, in which case they will
3614 * always be in the builddir).
3616 * Note: as a general rule of automake, files that are generated only as
3617 * part of the build-from-git process (but then are distributed with the
3618 * tarball) always go in srcdir (even if doing a srcdir != builddir
3619 * build from git) and are considered as distributed files.
3621 * Since: 2.38
3623 gchar *
3624 g_test_build_filename (GTestFileType file_type,
3625 const gchar *first_path,
3626 ...)
3628 gchar *result;
3629 va_list ap;
3631 g_assert (g_test_initialized ());
3633 va_start (ap, first_path);
3634 result = g_test_build_filename_va (file_type, first_path, ap);
3635 va_end (ap);
3637 return result;
3641 * g_test_get_dir:
3642 * @file_type: the type of file (built vs. distributed)
3644 * Gets the pathname of the directory containing test files of the type
3645 * specified by @file_type.
3647 * This is approximately the same as calling g_test_build_filename("."),
3648 * but you don't need to free the return value.
3650 * Returns: (type filename): the path of the directory, owned by GLib
3652 * Since: 2.38
3654 const gchar *
3655 g_test_get_dir (GTestFileType file_type)
3657 g_assert (g_test_initialized ());
3659 if (file_type == G_TEST_DIST)
3660 return test_disted_files_dir;
3661 else if (file_type == G_TEST_BUILT)
3662 return test_built_files_dir;
3664 g_assert_not_reached ();
3668 * g_test_get_filename:
3669 * @file_type: the type of file (built vs. distributed)
3670 * @first_path: the first segment of the pathname
3671 * @...: %NULL-terminated additional path segments
3673 * Gets the pathname to a data file that is required for a test.
3675 * This is the same as g_test_build_filename() with two differences.
3676 * The first difference is that must only use this function from within
3677 * a testcase function. The second difference is that you need not free
3678 * the return value -- it will be automatically freed when the testcase
3679 * finishes running.
3681 * It is safe to use this function from a thread inside of a testcase
3682 * but you must ensure that all such uses occur before the main testcase
3683 * function returns (ie: it is best to ensure that all threads have been
3684 * joined).
3686 * Returns: the path, automatically freed at the end of the testcase
3688 * Since: 2.38
3690 const gchar *
3691 g_test_get_filename (GTestFileType file_type,
3692 const gchar *first_path,
3693 ...)
3695 gchar *result;
3696 GSList *node;
3697 va_list ap;
3699 g_assert (g_test_initialized ());
3700 if (test_filename_free_list == NULL)
3701 g_error ("g_test_get_filename() can only be used within testcase functions");
3703 va_start (ap, first_path);
3704 result = g_test_build_filename_va (file_type, first_path, ap);
3705 va_end (ap);
3707 node = g_slist_prepend (NULL, result);
3709 node->next = *test_filename_free_list;
3710 while (!g_atomic_pointer_compare_and_exchange (test_filename_free_list, node->next, node));
3712 return result;
3715 /* --- macros docs START --- */
3717 * g_test_add:
3718 * @testpath: The test path for a new test case.
3719 * @Fixture: The type of a fixture data structure.
3720 * @tdata: Data argument for the test functions.
3721 * @fsetup: The function to set up the fixture data.
3722 * @ftest: The actual test function.
3723 * @fteardown: The function to tear down the fixture data.
3725 * Hook up a new test case at @testpath, similar to g_test_add_func().
3726 * A fixture data structure with setup and teardown functions may be provided,
3727 * similar to g_test_create_case().
3729 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
3730 * fteardown() callbacks can expect a @Fixture pointer as their first argument
3731 * in a type safe manner. They otherwise have type #GTestFixtureFunc.
3733 * Since: 2.16
3735 /* --- macros docs END --- */