1 /* GLib testing utilities
2 * Copyright (C) 2007 Imendio AB
3 * Authors: Tim Janik, Sven Herzberg
5 * SPDX-License-Identifier: LGPL-2.1-or-later
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
23 #include "gtestutils.h"
24 #include "gfileutils.h"
26 #include <sys/types.h>
36 #ifdef HAVE_SYS_RESOURCE_H
37 #include <sys/resource.h>
46 #ifdef HAVE_SYS_SELECT_H
47 #include <sys/select.h>
48 #endif /* HAVE_SYS_SELECT_H */
49 #include <glib/gstdio.h>
54 #include "gstrfuncs.h"
58 #include "glib-private.h"
59 #include "gutilsprivate.h"
65 * @short_description: a test framework
67 * GLib provides a framework for writing and maintaining unit tests
68 * in parallel to the code they are testing. The API is designed according
69 * to established concepts found in the other test frameworks (JUnit, NUnit,
70 * RUnit), which in turn is based on smalltalk unit testing concepts.
72 * - Test case: Tests (test methods) are grouped together with their
73 * fixture into test cases.
75 * - Fixture: A test fixture consists of fixture data and setup and
76 * teardown methods to establish the environment for the test
77 * functions. We use fresh fixtures, i.e. fixtures are newly set
78 * up and torn down around each test invocation to avoid dependencies
81 * - Test suite: Test cases can be grouped into test suites, to allow
82 * subsets of the available tests to be run. Test suites can be
83 * grouped into other test suites as well.
85 * The API is designed to handle creation and registration of test suites
86 * and test cases implicitly. A simple call like
87 * |[<!-- language="C" -->
88 * g_test_add_func ("/misc/assertions", test_assertions);
90 * creates a test suite called "misc" with a single test case named
91 * "assertions", which consists of running the test_assertions function.
93 * In addition to the traditional g_assert_true(), the test framework provides
94 * an extended set of assertions for comparisons: g_assert_cmpfloat(),
95 * g_assert_cmpfloat_with_epsilon(), g_assert_cmpint(), g_assert_cmpuint(),
96 * g_assert_cmphex(), g_assert_cmpstr(), g_assert_cmpmem() and
97 * g_assert_cmpvariant(). The
98 * advantage of these variants over plain g_assert_true() is that the assertion
99 * messages can be more elaborate, and include the values of the compared
102 * Note that g_assert() should not be used in unit tests, since it is a no-op
103 * when compiling with `G_DISABLE_ASSERT`. Use g_assert() in production code,
104 * and g_assert_true() in unit tests.
106 * A full example of creating a test suite with two tests using fixtures:
107 * |[<!-- language="C" -->
109 * #include <locale.h>
113 * OtherObject *helper;
117 * my_object_fixture_set_up (MyObjectFixture *fixture,
118 * gconstpointer user_data)
120 * fixture->obj = my_object_new ();
121 * my_object_set_prop1 (fixture->obj, "some-value");
122 * my_object_do_some_complex_setup (fixture->obj, user_data);
124 * fixture->helper = other_object_new ();
128 * my_object_fixture_tear_down (MyObjectFixture *fixture,
129 * gconstpointer user_data)
131 * g_clear_object (&fixture->helper);
132 * g_clear_object (&fixture->obj);
136 * test_my_object_test1 (MyObjectFixture *fixture,
137 * gconstpointer user_data)
139 * g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "initial-value");
143 * test_my_object_test2 (MyObjectFixture *fixture,
144 * gconstpointer user_data)
146 * my_object_do_some_work_using_helper (fixture->obj, fixture->helper);
147 * g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "updated-value");
151 * main (int argc, char *argv[])
153 * setlocale (LC_ALL, "");
155 * g_test_init (&argc, &argv, NULL);
157 * // Define the tests.
158 * g_test_add ("/my-object/test1", MyObjectFixture, "some-user-data",
159 * my_object_fixture_set_up, test_my_object_test1,
160 * my_object_fixture_tear_down);
161 * g_test_add ("/my-object/test2", MyObjectFixture, "some-user-data",
162 * my_object_fixture_set_up, test_my_object_test2,
163 * my_object_fixture_tear_down);
165 * return g_test_run ();
169 * ### Integrating GTest in your project
171 * If you are using the [Meson](http://mesonbuild.com) build system, you will
172 * typically use the provided `test()` primitive to call the test binaries,
175 * |[<!-- language="plain" -->
178 * executable('foo', 'foo.c', dependencies: deps),
180 * 'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
181 * 'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
187 * executable('bar', 'bar.c', dependencies: deps),
189 * 'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
190 * 'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
195 * If you are using Autotools, you're strongly encouraged to use the Automake
196 * [TAP](https://testanything.org/) harness; GLib provides template files for
197 * easily integrating with it:
199 * - [glib-tap.mk](https://gitlab.gnome.org/GNOME/glib/blob/glib-2-58/glib-tap.mk)
200 * - [tap-test](https://gitlab.gnome.org/GNOME/glib/blob/glib-2-58/tap-test)
201 * - [tap-driver.sh](https://gitlab.gnome.org/GNOME/glib/blob/glib-2-58/tap-driver.sh)
203 * You can copy these files in your own project's root directory, and then
204 * set up your `Makefile.am` file to reference them, for instance:
206 * |[<!-- language="plain" -->
207 * include $(top_srcdir)/glib-tap.mk
214 * # data distributed in the tarball
219 * # data not distributed in the tarball
224 * Make sure to distribute the TAP files, using something like the following
225 * in your top-level `Makefile.am`:
227 * |[<!-- language="plain" -->
233 * `glib-tap.mk` will be distributed implicitly due to being included in a
234 * `Makefile.am`. All three files should be added to version control.
236 * If you don't have access to the Autotools TAP harness, you can use the
237 * [gtester][gtester] and [gtester-report][gtester-report] tools, and use
238 * the [glib.mk](https://gitlab.gnome.org/GNOME/glib/blob/glib-2-58/glib.mk)
239 * Automake template provided by GLib. Note, however, that since GLib 2.62,
240 * [gtester][gtester] and [gtester-report][gtester-report] have been deprecated
241 * in favour of using TAP. The `--tap` argument to tests is enabled by default
246 * g_test_initialized:
248 * Returns %TRUE if g_test_init() has been called.
250 * Returns: %TRUE if g_test_init() has been called.
258 * Returns %TRUE if tests are run in quick mode.
259 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
260 * there is no "medium speed".
262 * By default, tests are run in quick mode. In tests that use
263 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
264 * can be used to change this.
266 * Returns: %TRUE if in quick mode
272 * Returns %TRUE if tests are run in slow mode.
273 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
274 * there is no "medium speed".
276 * By default, tests are run in quick mode. In tests that use
277 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
278 * can be used to change this.
280 * Returns: the opposite of g_test_quick()
286 * Returns %TRUE if tests are run in thorough mode, equivalent to
289 * By default, tests are run in quick mode. In tests that use
290 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
291 * can be used to change this.
293 * Returns: the same thing as g_test_slow()
299 * Returns %TRUE if tests are run in performance mode.
301 * By default, tests are run in quick mode. In tests that use
302 * g_test_init(), the option `-m perf` enables performance tests, while
303 * `-m quick` disables them.
305 * Returns: %TRUE if in performance mode
311 * Returns %TRUE if tests may provoke assertions and other formally-undefined
312 * behaviour, to verify that appropriate warnings are given. It might, in some
313 * cases, be useful to turn this off with if running tests under valgrind;
314 * in tests that use g_test_init(), the option `-m no-undefined` disables
315 * those tests, while `-m undefined` explicitly enables them (normally
316 * the default behaviour).
318 * Since GLib 2.68, if GLib was compiled with gcc or clang and
319 * [AddressSanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer)
320 * is enabled, the default changes to not exercising undefined behaviour.
322 * Returns: %TRUE if tests may provoke programming errors
328 * Returns %TRUE if tests are run in verbose mode.
329 * In tests that use g_test_init(), the option `--verbose` enables this,
330 * while `-q` or `--quiet` disables it.
331 * The default is neither g_test_verbose() nor g_test_quiet().
333 * Returns: %TRUE if in verbose mode
339 * Returns %TRUE if tests are run in quiet mode.
340 * In tests that use g_test_init(), the option `-q` or `--quiet` enables
341 * this, while `--verbose` disables it.
342 * The default is neither g_test_verbose() nor g_test_quiet().
344 * Returns: %TRUE if in quiet mode
348 * g_test_queue_unref:
349 * @gobject: the object to unref
351 * Enqueue an object to be released with g_object_unref() during
352 * the next teardown phase. This is equivalent to calling
353 * g_test_queue_destroy() with a destroy callback of g_object_unref().
359 * GTestSubprocessFlags:
360 * @G_TEST_SUBPROCESS_DEFAULT: Default behaviour. Since: 2.74
361 * @G_TEST_SUBPROCESS_INHERIT_STDIN: If this flag is given, the child
362 * process will inherit the parent's stdin. Otherwise, the child's
363 * stdin is redirected to `/dev/null`.
364 * @G_TEST_SUBPROCESS_INHERIT_STDOUT: If this flag is given, the child
365 * process will inherit the parent's stdout. Otherwise, the child's
366 * stdout will not be visible, but it will be captured to allow
367 * later tests with g_test_trap_assert_stdout().
368 * @G_TEST_SUBPROCESS_INHERIT_STDERR: If this flag is given, the child
369 * process will inherit the parent's stderr. Otherwise, the child's
370 * stderr will not be visible, but it will be captured to allow
371 * later tests with g_test_trap_assert_stderr().
373 * Flags to pass to g_test_trap_subprocess() to control input and output.
375 * Note that in contrast with g_test_trap_fork(), the default is to
376 * not show stdout and stderr.
380 * g_test_trap_assert_passed:
382 * Assert that the last test subprocess passed.
383 * See g_test_trap_subprocess().
389 * g_test_trap_assert_failed:
391 * Assert that the last test subprocess failed.
392 * See g_test_trap_subprocess().
394 * This is sometimes used to test situations that are formally considered to
395 * be undefined behaviour, like inputs that fail a g_return_if_fail()
396 * check. In these situations you should skip the entire test, including the
397 * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
398 * to indicate that undefined behaviour may be tested.
404 * g_test_trap_assert_stdout:
405 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
407 * Assert that the stdout output of the last test subprocess matches
408 * @soutpattern. See g_test_trap_subprocess().
414 * g_test_trap_assert_stdout_unmatched:
415 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
417 * Assert that the stdout output of the last test subprocess
418 * does not match @soutpattern. See g_test_trap_subprocess().
424 * g_test_trap_assert_stderr:
425 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
427 * Assert that the stderr output of the last test subprocess
428 * matches @serrpattern. See g_test_trap_subprocess().
430 * This is sometimes used to test situations that are formally
431 * considered to be undefined behaviour, like code that hits a
432 * g_assert() or g_error(). In these situations you should skip the
433 * entire test, including the call to g_test_trap_subprocess(), unless
434 * g_test_undefined() returns %TRUE to indicate that undefined
435 * behaviour may be tested.
441 * g_test_trap_assert_stderr_unmatched:
442 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
444 * Assert that the stderr output of the last test subprocess
445 * does not match @serrpattern. See g_test_trap_subprocess().
453 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
454 * for details on test case random numbers.
461 * @expr: the expression to check
463 * Debugging macro to terminate the application if the assertion
464 * fails. If the assertion fails (i.e. the expression is not true),
465 * an error message is logged and the application is terminated.
467 * The macro can be turned off in final releases of code by defining
468 * `G_DISABLE_ASSERT` when compiling the application, so code must
469 * not depend on any side effects from @expr. Similarly, it must not be used
470 * in unit tests, otherwise the unit tests will be ineffective if compiled with
471 * `G_DISABLE_ASSERT`. Use g_assert_true() and related macros in unit tests
476 * g_assert_not_reached:
478 * Debugging macro to terminate the application if it is ever
479 * reached. If it is reached, an error message is logged and the
480 * application is terminated.
482 * The macro can be turned off in final releases of code by defining
483 * `G_DISABLE_ASSERT` when compiling the application. Hence, it should not be
484 * used in unit tests, where assertions should always be effective.
489 * @expr: the expression to check
491 * Debugging macro to check that an expression is true.
493 * If the assertion fails (i.e. the expression is not true),
494 * an error message is logged and the application is either
495 * terminated or the testcase marked as failed.
497 * Note that unlike g_assert(), this macro is unaffected by whether
498 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
499 * conversely, g_assert() should not be used in tests.
501 * See g_test_set_nonfatal_assertions().
508 * @expr: the expression to check
510 * Debugging macro to check an expression is false.
512 * If the assertion fails (i.e. the expression is not false),
513 * an error message is logged and the application is either
514 * terminated or the testcase marked as failed.
516 * Note that unlike g_assert(), this macro is unaffected by whether
517 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
518 * conversely, g_assert() should not be used in tests.
520 * See g_test_set_nonfatal_assertions().
527 * @expr: the expression to check
529 * Debugging macro to check an expression is %NULL.
531 * If the assertion fails (i.e. the expression is not %NULL),
532 * an error message is logged and the application is either
533 * terminated or the testcase marked as failed.
535 * Note that unlike g_assert(), this macro is unaffected by whether
536 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
537 * conversely, g_assert() should not be used in tests.
539 * See g_test_set_nonfatal_assertions().
546 * @expr: the expression to check
548 * Debugging macro to check an expression is not %NULL.
550 * If the assertion fails (i.e. the expression is %NULL),
551 * an error message is logged and the application is either
552 * terminated or the testcase marked as failed.
554 * Note that unlike g_assert(), this macro is unaffected by whether
555 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
556 * conversely, g_assert() should not be used in tests.
558 * See g_test_set_nonfatal_assertions().
565 * @s1: a string (may be %NULL)
566 * @cmp: The comparison operator to use.
567 * One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
568 * @s2: another string (may be %NULL)
570 * Debugging macro to compare two strings. If the comparison fails,
571 * an error message is logged and the application is either terminated
572 * or the testcase marked as failed.
573 * The strings are compared using g_strcmp0().
575 * The effect of `g_assert_cmpstr (s1, op, s2)` is
576 * the same as `g_assert_true (g_strcmp0 (s1, s2) op 0)`.
577 * The advantage of this macro is that it can produce a message that
578 * includes the actual values of @s1 and @s2.
580 * |[<!-- language="C" -->
581 * g_assert_cmpstr (mystring, ==, "fubar");
589 * @strv1: (nullable): a string array (may be %NULL)
590 * @strv2: (nullable): another string array (may be %NULL)
592 * Debugging macro to check if two %NULL-terminated string arrays (i.e. 2
593 * #GStrv) are equal. If they are not equal, an error message is logged and the
594 * application is either terminated or the testcase marked as failed.
595 * If both arrays are %NULL, the check passes. If one array is %NULL but the
596 * other is not, an error message is logged.
598 * The effect of `g_assert_cmpstrv (strv1, strv2)` is the same as
599 * `g_assert_true (g_strv_equal (strv1, strv2))` (if both arrays are not
600 * %NULL). The advantage of this macro is that it can produce a message that
601 * includes how @strv1 and @strv2 are different.
603 * |[<!-- language="C" -->
604 * const char *expected[] = { "one", "two", "three", NULL };
605 * g_assert_cmpstrv (mystrv, expected);
614 * @cmp: The comparison operator to use.
615 * One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
616 * @n2: another integer
618 * Debugging macro to compare two integers.
620 * The effect of `g_assert_cmpint (n1, op, n2)` is
621 * the same as `g_assert_true (n1 op n2)`. The advantage
622 * of this macro is that it can produce a message that includes the
623 * actual values of @n1 and @n2.
630 * @n1: an unsigned integer
631 * @cmp: The comparison operator to use.
632 * One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
633 * @n2: another unsigned integer
635 * Debugging macro to compare two unsigned integers.
637 * The effect of `g_assert_cmpuint (n1, op, n2)` is
638 * the same as `g_assert_true (n1 op n2)`. The advantage
639 * of this macro is that it can produce a message that includes the
640 * actual values of @n1 and @n2.
647 * @n1: an unsigned integer
648 * @cmp: The comparison operator to use.
649 * One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
650 * @n2: another unsigned integer
652 * Debugging macro to compare to unsigned integers.
654 * This is a variant of g_assert_cmpuint() that displays the numbers
655 * in hexadecimal notation in the message.
662 * @n1: a floating point number
663 * @cmp: The comparison operator to use.
664 * One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
665 * @n2: another floating point number
667 * Debugging macro to compare two floating point numbers.
669 * The effect of `g_assert_cmpfloat (n1, op, n2)` is
670 * the same as `g_assert_true (n1 op n2)`. The advantage
671 * of this macro is that it can produce a message that includes the
672 * actual values of @n1 and @n2.
678 * g_assert_cmpfloat_with_epsilon:
679 * @n1: a floating point number
680 * @n2: another floating point number
681 * @epsilon: a numeric value that expresses the expected tolerance
682 * between @n1 and @n2
684 * Debugging macro to compare two floating point numbers within an epsilon.
686 * The effect of `g_assert_cmpfloat_with_epsilon (n1, n2, epsilon)` is
687 * the same as `g_assert_true (abs (n1 - n2) < epsilon)`. The advantage
688 * of this macro is that it can produce a message that includes the
689 * actual values of @n1 and @n2.
696 * @expr: the expression to check
698 * Debugging macro to check that an expression has a non-negative return value,
699 * as used by traditional POSIX functions (such as `rmdir()`) to indicate
702 * If the assertion fails (i.e. the @expr returns a negative value), an error
703 * message is logged and the testcase is marked as failed. The error message
704 * will contain the value of `errno` and its human-readable message from
707 * This macro will clear the value of `errno` before executing @expr.
714 * @m1: (nullable): pointer to a buffer
716 * @m2: (nullable): pointer to another buffer
719 * Debugging macro to compare memory regions. If the comparison fails,
720 * an error message is logged and the application is either terminated
721 * or the testcase marked as failed.
723 * The effect of `g_assert_cmpmem (m1, l1, m2, l2)` is
724 * the same as `g_assert_true (l1 == l2 && memcmp (m1, m2, l1) == 0)`.
725 * The advantage of this macro is that it can produce a message that
726 * includes the actual values of @l1 and @l2.
728 * @m1 may be %NULL if (and only if) @l1 is zero; similarly for @m2 and @l2.
730 * |[<!-- language="C" -->
731 * g_assert_cmpmem (buf->data, buf->len, expected, sizeof (expected));
738 * g_assert_cmpvariant:
739 * @v1: pointer to a #GVariant
740 * @v2: pointer to another #GVariant
742 * Debugging macro to compare two #GVariants. If the comparison fails,
743 * an error message is logged and the application is either terminated
744 * or the testcase marked as failed. The variants are compared using
747 * The effect of `g_assert_cmpvariant (v1, v2)` is the same as
748 * `g_assert_true (g_variant_equal (v1, v2))`. The advantage of this macro is
749 * that it can produce a message that includes the actual values of @v1 and @v2.
756 * @err: a #GError, possibly %NULL
758 * Debugging macro to check that a #GError is not set.
760 * The effect of `g_assert_no_error (err)` is
761 * the same as `g_assert_true (err == NULL)`. The advantage
762 * of this macro is that it can produce a message that includes
763 * the error message and code.
770 * @err: a #GError, possibly %NULL
771 * @dom: the expected error domain (a #GQuark)
772 * @c: the expected error code
774 * Debugging macro to check that a method has returned
775 * the correct #GError.
777 * The effect of `g_assert_error (err, dom, c)` is
778 * the same as `g_assert_true (err != NULL && err->domain
779 * == dom && err->code == c)`. The advantage of this
780 * macro is that it can produce a message that includes the incorrect
781 * error message and code.
783 * This can only be used to test for a specific error. If you want to
784 * test that @err is set, but don't care what it's set to, just use
785 * `g_assert_nonnull (err)`.
793 * An opaque structure representing a test case.
799 * An opaque structure representing a test suite.
803 /* Global variable for storing assertion messages; this is the counterpart to
804 * glibc's (private) __abort_msg variable, and allows developers and crash
805 * analysis systems like Apport and ABRT to fish out assertion messages from
806 * core dumps, instead of having to catch them on screen output.
808 GLIB_VAR char *__glib_assert_msg;
809 char *__glib_assert_msg = NULL;
811 /* --- constants --- */
812 #define G_TEST_STATUS_TIMED_OUT 1024
814 /* --- structures --- */
819 void (*fixture_setup) (void*, gconstpointer);
820 void (*fixture_test) (void*, gconstpointer);
821 void (*fixture_teardown) (void*, gconstpointer);
830 typedef struct DestroyEntry DestroyEntry;
834 GDestroyNotify destroy_func;
835 gpointer destroy_data;
838 /* --- prototypes --- */
839 static void test_cleanup (void);
840 static void test_run_seed (const gchar *rseed);
841 static void test_trap_clear (void);
842 static guint8* g_test_log_dump (GTestLogMsg *msg,
844 static void gtest_default_log_handler (const gchar *log_domain,
845 GLogLevelFlags log_level,
846 const gchar *message,
847 gpointer unused_data);
850 static const char * const g_test_result_names[] = {
857 /* --- variables --- */
858 static int test_log_fd = -1;
859 static gboolean test_mode_fatal = TRUE;
860 static gboolean g_test_run_once = TRUE;
861 static gboolean test_isolate_dirs = FALSE;
862 static gchar *test_isolate_dirs_tmpdir = NULL;
863 static const gchar *test_tmpdir = NULL;
864 static gboolean test_run_list = FALSE;
865 static gchar *test_run_seedstr = NULL;
866 G_LOCK_DEFINE_STATIC (test_run_rand);
867 static GRand *test_run_rand = NULL;
868 static gchar *test_run_name = "";
869 static GSList **test_filename_free_list;
870 static guint test_run_forks = 0;
871 static guint test_run_count = 0;
872 static guint test_count = 0;
873 static guint test_skipped_count = 0;
874 static GTestResult test_run_success = G_TEST_RUN_FAILURE;
875 static gchar *test_run_msg = NULL;
876 static guint test_startup_skip_count = 0;
877 static GTimer *test_user_timer = NULL;
878 static double test_user_stamp = 0;
879 static GSList *test_paths = NULL;
880 static gboolean test_prefix = FALSE;
881 static gboolean test_prefix_extended = FALSE;
882 static GSList *test_paths_skipped = NULL;
883 static gboolean test_prefix_skipped = FALSE;
884 static gboolean test_prefix_extended_skipped = FALSE;
885 static GTestSuite *test_suite_root = NULL;
886 static int test_trap_last_status = 0; /* unmodified platform-specific status */
887 static GPid test_trap_last_pid = 0;
888 static char *test_trap_last_subprocess = NULL;
889 static char *test_trap_last_stdout = NULL;
890 static char *test_trap_last_stderr = NULL;
891 static char *test_uri_base = NULL;
892 static gboolean test_debug_log = FALSE;
893 static gboolean test_tap_log = TRUE; /* default to TAP as of GLib 2.62; see #1619; the non-TAP output mode is deprecated */
894 static gboolean test_nonfatal_assertions = FALSE;
895 static DestroyEntry *test_destroy_queue = NULL;
896 static const char *test_argv0 = NULL; /* (nullable), points into global argv */
897 static char *test_argv0_dirname = NULL; /* owned by GLib */
898 static const char *test_disted_files_dir; /* points into test_argv0_dirname or an environment variable */
899 static const char *test_built_files_dir; /* points into test_argv0_dirname or an environment variable */
900 static char *test_initial_cwd = NULL;
901 static gboolean test_in_forked_child = FALSE;
902 static gboolean test_in_subprocess = FALSE;
903 static GTestConfig mutable_test_config_vars = {
904 FALSE, /* test_initialized */
905 TRUE, /* test_quick */
906 FALSE, /* test_perf */
907 FALSE, /* test_verbose */
908 FALSE, /* test_quiet */
909 TRUE, /* test_undefined */
911 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
912 static gboolean no_g_set_prgname = FALSE;
914 /* --- functions --- */
916 g_test_log_type_name (GTestLogType log_type)
920 case G_TEST_LOG_NONE: return "none";
921 case G_TEST_LOG_ERROR: return "error";
922 case G_TEST_LOG_START_BINARY: return "binary";
923 case G_TEST_LOG_LIST_CASE: return "list";
924 case G_TEST_LOG_SKIP_CASE: return "skip";
925 case G_TEST_LOG_START_CASE: return "start";
926 case G_TEST_LOG_STOP_CASE: return "stop";
927 case G_TEST_LOG_MIN_RESULT: return "minperf";
928 case G_TEST_LOG_MAX_RESULT: return "maxperf";
929 case G_TEST_LOG_MESSAGE: return "message";
930 case G_TEST_LOG_START_SUITE: return "start suite";
931 case G_TEST_LOG_STOP_SUITE: return "stop suite";
937 g_test_log_send (guint n_bytes,
938 const guint8 *buffer)
940 if (test_log_fd >= 0)
944 r = write (test_log_fd, buffer, n_bytes);
945 while (r < 0 && errno == EINTR);
949 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
952 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
953 msg = g_test_log_buffer_pop (lbuffer);
954 g_warn_if_fail (msg != NULL);
955 g_warn_if_fail (lbuffer->data->len == 0);
956 g_test_log_buffer_free (lbuffer);
958 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
959 for (ui = 0; ui < msg->n_strings; ui++)
960 g_printerr (":{%s}", msg->strings[ui]);
964 for (ui = 0; ui < msg->n_nums; ui++)
966 if ((long double) (long) msg->nums[ui] == msg->nums[ui])
967 g_printerr ("%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
969 g_printerr ("%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
973 g_printerr (":LOG*}\n");
974 g_test_log_msg_free (msg);
979 g_test_log (GTestLogType lbit,
980 const gchar *string1,
981 const gchar *string2,
988 gchar *astrings[3] = { NULL, NULL, NULL };
994 case G_TEST_LOG_START_BINARY:
996 g_print ("# random seed: %s\n", string2);
997 else if (g_test_verbose ())
998 g_print ("GTest: random seed: %s\n", string2);
1000 case G_TEST_LOG_START_SUITE:
1003 /* We only print the TAP "plan" (1..n) ahead of time if we did
1004 * not use the -p option to select specific tests to be run. */
1005 if (string1[0] != 0)
1006 g_print ("# Start of %s tests\n", string1);
1007 else if (test_paths == NULL)
1008 g_print ("1..%d\n", test_count);
1011 case G_TEST_LOG_STOP_SUITE:
1014 /* If we didn't print the TAP "plan" at the beginning because
1015 * we were using -p, we need to print how many tests we ran at
1016 * the end instead. */
1017 if (string1[0] != 0)
1018 g_print ("# End of %s tests\n", string1);
1019 else if (test_paths != NULL)
1020 g_print ("1..%d\n", test_run_count);
1023 case G_TEST_LOG_STOP_CASE:
1025 fail = result == G_TEST_RUN_FAILURE;
1030 /* The TAP representation for an expected failure starts with
1031 * "not ok", even though it does not actually count as failing
1032 * due to the use of the TODO directive. "ok # TODO" would mean
1033 * a test that was expected to fail unexpectedly succeeded,
1034 * for which GTestResult does not currently have a
1035 * representation. */
1036 if (fail || result == G_TEST_RUN_INCOMPLETE)
1041 g_print ("%s %d %s", ok, test_run_count, string1);
1042 if (result == G_TEST_RUN_INCOMPLETE)
1043 g_print (" # TODO %s\n", string2 ? string2 : "");
1044 else if (result == G_TEST_RUN_SKIPPED)
1045 g_print (" # SKIP %s\n", string2 ? string2 : "");
1046 else if (result == G_TEST_RUN_FAILURE && string2 != NULL)
1047 g_print (" - %s\n", string2);
1051 else if (g_test_verbose ())
1052 g_print ("GTest: result: %s\n", g_test_result_names[result]);
1053 else if (!g_test_quiet ())
1054 g_print ("%s\n", g_test_result_names[result]);
1055 if (fail && test_mode_fatal)
1058 g_print ("Bail out!\n");
1061 if (result == G_TEST_RUN_SKIPPED || result == G_TEST_RUN_INCOMPLETE)
1062 test_skipped_count++;
1064 case G_TEST_LOG_SKIP_CASE:
1066 g_print ("ok %d %s # SKIP\n", test_run_count, string1);
1068 case G_TEST_LOG_MIN_RESULT:
1070 g_print ("# min perf: %s\n", string1);
1071 else if (g_test_verbose ())
1072 g_print ("(MINPERF:%s)\n", string1);
1074 case G_TEST_LOG_MAX_RESULT:
1076 g_print ("# max perf: %s\n", string1);
1077 else if (g_test_verbose ())
1078 g_print ("(MAXPERF:%s)\n", string1);
1080 case G_TEST_LOG_MESSAGE:
1083 if (strstr (string1, "\n") == NULL)
1084 g_print ("# %s\n", string1);
1087 char **lines = g_strsplit (string1, "\n", -1);
1090 for (i = 0; lines[i] != NULL; i++)
1091 g_print ("# %s\n", lines[i]);
1096 else if (g_test_verbose ())
1097 g_print ("(MSG: %s)\n", string1);
1099 case G_TEST_LOG_ERROR:
1101 g_print ("Bail out! %s\n", string1);
1102 else if (g_test_verbose ())
1103 g_print ("(ERROR: %s)\n", string1);
1108 msg.log_type = lbit;
1109 msg.n_strings = (string1 != NULL) + (string1 && string2);
1110 msg.strings = astrings;
1111 astrings[0] = (gchar*) string1;
1112 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
1113 msg.n_nums = n_args;
1115 dbuffer = g_test_log_dump (&msg, &dbufferlen);
1116 g_test_log_send (dbufferlen, dbuffer);
1121 case G_TEST_LOG_START_CASE:
1124 else if (g_test_verbose ())
1125 g_print ("GTest: run: %s\n", string1);
1126 else if (!g_test_quiet ())
1127 g_print ("%s: ", string1);
1133 /* We intentionally parse the command line without GOptionContext
1134 * because otherwise you would never be able to test it.
1137 parse_args (gint *argc_p,
1140 guint argc = *argc_p;
1141 gchar **argv = *argv_p;
1144 test_argv0 = argv[0]; /* will be NULL iff argc == 0 */
1145 test_initial_cwd = g_get_current_dir ();
1147 /* parse known args */
1148 for (i = 1; i < argc; i++)
1150 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
1152 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1153 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1154 g_log_set_always_fatal (fatal_mask);
1157 else if (strcmp (argv[i], "--keep-going") == 0 ||
1158 strcmp (argv[i], "-k") == 0)
1160 test_mode_fatal = FALSE;
1163 else if (strcmp (argv[i], "--debug-log") == 0)
1165 test_debug_log = TRUE;
1168 else if (strcmp (argv[i], "--tap") == 0)
1170 test_tap_log = TRUE;
1173 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
1175 gchar *equal = argv[i] + 12;
1177 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
1178 else if (i + 1 < argc)
1181 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
1185 /* Force non-TAP output when using gtester */
1186 test_tap_log = FALSE;
1188 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
1190 gchar *equal = argv[i] + 16;
1192 test_startup_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
1193 else if (i + 1 < argc)
1196 test_startup_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
1200 else if (strcmp ("--GTestSubprocess", argv[i]) == 0)
1202 test_in_subprocess = TRUE;
1203 /* We typically expect these child processes to crash, and some
1204 * tests spawn a *lot* of them. Avoid spamming system crash
1205 * collection programs such as systemd-coredump and abrt.
1207 #ifdef HAVE_SYS_RESOURCE_H
1209 struct rlimit limit = { 0, 0 };
1210 (void) setrlimit (RLIMIT_CORE, &limit);
1215 /* Force non-TAP output when spawning a subprocess, since people often
1216 * test the stdout/stderr of the subprocess strictly */
1217 test_tap_log = FALSE;
1219 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
1221 gchar *equal = argv[i] + 2;
1223 test_paths = g_slist_prepend (test_paths, equal + 1);
1224 else if (i + 1 < argc)
1227 test_paths = g_slist_prepend (test_paths, argv[i]);
1230 if (test_prefix_extended) {
1231 printf ("do not mix [-r | --run-prefix] with '-p'\n");
1236 else if (strcmp ("-r", argv[i]) == 0 ||
1237 strncmp ("-r=", argv[i], 3) == 0 ||
1238 strcmp ("--run-prefix", argv[i]) == 0 ||
1239 strncmp ("--run-prefix=", argv[i], 13) == 0)
1241 gchar *equal = argv[i] + 2;
1243 test_paths = g_slist_prepend (test_paths, equal + 1);
1244 else if (i + 1 < argc)
1247 test_paths = g_slist_prepend (test_paths, argv[i]);
1251 printf ("do not mix [-r | --run-prefix] with '-p'\n");
1254 test_prefix_extended = TRUE;
1256 else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
1258 gchar *equal = argv[i] + 2;
1260 test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
1261 else if (i + 1 < argc)
1264 test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
1267 if (test_prefix_extended_skipped) {
1268 printf ("do not mix [-x | --skip-prefix] with '-s'\n");
1271 test_prefix_skipped = TRUE;
1273 else if (strcmp ("-x", argv[i]) == 0 ||
1274 strncmp ("-x=", argv[i], 3) == 0 ||
1275 strcmp ("--skip-prefix", argv[i]) == 0 ||
1276 strncmp ("--skip-prefix=", argv[i], 14) == 0)
1278 gchar *equal = argv[i] + 2;
1280 test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
1281 else if (i + 1 < argc)
1284 test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
1287 if (test_prefix_skipped) {
1288 printf ("do not mix [-x | --skip-prefix] with '-s'\n");
1291 test_prefix_extended_skipped = TRUE;
1293 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
1295 gchar *equal = argv[i] + 2;
1296 const gchar *mode = "";
1299 else if (i + 1 < argc)
1304 if (strcmp (mode, "perf") == 0)
1305 mutable_test_config_vars.test_perf = TRUE;
1306 else if (strcmp (mode, "slow") == 0)
1307 mutable_test_config_vars.test_quick = FALSE;
1308 else if (strcmp (mode, "thorough") == 0)
1309 mutable_test_config_vars.test_quick = FALSE;
1310 else if (strcmp (mode, "quick") == 0)
1312 mutable_test_config_vars.test_quick = TRUE;
1313 mutable_test_config_vars.test_perf = FALSE;
1315 else if (strcmp (mode, "undefined") == 0)
1316 mutable_test_config_vars.test_undefined = TRUE;
1317 else if (strcmp (mode, "no-undefined") == 0)
1318 mutable_test_config_vars.test_undefined = FALSE;
1320 g_error ("unknown test mode: -m %s", mode);
1323 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
1325 mutable_test_config_vars.test_quiet = TRUE;
1326 mutable_test_config_vars.test_verbose = FALSE;
1329 else if (strcmp ("--verbose", argv[i]) == 0)
1331 mutable_test_config_vars.test_quiet = FALSE;
1332 mutable_test_config_vars.test_verbose = TRUE;
1335 else if (strcmp ("-l", argv[i]) == 0)
1337 test_run_list = TRUE;
1340 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
1342 gchar *equal = argv[i] + 6;
1344 test_run_seedstr = equal + 1;
1345 else if (i + 1 < argc)
1348 test_run_seedstr = argv[i];
1352 else if (strcmp ("-?", argv[i]) == 0 ||
1353 strcmp ("-h", argv[i]) == 0 ||
1354 strcmp ("--help", argv[i]) == 0)
1357 " %s [OPTION...]\n\n"
1359 " -h, --help Show help options\n\n"
1361 " --g-fatal-warnings Make all warnings fatal\n"
1362 " -l List test cases available in a test executable\n"
1363 " -m {perf|slow|thorough|quick} Execute tests according to mode\n"
1364 " -m {undefined|no-undefined} Execute tests according to mode\n"
1365 " -p TESTPATH Only start test cases matching TESTPATH\n"
1366 " -s TESTPATH Skip all tests matching TESTPATH\n"
1367 " [-r | --run-prefix] PREFIX Only start test cases (or suites) matching PREFIX (incompatible with -p).\n"
1368 " Unlike the -p option (which only goes one level deep), this option would \n"
1369 " run all tests path that have PREFIX at the beginning of their name.\n"
1370 " Note that the prefix used should be a valid test path (and not a simple prefix).\n"
1371 " [-x | --skip-prefix] PREFIX Skip all tests matching PREFIX (incompatible with -s)\n"
1372 " Unlike the -s option (which only skips the exact TESTPATH), this option will \n"
1373 " skip all the tests that begins with PREFIX).\n"
1374 " --seed=SEEDSTRING Start tests with random seed SEEDSTRING\n"
1375 " --debug-log debug test logging output\n"
1376 " -q, --quiet Run tests quietly\n"
1377 " --verbose Run tests verbosely\n",
1383 /* We've been prepending to test_paths, but its order matters, so
1385 test_paths = g_slist_reverse (test_paths);
1389 for (i = 0; i < argc; i++)
1392 argv[e++] = argv[i];
1399 /* A fairly naive `rm -rf` implementation to clean up after unit tests. */
1401 rm_rf (const gchar *path)
1406 dir = g_dir_open (path, 0, NULL);
1409 /* Assume it’s a file. Ignore failure. */
1410 (void) g_remove (path);
1414 while ((entry = g_dir_read_name (dir)) != NULL)
1416 gchar *sub_path = g_build_filename (path, entry, NULL);
1426 /* Implement the %G_TEST_OPTION_ISOLATE_DIRS option, iff it’s enabled. Create
1427 * a temporary directory for this unit test (disambiguated using @test_run_name)
1428 * and use g_set_user_dirs() to point various XDG directories into it, without
1429 * having to call setenv() in a process which potentially has threads running.
1431 * Note that this is called for each unit test, and hence won’t have taken
1432 * effect before g_test_run() is called in the unit test’s main(). Hence
1433 * references to XDG variables in main() will not be using the temporary
1436 test_do_isolate_dirs (GError **error)
1438 gchar *subdir = NULL;
1439 gchar *home_dir = NULL, *cache_dir = NULL, *config_dir = NULL;
1440 gchar *state_dir = NULL, *data_dir = NULL, *runtime_dir = NULL;
1441 gchar *config_dirs[3];
1442 gchar *data_dirs[3];
1444 if (!test_isolate_dirs)
1447 /* The @test_run_name includes the test suites, so may be several directories
1448 * deep. Add a `.dirs` directory to contain all the paths we create, and
1449 * guarantee none of them clash with test paths below the current one — test
1450 * paths may not contain components starting with `.`. */
1451 subdir = g_build_filename (test_tmpdir, test_run_name, ".dirs", NULL);
1453 /* We have to create the runtime directory (because it must be bound to
1454 * the session lifetime, which we consider to be the lifetime of the unit
1455 * test for testing purposes — see
1456 * https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html.
1457 * We don’t need to create the other directories — the specification
1458 * requires that client code create them if they don’t exist. Not creating
1459 * them automatically is a good test of clients’ adherence to the spec
1460 * and error handling of missing directories. */
1461 runtime_dir = g_build_filename (subdir, "runtime", NULL);
1462 if (g_mkdir_with_parents (runtime_dir, 0700) != 0)
1464 gint saved_errno = errno;
1465 g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
1466 "Failed to create XDG_RUNTIME_DIR ‘%s’: %s",
1467 runtime_dir, g_strerror (saved_errno));
1468 g_free (runtime_dir);
1473 home_dir = g_build_filename (subdir, "home", NULL);
1474 cache_dir = g_build_filename (subdir, "cache", NULL);
1475 config_dir = g_build_filename (subdir, "config", NULL);
1476 data_dir = g_build_filename (subdir, "data", NULL);
1477 state_dir = g_build_filename (subdir, "state", NULL);
1479 config_dirs[0] = g_build_filename (subdir, "system-config1", NULL);
1480 config_dirs[1] = g_build_filename (subdir, "system-config2", NULL);
1481 config_dirs[2] = NULL;
1483 data_dirs[0] = g_build_filename (subdir, "system-data1", NULL);
1484 data_dirs[1] = g_build_filename (subdir, "system-data2", NULL);
1485 data_dirs[2] = NULL;
1487 /* Remember to update the documentation for %G_TEST_OPTION_ISOLATE_DIRS if
1488 * this list changes. */
1489 g_set_user_dirs ("HOME", home_dir,
1490 "XDG_CACHE_HOME", cache_dir,
1491 "XDG_CONFIG_DIRS", config_dirs,
1492 "XDG_CONFIG_HOME", config_dir,
1493 "XDG_DATA_DIRS", data_dirs,
1494 "XDG_DATA_HOME", data_dir,
1495 "XDG_STATE_HOME", state_dir,
1496 "XDG_RUNTIME_DIR", runtime_dir,
1499 g_free (runtime_dir);
1502 g_free (config_dir);
1505 g_free (data_dirs[1]);
1506 g_free (data_dirs[0]);
1507 g_free (config_dirs[1]);
1508 g_free (config_dirs[0]);
1514 /* Clean up after test_do_isolate_dirs(). */
1516 test_rm_isolate_dirs (void)
1518 gchar *subdir = NULL;
1520 if (!test_isolate_dirs)
1523 subdir = g_build_filename (test_tmpdir, test_run_name, NULL);
1530 * @argc: Address of the @argc parameter of the main() function.
1531 * Changed if any arguments were handled.
1532 * @argv: Address of the @argv parameter of main().
1533 * Any parameters understood by g_test_init() stripped before return.
1534 * @...: %NULL-terminated list of special options, documented below.
1536 * Initialize the GLib testing framework, e.g. by seeding the
1537 * test random number generator, the name for g_get_prgname()
1538 * and parsing test related command line args.
1540 * So far, the following arguments are understood:
1542 * - `-l`: List test cases available in a test executable.
1543 * - `--seed=SEED`: Provide a random seed to reproduce test
1544 * runs using random numbers.
1545 * - `--verbose`: Run tests verbosely.
1546 * - `-q`, `--quiet`: Run tests quietly.
1547 * - `-p PATH`: Execute all tests matching the given path.
1548 * - `-s PATH`: Skip all tests matching the given path.
1549 * This can also be used to force a test to run that would otherwise
1550 * be skipped (ie, a test whose name contains "/subprocess").
1551 * - `-m {perf|slow|thorough|quick|undefined|no-undefined}`: Execute tests according to these test modes:
1553 * `perf`: Performance tests, may take long and report results (off by default).
1555 * `slow`, `thorough`: Slow and thorough tests, may take quite long and maximize coverage
1558 * `quick`: Quick tests, should run really quickly and give good coverage (the default).
1560 * `undefined`: Tests for undefined behaviour, may provoke programming errors
1561 * under g_test_trap_subprocess() or g_test_expect_message() to check
1562 * that appropriate assertions or warnings are given (the default).
1564 * `no-undefined`: Avoid tests for undefined behaviour
1566 * - `--debug-log`: Debug test logging output.
1568 * Options which can be passed to @... are:
1570 * - `"no_g_set_prgname"`: Causes g_test_init() to not call g_set_prgname().
1571 * - %G_TEST_OPTION_ISOLATE_DIRS: Creates a unique temporary directory for each
1572 * unit test and uses g_set_user_dirs() to set XDG directories to point into
1573 * that temporary directory for the duration of the unit test. See the
1574 * documentation for %G_TEST_OPTION_ISOLATE_DIRS.
1576 * Since 2.58, if tests are compiled with `G_DISABLE_ASSERT` defined,
1577 * g_test_init() will print an error and exit. This is to prevent no-op tests
1578 * from being executed, as g_assert() is commonly (erroneously) used in unit
1579 * tests, and is a no-op when compiled with `G_DISABLE_ASSERT`. Ensure your
1580 * tests are compiled without `G_DISABLE_ASSERT` defined.
1585 (g_test_init) (int *argc,
1589 static char seedstr[4 + 4 * 8 + 1];
1592 /* make warnings and criticals fatal for all test programs */
1593 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1595 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1596 g_log_set_always_fatal (fatal_mask);
1597 /* check caller args */
1598 g_return_if_fail (argc != NULL);
1599 g_return_if_fail (argv != NULL);
1600 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
1601 mutable_test_config_vars.test_initialized = TRUE;
1603 #ifdef _GLIB_ADDRESS_SANITIZER
1604 mutable_test_config_vars.test_undefined = FALSE;
1608 // don't open a window for errors (like the "abort() was called one")
1609 _CrtSetReportMode (_CRT_ERROR, _CRTDBG_MODE_FILE);
1610 _CrtSetReportFile (_CRT_ERROR, _CRTDBG_FILE_STDERR);
1611 // while gtest tests tend to use g_assert and friends
1612 // if they do use the C standard assert macro we want to
1613 // output a message to stderr, not open a popup window
1614 _CrtSetReportMode (_CRT_ASSERT, _CRTDBG_MODE_FILE);
1615 _CrtSetReportFile (_CRT_ASSERT, _CRTDBG_FILE_STDERR);
1616 // in release mode abort() will pop up a windows error
1617 // reporting dialog, let's prevent that. Only msvcrxx and
1618 // the UCRT have this function, but there's no great way to
1619 // detect msvcrxx (that I know of) so only call this when using
1622 _set_abort_behavior (0, _CALL_REPORTFAULT);
1626 va_start (args, argv);
1627 while ((option = va_arg (args, char *)))
1629 if (g_strcmp0 (option, "no_g_set_prgname") == 0)
1630 no_g_set_prgname = TRUE;
1631 else if (g_strcmp0 (option, G_TEST_OPTION_ISOLATE_DIRS) == 0)
1632 test_isolate_dirs = TRUE;
1636 /* setup random seed string */
1637 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
1638 test_run_seedstr = seedstr;
1640 /* parse args, sets up mode, changes seed, etc. */
1641 parse_args (argc, argv);
1643 if (!g_get_prgname() && !no_g_set_prgname)
1644 g_set_prgname ((*argv)[0]);
1646 /* Set up the temporary directory for isolating the test. We have to do this
1647 * early, as we want the return values from g_get_user_data_dir() (and
1648 * friends) to return subdirectories of the temporary directory throughout
1649 * the setup function, test, and teardown function, for each unit test.
1650 * See test_do_isolate_dirs().
1652 * The directory is deleted at the bottom of g_test_run().
1654 * Rather than setting the XDG_* environment variables we use a new
1655 * G_TEST_TMPDIR variable which gives the top-level temporary directory. This
1656 * allows test subprocesses to reuse the same temporary directory when
1657 * g_test_init() is called in them. */
1658 if (test_isolate_dirs)
1660 if (g_getenv ("G_TEST_TMPDIR") == NULL)
1662 gchar *test_prgname = NULL;
1664 GError *local_error = NULL;
1666 test_prgname = g_path_get_basename (g_get_prgname ());
1667 if (*test_prgname == '\0')
1669 g_free (test_prgname);
1670 test_prgname = g_strdup ("unknown");
1672 tmpl = g_strdup_printf ("test_%s_XXXXXX", test_prgname);
1673 g_free (test_prgname);
1675 test_isolate_dirs_tmpdir = g_dir_make_tmp (tmpl, &local_error);
1676 if (local_error != NULL)
1678 g_printerr ("%s: Failed to create temporary directory: %s\n",
1679 (*argv)[0], local_error->message);
1680 g_error_free (local_error);
1685 /* Propagate the temporary directory to subprocesses. */
1686 g_setenv ("G_TEST_TMPDIR", test_isolate_dirs_tmpdir, TRUE);
1688 /* And clear the traditional environment variables so subprocesses
1689 * spawned by the code under test can’t trash anything. If a test
1690 * spawns a process, the test is responsible for propagating
1691 * appropriate environment variables.
1693 * We assume that any in-process code will use g_get_user_data_dir()
1694 * and friends, rather than getenv() directly.
1696 * We set them to ‘/dev/null’ as that should fairly obviously not
1697 * accidentally work, and should be fairly greppable. */
1699 const gchar *overridden_environment_variables[] =
1711 for (i = 0; i < G_N_ELEMENTS (overridden_environment_variables); i++)
1712 g_setenv (overridden_environment_variables[i], "/dev/null", TRUE);
1716 /* Cache this for the remainder of this process’ lifetime. */
1717 test_tmpdir = g_getenv ("G_TEST_TMPDIR");
1720 /* verify GRand reliability, needed for reliable seeds */
1723 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
1724 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
1725 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
1726 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
1727 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
1731 /* check rand seed */
1732 test_run_seed (test_run_seedstr);
1734 /* report program start */
1735 g_log_set_default_handler (gtest_default_log_handler, NULL);
1736 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
1738 test_argv0_dirname = (test_argv0 != NULL) ? g_path_get_dirname (test_argv0) : g_strdup (".");
1740 /* Make sure we get the real dirname that the test was run from */
1741 if (g_str_has_suffix (test_argv0_dirname, "/.libs"))
1744 tmp = g_path_get_dirname (test_argv0_dirname);
1745 g_free (test_argv0_dirname);
1746 test_argv0_dirname = tmp;
1749 test_disted_files_dir = g_getenv ("G_TEST_SRCDIR");
1750 if (!test_disted_files_dir)
1751 test_disted_files_dir = test_argv0_dirname;
1753 test_built_files_dir = g_getenv ("G_TEST_BUILDDIR");
1754 if (!test_built_files_dir)
1755 test_built_files_dir = test_argv0_dirname;
1761 /* Free statically allocated variables */
1763 g_clear_pointer (&test_run_rand, g_rand_free);
1765 g_clear_pointer (&test_argv0_dirname, g_free);
1767 g_clear_pointer (&test_initial_cwd, g_free);
1771 test_run_seed (const gchar *rseed)
1773 guint seed_failed = 0;
1775 g_rand_free (test_run_rand);
1776 test_run_rand = NULL;
1777 while (strchr (" \t\v\r\n\f", *rseed))
1779 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
1781 const char *s = rseed + 4;
1782 if (strlen (s) >= 32) /* require 4 * 8 chars */
1784 guint32 seedarray[4];
1785 gchar *p, hexbuf[9] = { 0, };
1786 memcpy (hexbuf, s + 0, 8);
1787 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
1788 seed_failed += p != NULL && *p != 0;
1789 memcpy (hexbuf, s + 8, 8);
1790 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
1791 seed_failed += p != NULL && *p != 0;
1792 memcpy (hexbuf, s + 16, 8);
1793 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
1794 seed_failed += p != NULL && *p != 0;
1795 memcpy (hexbuf, s + 24, 8);
1796 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
1797 seed_failed += p != NULL && *p != 0;
1800 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
1805 g_error ("Unknown or invalid random seed: %s", rseed);
1811 * Get a reproducible random integer number.
1813 * The random numbers generated by the g_test_rand_*() family of functions
1814 * change with every new test program start, unless the --seed option is
1815 * given when starting test programs.
1817 * For individual test cases however, the random number generator is
1818 * reseeded, to avoid dependencies between tests and to make --seed
1819 * effective for all test cases.
1821 * Returns: a random number from the seeded random number generator.
1826 g_test_rand_int (void)
1830 G_LOCK (test_run_rand);
1831 r = g_rand_int (test_run_rand);
1832 G_UNLOCK (test_run_rand);
1838 * g_test_rand_int_range:
1839 * @begin: the minimum value returned by this function
1840 * @end: the smallest value not to be returned by this function
1842 * Get a reproducible random integer number out of a specified range,
1843 * see g_test_rand_int() for details on test case random numbers.
1845 * Returns: a number with @begin <= number < @end.
1850 g_test_rand_int_range (gint32 begin,
1855 G_LOCK (test_run_rand);
1856 r = g_rand_int_range (test_run_rand, begin, end);
1857 G_UNLOCK (test_run_rand);
1863 * g_test_rand_double:
1865 * Get a reproducible random floating point number,
1866 * see g_test_rand_int() for details on test case random numbers.
1868 * Returns: a random number from the seeded random number generator.
1873 g_test_rand_double (void)
1877 G_LOCK (test_run_rand);
1878 r = g_rand_double (test_run_rand);
1879 G_UNLOCK (test_run_rand);
1885 * g_test_rand_double_range:
1886 * @range_start: the minimum value returned by this function
1887 * @range_end: the minimum value not returned by this function
1889 * Get a reproducible random floating pointer number out of a specified range,
1890 * see g_test_rand_int() for details on test case random numbers.
1892 * Returns: a number with @range_start <= number < @range_end.
1897 g_test_rand_double_range (double range_start,
1902 G_LOCK (test_run_rand);
1903 r = g_rand_double_range (test_run_rand, range_start, range_end);
1904 G_UNLOCK (test_run_rand);
1910 * g_test_timer_start:
1912 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1913 * to be done. Call this function again to restart the timer.
1918 g_test_timer_start (void)
1920 if (!test_user_timer)
1921 test_user_timer = g_timer_new();
1922 test_user_stamp = 0;
1923 g_timer_start (test_user_timer);
1927 * g_test_timer_elapsed:
1929 * Get the number of seconds since the last start of the timer with
1930 * g_test_timer_start().
1932 * Returns: the time since the last start of the timer in seconds, as a double
1937 g_test_timer_elapsed (void)
1939 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1940 return test_user_stamp;
1944 * g_test_timer_last:
1946 * Report the last result of g_test_timer_elapsed().
1948 * Returns: the last result of g_test_timer_elapsed(), as a double
1953 g_test_timer_last (void)
1955 return test_user_stamp;
1959 * g_test_minimized_result:
1960 * @minimized_quantity: the reported value
1961 * @format: the format string of the report message
1962 * @...: arguments to pass to the printf() function
1964 * Report the result of a performance or measurement test.
1965 * The test should generally strive to minimize the reported
1966 * quantities (smaller values are better than larger ones),
1967 * this and @minimized_quantity can determine sorting
1968 * order for test result reports.
1973 g_test_minimized_result (double minimized_quantity,
1977 long double largs = minimized_quantity;
1981 va_start (args, format);
1982 buffer = g_strdup_vprintf (format, args);
1985 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1990 * g_test_maximized_result:
1991 * @maximized_quantity: the reported value
1992 * @format: the format string of the report message
1993 * @...: arguments to pass to the printf() function
1995 * Report the result of a performance or measurement test.
1996 * The test should generally strive to maximize the reported
1997 * quantities (larger values are better than smaller ones),
1998 * this and @maximized_quantity can determine sorting
1999 * order for test result reports.
2004 g_test_maximized_result (double maximized_quantity,
2008 long double largs = maximized_quantity;
2012 va_start (args, format);
2013 buffer = g_strdup_vprintf (format, args);
2016 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
2022 * @format: the format string
2023 * @...: printf-like arguments to @format
2025 * Add a message to the test report.
2030 g_test_message (const char *format,
2036 va_start (args, format);
2037 buffer = g_strdup_vprintf (format, args);
2040 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
2046 * @uri_pattern: the base pattern for bug URIs
2048 * Specify the base URI for bug reports.
2050 * The base URI is used to construct bug report messages for
2051 * g_test_message() when g_test_bug() is called.
2052 * Calling this function outside of a test case sets the
2053 * default base URI for all test cases. Calling it from within
2054 * a test case changes the base URI for the scope of the test
2056 * Bug URIs are constructed by appending a bug specific URI
2057 * portion to @uri_pattern, or by replacing the special string
2058 * `%s` within @uri_pattern if that is present.
2060 * If g_test_bug_base() is not called, bug URIs are formed solely
2061 * from the value provided by g_test_bug().
2066 g_test_bug_base (const char *uri_pattern)
2068 g_free (test_uri_base);
2069 test_uri_base = g_strdup (uri_pattern);
2074 * @bug_uri_snippet: Bug specific bug tracker URI or URI portion.
2076 * This function adds a message to test reports that
2077 * associates a bug URI with a test case.
2079 * Bug URIs are constructed from a base URI set with g_test_bug_base()
2080 * and @bug_uri_snippet. If g_test_bug_base() has not been called, it is
2081 * assumed to be the empty string, so a full URI can be provided to
2082 * g_test_bug() instead.
2084 * Since GLib 2.70, the base URI is not prepended to @bug_uri_snippet if it
2085 * is already a valid URI.
2088 * See also: g_test_summary()
2091 g_test_bug (const char *bug_uri_snippet)
2093 const char *c = NULL;
2095 g_return_if_fail (bug_uri_snippet != NULL);
2097 if (g_str_has_prefix (bug_uri_snippet, "http:") ||
2098 g_str_has_prefix (bug_uri_snippet, "https:"))
2100 g_test_message ("Bug Reference: %s", bug_uri_snippet);
2104 if (test_uri_base != NULL)
2105 c = strstr (test_uri_base, "%s");
2108 char *b = g_strndup (test_uri_base, c - test_uri_base);
2109 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
2111 g_test_message ("Bug Reference: %s", s);
2115 g_test_message ("Bug Reference: %s%s",
2116 test_uri_base ? test_uri_base : "", bug_uri_snippet);
2121 * @summary: One or two sentences summarising what the test checks, and how it
2124 * Set the summary for a test, which describes what the test checks, and how it
2125 * goes about checking it. This may be included in test report output, and is
2126 * useful documentation for anyone reading the source code or modifying a test
2127 * in future. It must be a single line.
2129 * This should be called at the top of a test function.
2132 * |[<!-- language="C" -->
2134 * test_array_sort (void)
2136 * g_test_summary ("Test my_array_sort() sorts the array correctly and stably, "
2137 * "including testing zero length and one-element arrays.");
2144 * See also: g_test_bug()
2147 g_test_summary (const char *summary)
2149 g_return_if_fail (summary != NULL);
2150 g_return_if_fail (strchr (summary, '\n') == NULL);
2151 g_return_if_fail (strchr (summary, '\r') == NULL);
2153 g_test_message ("%s summary: %s", test_run_name, summary);
2159 * Get the toplevel test suite for the test path API.
2161 * Returns: the toplevel #GTestSuite
2166 g_test_get_root (void)
2168 if (!test_suite_root)
2170 test_suite_root = g_test_create_suite ("root");
2171 g_free (test_suite_root->name);
2172 test_suite_root->name = g_strdup ("");
2175 return test_suite_root;
2181 * Runs all tests under the toplevel suite which can be retrieved
2182 * with g_test_get_root(). Similar to g_test_run_suite(), the test
2183 * cases to be run are filtered according to test path arguments
2184 * (`-p testpath` and `-s testpath`) as parsed by g_test_init().
2185 * g_test_run_suite() or g_test_run() may only be called once in a
2188 * In general, the tests and sub-suites within each suite are run in
2189 * the order in which they are defined. However, note that prior to
2190 * GLib 2.36, there was a bug in the `g_test_add_*`
2191 * functions which caused them to create multiple suites with the same
2192 * name, meaning that if you created tests "/foo/simple",
2193 * "/bar/simple", and "/foo/using-bar" in that order, they would get
2194 * run in that order (since g_test_run() would run the first "/foo"
2195 * suite, then the "/bar" suite, then the second "/foo" suite). As of
2196 * 2.36, this bug is fixed, and adding the tests in that order would
2197 * result in a running order of "/foo/simple", "/foo/using-bar",
2198 * "/bar/simple". If this new ordering is sub-optimal (because it puts
2199 * more-complicated tests before simpler ones, making it harder to
2200 * figure out exactly what has failed), you can fix it by changing the
2201 * test paths to group tests by suite in a way that will result in the
2202 * desired running order. Eg, "/simple/foo", "/simple/bar",
2203 * "/complex/foo-using-bar".
2205 * However, you should never make the actual result of a test depend
2206 * on the order that tests are run in. If you need to ensure that some
2207 * particular code runs before or after a given test case, use
2208 * g_test_add(), which lets you specify setup and teardown functions.
2210 * If all tests are skipped or marked as incomplete (expected failures),
2211 * this function will return 0 if producing TAP output, or 77 (treated
2212 * as "skip test" by Automake) otherwise.
2214 * Returns: 0 on success, 1 on failure (assuming it returns at all),
2215 * 0 or 77 if all tests were skipped with g_test_skip() and/or
2216 * g_test_incomplete()
2226 if (atexit (test_cleanup) != 0)
2229 g_error ("Unable to register test cleanup to be run at exit: %s",
2230 g_strerror (errsv));
2233 suite = g_test_get_root ();
2234 if (g_test_run_suite (suite) != 0)
2240 /* Clean up the temporary directory. */
2241 if (test_isolate_dirs_tmpdir != NULL)
2243 rm_rf (test_isolate_dirs_tmpdir);
2244 g_free (test_isolate_dirs_tmpdir);
2245 test_isolate_dirs_tmpdir = NULL;
2248 /* 77 is special to Automake's default driver, but not Automake's TAP driver
2249 * or Perl's prove(1) TAP driver. */
2256 if (test_run_count > 0 && test_run_count == test_skipped_count)
2268 g_test_suite_free (suite);
2273 * g_test_create_case:
2274 * @test_name: the name for the test case
2275 * @data_size: the size of the fixture data structure
2276 * @test_data: test data argument for the test functions
2277 * @data_setup: (scope async): the function to set up the fixture data
2278 * @data_test: (scope async): the actual test function
2279 * @data_teardown: (scope async): the function to teardown the fixture data
2281 * Create a new #GTestCase, named @test_name.
2283 * This API is fairly low level, and calling g_test_add() or g_test_add_func()
2286 * When this test is executed, a fixture structure of size @data_size
2287 * will be automatically allocated and filled with zeros. Then @data_setup is
2288 * called to initialize the fixture. After fixture setup, the actual test
2289 * function @data_test is called. Once the test run completes, the
2290 * fixture structure is torn down by calling @data_teardown and
2291 * after that the memory is automatically released by the test framework.
2293 * Splitting up a test run into fixture setup, test function and
2294 * fixture teardown is most useful if the same fixture type is used for
2295 * multiple tests. In this cases, g_test_create_case() will be
2296 * called with the same type of fixture (the @data_size argument), but varying
2297 * @test_name and @data_test arguments.
2299 * Returns: a newly allocated #GTestCase.
2304 g_test_create_case (const char *test_name,
2306 gconstpointer test_data,
2307 GTestFixtureFunc data_setup,
2308 GTestFixtureFunc data_test,
2309 GTestFixtureFunc data_teardown)
2313 g_return_val_if_fail (test_name != NULL, NULL);
2314 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
2315 g_return_val_if_fail (test_name[0] != 0, NULL);
2316 g_return_val_if_fail (data_test != NULL, NULL);
2318 tc = g_slice_new0 (GTestCase);
2319 tc->name = g_strdup (test_name);
2320 tc->test_data = (gpointer) test_data;
2321 tc->fixture_size = data_size;
2322 tc->fixture_setup = (void*) data_setup;
2323 tc->fixture_test = (void*) data_test;
2324 tc->fixture_teardown = (void*) data_teardown;
2330 find_suite (gconstpointer l, gconstpointer s)
2332 const GTestSuite *suite = l;
2333 const gchar *str = s;
2335 return strcmp (suite->name, str);
2339 find_case (gconstpointer l, gconstpointer s)
2341 const GTestCase *tc = l;
2342 const gchar *str = s;
2344 return strcmp (tc->name, str);
2349 * @fixture: (not nullable): the test fixture
2350 * @user_data: the data provided when registering the test
2352 * The type used for functions that operate on test fixtures. This is
2353 * used for the fixture setup and teardown functions as well as for the
2354 * testcases themselves.
2356 * @user_data is a pointer to the data that was given when registering
2359 * @fixture will be a pointer to the area of memory allocated by the
2360 * test framework, of the size requested. If the requested size was
2361 * zero then @fixture will be equal to @user_data.
2366 g_test_add_vtable (const char *testpath,
2368 gconstpointer test_data,
2369 GTestFixtureFunc data_setup,
2370 GTestFixtureFunc fixture_test_func,
2371 GTestFixtureFunc data_teardown)
2377 g_return_if_fail (testpath != NULL);
2378 g_return_if_fail (g_path_is_absolute (testpath));
2379 g_return_if_fail (fixture_test_func != NULL);
2380 g_return_if_fail (!test_isolate_dirs || strstr (testpath, "/.") == NULL);
2382 suite = g_test_get_root();
2383 segments = g_strsplit (testpath, "/", -1);
2384 for (ui = 0; segments[ui] != NULL; ui++)
2386 const char *seg = segments[ui];
2387 gboolean islast = segments[ui + 1] == NULL;
2388 if (islast && !seg[0])
2389 g_error ("invalid test case path: %s", testpath);
2391 continue; /* initial or duplicate slash */
2396 l = g_slist_find_custom (suite->suites, seg, find_suite);
2403 csuite = g_test_create_suite (seg);
2404 g_test_suite_add_suite (suite, csuite);
2412 if (g_slist_find_custom (suite->cases, seg, find_case))
2413 g_error ("duplicate test case path: %s", testpath);
2415 tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
2416 g_test_suite_add (suite, tc);
2419 g_strfreev (segments);
2425 * Indicates that a test failed. This function can be called
2426 * multiple times from the same test. You can use this function
2427 * if your test failed in a recoverable way.
2429 * Do not use this function if the failure of a test could cause
2430 * other tests to malfunction.
2432 * Calling this function will not stop the test from running, you
2433 * need to return from the test function yourself. So you can
2434 * produce additional diagnostic messages or even continue running
2437 * If not called from inside a test, this function does nothing.
2439 * Note that unlike g_test_skip() and g_test_incomplete(), this
2440 * function does not log a message alongside the test failure.
2441 * If details of the test failure are available, either log them with
2442 * g_test_message() before g_test_fail(), or use g_test_fail_printf()
2450 test_run_success = G_TEST_RUN_FAILURE;
2451 g_clear_pointer (&test_run_msg, g_free);
2455 * g_test_fail_printf:
2456 * @format: the format string
2457 * @...: printf-like arguments to @format
2459 * Equivalent to g_test_fail(), but also record a message like
2460 * g_test_skip_printf().
2465 g_test_fail_printf (const char *format,
2470 test_run_success = G_TEST_RUN_FAILURE;
2471 va_start (args, format);
2472 g_free (test_run_msg);
2473 test_run_msg = g_strdup_vprintf (format, args);
2478 * g_test_incomplete:
2479 * @msg: (nullable): explanation
2481 * Indicates that a test failed because of some incomplete
2482 * functionality. This function can be called multiple times
2483 * from the same test.
2485 * Calling this function will not stop the test from running, you
2486 * need to return from the test function yourself. So you can
2487 * produce additional diagnostic messages or even continue running
2490 * If not called from inside a test, this function does nothing.
2495 g_test_incomplete (const gchar *msg)
2497 test_run_success = G_TEST_RUN_INCOMPLETE;
2498 g_free (test_run_msg);
2499 test_run_msg = g_strdup (msg);
2503 * g_test_incomplete_printf:
2504 * @format: the format string
2505 * @...: printf-like arguments to @format
2507 * Equivalent to g_test_incomplete(), but the explanation is formatted
2508 * as if by g_strdup_printf().
2513 g_test_incomplete_printf (const char *format,
2518 test_run_success = G_TEST_RUN_INCOMPLETE;
2519 va_start (args, format);
2520 g_free (test_run_msg);
2521 test_run_msg = g_strdup_vprintf (format, args);
2527 * @msg: (nullable): explanation
2529 * Indicates that a test was skipped.
2531 * Calling this function will not stop the test from running, you
2532 * need to return from the test function yourself. So you can
2533 * produce additional diagnostic messages or even continue running
2536 * If not called from inside a test, this function does nothing.
2541 g_test_skip (const gchar *msg)
2543 test_run_success = G_TEST_RUN_SKIPPED;
2544 g_free (test_run_msg);
2545 test_run_msg = g_strdup (msg);
2549 * g_test_skip_printf:
2550 * @format: the format string
2551 * @...: printf-like arguments to @format
2553 * Equivalent to g_test_skip(), but the explanation is formatted
2554 * as if by g_strdup_printf().
2559 g_test_skip_printf (const char *format,
2564 test_run_success = G_TEST_RUN_SKIPPED;
2565 va_start (args, format);
2566 g_free (test_run_msg);
2567 test_run_msg = g_strdup_vprintf (format, args);
2574 * Returns whether a test has already failed. This will
2575 * be the case when g_test_fail(), g_test_incomplete()
2576 * or g_test_skip() have been called, but also if an
2577 * assertion has failed.
2579 * This can be useful to return early from a test if
2580 * continuing after a failed assertion might be harmful.
2582 * The return value of this function is only meaningful
2583 * if it is called from inside a test function.
2585 * Returns: %TRUE if the test has failed
2590 g_test_failed (void)
2592 return test_run_success != G_TEST_RUN_SUCCESS;
2596 * g_test_set_nonfatal_assertions:
2598 * Changes the behaviour of the various `g_assert_*()` macros,
2599 * g_test_assert_expected_messages() and the various
2600 * `g_test_trap_assert_*()` macros to not abort to program, but instead
2601 * call g_test_fail() and continue. (This also changes the behavior of
2602 * g_test_fail() so that it will not cause the test program to abort
2603 * after completing the failed test.)
2605 * Note that the g_assert_not_reached() and g_assert() macros are not
2608 * This function can only be called after g_test_init().
2613 g_test_set_nonfatal_assertions (void)
2615 if (!g_test_config_vars->test_initialized)
2616 g_error ("g_test_set_nonfatal_assertions called without g_test_init");
2617 test_nonfatal_assertions = TRUE;
2618 test_mode_fatal = FALSE;
2624 * The type used for test case functions.
2631 * @testpath: /-separated test case path name for the test.
2632 * @test_func: (scope async): The test function to invoke for this test.
2634 * Create a new test case, similar to g_test_create_case(). However
2635 * the test is assumed to use no fixture, and test suites are automatically
2636 * created on the fly and added to the root fixture, based on the
2637 * slash-separated portions of @testpath.
2639 * If @testpath includes the component "subprocess" anywhere in it,
2640 * the test will be skipped by default, and only run if explicitly
2641 * required via the `-p` command-line option or g_test_trap_subprocess().
2643 * No component of @testpath may start with a dot (`.`) if the
2644 * %G_TEST_OPTION_ISOLATE_DIRS option is being used; and it is recommended to
2645 * do so even if it isn’t.
2650 g_test_add_func (const char *testpath,
2651 GTestFunc test_func)
2653 g_return_if_fail (testpath != NULL);
2654 g_return_if_fail (testpath[0] == '/');
2655 g_return_if_fail (test_func != NULL);
2656 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
2661 * @user_data: the data provided when registering the test
2663 * The type used for test case functions that take an extra pointer
2670 * g_test_add_data_func:
2671 * @testpath: /-separated test case path name for the test.
2672 * @test_data: Test data argument for the test function.
2673 * @test_func: (scope async): The test function to invoke for this test.
2675 * Create a new test case, similar to g_test_create_case(). However
2676 * the test is assumed to use no fixture, and test suites are automatically
2677 * created on the fly and added to the root fixture, based on the
2678 * slash-separated portions of @testpath. The @test_data argument
2679 * will be passed as first argument to @test_func.
2681 * If @testpath includes the component "subprocess" anywhere in it,
2682 * the test will be skipped by default, and only run if explicitly
2683 * required via the `-p` command-line option or g_test_trap_subprocess().
2685 * No component of @testpath may start with a dot (`.`) if the
2686 * %G_TEST_OPTION_ISOLATE_DIRS option is being used; and it is recommended to
2687 * do so even if it isn’t.
2692 g_test_add_data_func (const char *testpath,
2693 gconstpointer test_data,
2694 GTestDataFunc test_func)
2696 g_return_if_fail (testpath != NULL);
2697 g_return_if_fail (testpath[0] == '/');
2698 g_return_if_fail (test_func != NULL);
2700 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
2704 * g_test_add_data_func_full:
2705 * @testpath: /-separated test case path name for the test.
2706 * @test_data: Test data argument for the test function.
2707 * @test_func: The test function to invoke for this test.
2708 * @data_free_func: #GDestroyNotify for @test_data.
2710 * Create a new test case, as with g_test_add_data_func(), but freeing
2711 * @test_data after the test run is complete.
2716 g_test_add_data_func_full (const char *testpath,
2718 GTestDataFunc test_func,
2719 GDestroyNotify data_free_func)
2721 g_return_if_fail (testpath != NULL);
2722 g_return_if_fail (testpath[0] == '/');
2723 g_return_if_fail (test_func != NULL);
2725 g_test_add_vtable (testpath, 0, test_data, NULL,
2726 (GTestFixtureFunc) test_func,
2727 (GTestFixtureFunc) data_free_func);
2731 g_test_suite_case_exists (GTestSuite *suite,
2732 const char *test_path)
2739 slash = strchr (test_path, '/');
2743 for (iter = suite->suites; iter; iter = iter->next)
2745 GTestSuite *child_suite = iter->data;
2747 if (!strncmp (child_suite->name, test_path, slash - test_path))
2748 if (g_test_suite_case_exists (child_suite, slash))
2754 for (iter = suite->cases; iter; iter = iter->next)
2757 if (!strcmp (tc->name, test_path))
2766 * g_test_create_suite:
2767 * @suite_name: a name for the suite
2769 * Create a new test suite with the name @suite_name.
2771 * Returns: A newly allocated #GTestSuite instance.
2776 g_test_create_suite (const char *suite_name)
2779 g_return_val_if_fail (suite_name != NULL, NULL);
2780 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
2781 g_return_val_if_fail (suite_name[0] != 0, NULL);
2782 ts = g_slice_new0 (GTestSuite);
2783 ts->name = g_strdup (suite_name);
2789 * @suite: a #GTestSuite
2790 * @test_case: a #GTestCase
2792 * Adds @test_case to @suite.
2797 g_test_suite_add (GTestSuite *suite,
2798 GTestCase *test_case)
2800 g_return_if_fail (suite != NULL);
2801 g_return_if_fail (test_case != NULL);
2803 suite->cases = g_slist_append (suite->cases, test_case);
2807 * g_test_suite_add_suite:
2808 * @suite: a #GTestSuite
2809 * @nestedsuite: another #GTestSuite
2811 * Adds @nestedsuite to @suite.
2816 g_test_suite_add_suite (GTestSuite *suite,
2817 GTestSuite *nestedsuite)
2819 g_return_if_fail (suite != NULL);
2820 g_return_if_fail (nestedsuite != NULL);
2822 suite->suites = g_slist_append (suite->suites, nestedsuite);
2826 * g_test_queue_free:
2827 * @gfree_pointer: the pointer to be stored.
2829 * Enqueue a pointer to be released with g_free() during the next
2830 * teardown phase. This is equivalent to calling g_test_queue_destroy()
2831 * with a destroy callback of g_free().
2836 g_test_queue_free (gpointer gfree_pointer)
2839 g_test_queue_destroy (g_free, gfree_pointer);
2843 * g_test_queue_destroy:
2844 * @destroy_func: Destroy callback for teardown phase.
2845 * @destroy_data: Destroy callback data.
2847 * This function enqueus a callback @destroy_func to be executed
2848 * during the next test case teardown phase. This is most useful
2849 * to auto destruct allocated test resources at the end of a test run.
2850 * Resources are released in reverse queue order, that means enqueueing
2851 * callback A before callback B will cause B() to be called before
2852 * A() during teardown.
2857 g_test_queue_destroy (GDestroyNotify destroy_func,
2858 gpointer destroy_data)
2860 DestroyEntry *dentry;
2862 g_return_if_fail (destroy_func != NULL);
2864 dentry = g_slice_new0 (DestroyEntry);
2865 dentry->destroy_func = destroy_func;
2866 dentry->destroy_data = destroy_data;
2867 dentry->next = test_destroy_queue;
2868 test_destroy_queue = dentry;
2872 test_has_prefix (gconstpointer a,
2875 const gchar *test_path_skipped_local = (const gchar *)a;
2876 const gchar* test_run_name_local = (const gchar*)b;
2877 if (test_prefix_extended_skipped)
2879 /* If both are null, we consider that it doesn't match */
2880 if (!test_path_skipped_local || !test_run_name_local)
2882 return strncmp (test_run_name_local, test_path_skipped_local, strlen (test_path_skipped_local));
2884 return g_strcmp0 (test_run_name_local, test_path_skipped_local);
2888 test_case_run (GTestCase *tc)
2890 gchar *old_base = g_strdup (test_uri_base);
2891 GSList **old_free_list, *filename_free_list = NULL;
2892 gboolean success = G_TEST_RUN_SUCCESS;
2894 old_free_list = test_filename_free_list;
2895 test_filename_free_list = &filename_free_list;
2897 if (++test_run_count <= test_startup_skip_count)
2898 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
2899 else if (test_run_list)
2901 g_print ("%s\n", test_run_name);
2902 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
2906 GTimer *test_run_timer = g_timer_new();
2907 long double largs[3];
2909 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
2911 test_run_success = G_TEST_RUN_SUCCESS;
2912 g_clear_pointer (&test_run_msg, g_free);
2913 g_test_log_set_fatal_handler (NULL, NULL);
2914 if (test_paths_skipped && g_slist_find_custom (test_paths_skipped, test_run_name, (GCompareFunc)test_has_prefix))
2915 g_test_skip ("by request (-s option)");
2918 GError *local_error = NULL;
2920 if (!test_do_isolate_dirs (&local_error))
2922 g_test_log (G_TEST_LOG_ERROR, local_error->message, NULL, 0, NULL);
2924 g_error_free (local_error);
2928 g_timer_start (test_run_timer);
2929 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
2930 test_run_seed (test_run_seedstr);
2931 if (tc->fixture_setup)
2932 tc->fixture_setup (fixture, tc->test_data);
2933 tc->fixture_test (fixture, tc->test_data);
2935 while (test_destroy_queue)
2937 DestroyEntry *dentry = test_destroy_queue;
2938 test_destroy_queue = dentry->next;
2939 dentry->destroy_func (dentry->destroy_data);
2940 g_slice_free (DestroyEntry, dentry);
2942 if (tc->fixture_teardown)
2943 tc->fixture_teardown (fixture, tc->test_data);
2944 if (tc->fixture_size)
2946 g_timer_stop (test_run_timer);
2949 test_rm_isolate_dirs ();
2951 success = test_run_success;
2952 test_run_success = G_TEST_RUN_FAILURE;
2953 largs[0] = success; /* OK */
2954 largs[1] = test_run_forks;
2955 largs[2] = g_timer_elapsed (test_run_timer, NULL);
2956 g_test_log (G_TEST_LOG_STOP_CASE, test_run_name, test_run_msg, G_N_ELEMENTS (largs), largs);
2957 g_clear_pointer (&test_run_msg, g_free);
2958 g_timer_destroy (test_run_timer);
2961 g_slist_free_full (filename_free_list, g_free);
2962 test_filename_free_list = old_free_list;
2963 g_free (test_uri_base);
2964 test_uri_base = old_base;
2966 return (success == G_TEST_RUN_SUCCESS ||
2967 success == G_TEST_RUN_SKIPPED ||
2968 success == G_TEST_RUN_INCOMPLETE);
2972 path_has_prefix (const char *path,
2975 int prefix_len = strlen (prefix);
2977 return (strncmp (path, prefix, prefix_len) == 0 &&
2978 (path[prefix_len] == '\0' ||
2979 path[prefix_len] == '/'));
2983 test_should_run (const char *test_path,
2984 const char *cmp_path)
2986 if (strstr (test_run_name, "/subprocess"))
2988 if (g_strcmp0 (test_path, cmp_path) == 0)
2991 if (g_test_verbose ())
2992 g_print ("GTest: skipping: %s\n", test_run_name);
2996 return !cmp_path || path_has_prefix (test_path, cmp_path);
2999 /* Recurse through @suite, running tests matching @path (or all tests
3000 * if @path is %NULL).
3003 g_test_run_suite_internal (GTestSuite *suite,
3007 gchar *old_name = test_run_name;
3010 g_return_val_if_fail (suite != NULL, -1);
3012 g_test_log (G_TEST_LOG_START_SUITE, suite->name, NULL, 0, NULL);
3014 for (iter = suite->cases; iter; iter = iter->next)
3016 GTestCase *tc = iter->data;
3018 test_run_name = g_build_path ("/", old_name, tc->name, NULL);
3019 if (test_should_run (test_run_name, path))
3021 if (!test_case_run (tc))
3024 g_free (test_run_name);
3027 for (iter = suite->suites; iter; iter = iter->next)
3029 GTestSuite *ts = iter->data;
3031 test_run_name = g_build_path ("/", old_name, ts->name, NULL);
3032 if (test_prefix_extended) {
3033 if (!path || path_has_prefix (test_run_name, path))
3034 n_bad += g_test_run_suite_internal (ts, test_run_name);
3035 else if (!path || path_has_prefix (path, test_run_name))
3036 n_bad += g_test_run_suite_internal (ts, path);
3037 } else if (!path || path_has_prefix (path, test_run_name)) {
3038 n_bad += g_test_run_suite_internal (ts, path);
3041 g_free (test_run_name);
3044 test_run_name = old_name;
3046 g_test_log (G_TEST_LOG_STOP_SUITE, suite->name, NULL, 0, NULL);
3052 g_test_suite_count (GTestSuite *suite)
3057 g_return_val_if_fail (suite != NULL, -1);
3059 for (iter = suite->cases; iter; iter = iter->next)
3061 GTestCase *tc = iter->data;
3063 if (strcmp (tc->name, "subprocess") != 0)
3067 for (iter = suite->suites; iter; iter = iter->next)
3069 GTestSuite *ts = iter->data;
3071 if (strcmp (ts->name, "subprocess") != 0)
3072 n += g_test_suite_count (ts);
3080 * @suite: a #GTestSuite
3082 * Execute the tests within @suite and all nested #GTestSuites.
3083 * The test suites to be executed are filtered according to
3084 * test path arguments (`-p testpath` and `-s testpath`) as parsed by
3085 * g_test_init(). See the g_test_run() documentation for more
3086 * information on the order that tests are run in.
3088 * g_test_run_suite() or g_test_run() may only be called once
3091 * Returns: 0 on success
3096 g_test_run_suite (GTestSuite *suite)
3100 g_return_val_if_fail (g_test_run_once == TRUE, -1);
3102 g_test_run_once = FALSE;
3103 test_count = g_test_suite_count (suite);
3105 test_run_name = g_strdup_printf ("/%s", suite->name);
3111 for (iter = test_paths; iter; iter = iter->next)
3112 n_bad += g_test_run_suite_internal (suite, iter->data);
3115 n_bad = g_test_run_suite_internal (suite, NULL);
3117 g_free (test_run_name);
3118 test_run_name = NULL;
3125 * @test_case: a #GTestCase
3127 * Free the @test_case.
3132 g_test_case_free (GTestCase *test_case)
3134 g_free (test_case->name);
3135 g_slice_free (GTestCase, test_case);
3139 * g_test_suite_free:
3140 * @suite: a #GTestSuite
3142 * Free the @suite and all nested #GTestSuites.
3147 g_test_suite_free (GTestSuite *suite)
3149 g_slist_free_full (suite->cases, (GDestroyNotify)g_test_case_free);
3151 g_free (suite->name);
3153 g_slist_free_full (suite->suites, (GDestroyNotify)g_test_suite_free);
3155 g_slice_free (GTestSuite, suite);
3159 gtest_default_log_handler (const gchar *log_domain,
3160 GLogLevelFlags log_level,
3161 const gchar *message,
3162 gpointer unused_data)
3164 const gchar *strv[16];
3165 gboolean fatal = FALSE;
3171 strv[i++] = log_domain;
3174 if (log_level & G_LOG_FLAG_FATAL)
3176 strv[i++] = "FATAL-";
3179 if (log_level & G_LOG_FLAG_RECURSION)
3180 strv[i++] = "RECURSIVE-";
3181 if (log_level & G_LOG_LEVEL_ERROR)
3182 strv[i++] = "ERROR";
3183 if (log_level & G_LOG_LEVEL_CRITICAL)
3184 strv[i++] = "CRITICAL";
3185 if (log_level & G_LOG_LEVEL_WARNING)
3186 strv[i++] = "WARNING";
3187 if (log_level & G_LOG_LEVEL_MESSAGE)
3188 strv[i++] = "MESSAGE";
3189 if (log_level & G_LOG_LEVEL_INFO)
3191 if (log_level & G_LOG_LEVEL_DEBUG)
3192 strv[i++] = "DEBUG";
3194 strv[i++] = message;
3197 msg = g_strjoinv ("", (gchar**) strv);
3198 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
3199 g_log_default_handler (log_domain, log_level, message, unused_data);
3205 g_assertion_message (const char *domain,
3209 const char *message)
3215 message = "code should not be reached";
3216 g_snprintf (lstr, 32, "%d", line);
3217 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
3218 "ERROR:", file, ":", lstr, ":",
3219 func, func[0] ? ":" : "",
3220 " ", message, NULL);
3221 g_printerr ("**\n%s\n", s);
3223 /* Don't print a fatal error indication if assertions are non-fatal, or
3224 * if we are a child process that might be sharing the parent's stdout. */
3225 if (test_nonfatal_assertions || test_in_subprocess || test_in_forked_child)
3226 g_test_log (G_TEST_LOG_MESSAGE, s, NULL, 0, NULL);
3228 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
3230 if (test_nonfatal_assertions)
3237 /* store assertion message in global variable, so that it can be found in a
3239 if (__glib_assert_msg != NULL)
3240 /* free the old one */
3241 free (__glib_assert_msg);
3242 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
3243 strcpy (__glib_assert_msg, s);
3247 if (test_in_subprocess)
3249 /* If this is a test case subprocess then it probably hit this
3250 * assertion on purpose, so just exit() rather than abort()ing,
3251 * to avoid triggering any system crash-reporting daemon.
3260 * g_assertion_message_expr: (skip)
3261 * @domain: (nullable): log domain
3262 * @file: file containing the assertion
3263 * @line: line number of the assertion
3264 * @func: function containing the assertion
3265 * @expr: (nullable): expression which failed
3267 * Internal function used to print messages from the public g_assert() and
3268 * g_assert_not_reached() macros.
3271 g_assertion_message_expr (const char *domain,
3279 s = g_strdup ("code should not be reached");
3281 s = g_strconcat ("assertion failed: (", expr, ")", NULL);
3282 g_assertion_message (domain, file, line, func, s);
3285 /* Normally g_assertion_message() won't return, but we need this for
3286 * when test_nonfatal_assertions is set, since
3287 * g_assertion_message_expr() is used for always-fatal assertions.
3289 if (test_in_subprocess)
3296 g_assertion_message_cmpnum (const char *domain,
3310 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;
3311 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;
3312 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr, (double) arg1, cmp, (double) arg2); break;
3313 /* ideally use: floats=%.7g double=%.17g */
3315 g_assertion_message (domain, file, line, func, s);
3320 g_assertion_message_cmpstr (const char *domain,
3329 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
3330 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
3331 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
3334 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
3337 g_assertion_message (domain, file, line, func, s);
3342 g_assertion_message_cmpstrv (const char *domain,
3347 const char * const *arg1,
3348 const char * const *arg2,
3349 gsize first_wrong_idx)
3351 const char *s1 = arg1[first_wrong_idx], *s2 = arg2[first_wrong_idx];
3352 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
3354 a1 = g_strconcat ("\"", t1 = g_strescape (s1, NULL), "\"", NULL);
3355 a2 = g_strconcat ("\"", t2 = g_strescape (s2, NULL), "\"", NULL);
3358 s = g_strdup_printf ("assertion failed (%s): first differing element at index %" G_GSIZE_FORMAT ": %s does not equal %s",
3359 expr, first_wrong_idx, a1, a2);
3362 g_assertion_message (domain, file, line, func, s);
3367 g_assertion_message_error (const char *domain,
3372 const GError *error,
3373 GQuark error_domain,
3378 /* This is used by both g_assert_error() and g_assert_no_error(), so there
3379 * are three cases: expected an error but got the wrong error, expected
3380 * an error but got no error, and expected no error but got an error.
3383 gstring = g_string_new ("assertion failed ");
3385 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
3386 g_quark_to_string (error_domain), error_code);
3388 g_string_append_printf (gstring, "(%s == NULL): ", expr);
3391 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
3392 g_quark_to_string (error->domain), error->code);
3394 g_string_append_printf (gstring, "%s is NULL", expr);
3396 g_assertion_message (domain, file, line, func, gstring->str);
3397 g_string_free (gstring, TRUE);
3402 * @str1: (nullable): a C string or %NULL
3403 * @str2: (nullable): another C string or %NULL
3405 * Compares @str1 and @str2 like strcmp(). Handles %NULL
3406 * gracefully by sorting it before non-%NULL strings.
3407 * Comparing two %NULL pointers returns 0.
3409 * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
3414 g_strcmp0 (const char *str1,
3418 return -(str1 != str2);
3420 return str1 != str2;
3421 return strcmp (str1, str2);
3425 test_trap_clear (void)
3427 test_trap_last_status = 0;
3428 test_trap_last_pid = 0;
3429 g_clear_pointer (&test_trap_last_subprocess, g_free);
3430 g_clear_pointer (&test_trap_last_stdout, g_free);
3431 g_clear_pointer (&test_trap_last_stderr, g_free);
3442 ret = dup2 (fd1, fd2);
3443 while (ret < 0 && errno == EINTR);
3452 int child_status; /* unmodified platform-specific status */
3454 GIOChannel *stdout_io;
3455 gboolean echo_stdout;
3456 GString *stdout_str;
3458 GIOChannel *stderr_io;
3459 gboolean echo_stderr;
3460 GString *stderr_str;
3464 check_complete (WaitForChildData *data)
3466 if (data->child_status != -1 && data->stdout_io == NULL && data->stderr_io == NULL)
3467 g_main_loop_quit (data->loop);
3471 child_exited (GPid pid,
3475 WaitForChildData *data = user_data;
3477 g_assert (status != -1);
3478 data->child_status = status;
3480 check_complete (data);
3484 child_timeout (gpointer user_data)
3486 WaitForChildData *data = user_data;
3489 TerminateProcess (data->pid, G_TEST_STATUS_TIMED_OUT);
3491 kill (data->pid, SIGALRM);
3498 child_read (GIOChannel *io, GIOCondition cond, gpointer user_data)
3500 WaitForChildData *data = user_data;
3502 gsize nread, nwrote, total;
3504 FILE *echo_file = NULL;
3506 status = g_io_channel_read_chars (io, buf, sizeof (buf), &nread, NULL);
3507 if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF)
3509 // FIXME data->error = (status == G_IO_STATUS_ERROR);
3510 if (io == data->stdout_io)
3511 g_clear_pointer (&data->stdout_io, g_io_channel_unref);
3513 g_clear_pointer (&data->stderr_io, g_io_channel_unref);
3515 check_complete (data);
3518 else if (status == G_IO_STATUS_AGAIN)
3521 if (io == data->stdout_io)
3523 g_string_append_len (data->stdout_str, buf, nread);
3524 if (data->echo_stdout)
3529 g_string_append_len (data->stderr_str, buf, nread);
3530 if (data->echo_stderr)
3536 for (total = 0; total < nread; total += nwrote)
3540 nwrote = fwrite (buf + total, 1, nread - total, echo_file);
3543 g_error ("write failed: %s", g_strerror (errsv));
3551 wait_for_child (GPid pid,
3552 int stdout_fd, gboolean echo_stdout,
3553 int stderr_fd, gboolean echo_stderr,
3556 WaitForChildData data;
3557 GMainContext *context;
3561 data.child_status = -1;
3563 context = g_main_context_new ();
3564 data.loop = g_main_loop_new (context, FALSE);
3566 source = g_child_watch_source_new (pid);
3567 g_source_set_callback (source, (GSourceFunc) child_exited, &data, NULL);
3568 g_source_attach (source, context);
3569 g_source_unref (source);
3571 data.echo_stdout = echo_stdout;
3572 data.stdout_str = g_string_new (NULL);
3573 data.stdout_io = g_io_channel_unix_new (stdout_fd);
3574 g_io_channel_set_close_on_unref (data.stdout_io, TRUE);
3575 g_io_channel_set_encoding (data.stdout_io, NULL, NULL);
3576 g_io_channel_set_buffered (data.stdout_io, FALSE);
3577 source = g_io_create_watch (data.stdout_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
3578 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
3579 g_source_attach (source, context);
3580 g_source_unref (source);
3582 data.echo_stderr = echo_stderr;
3583 data.stderr_str = g_string_new (NULL);
3584 data.stderr_io = g_io_channel_unix_new (stderr_fd);
3585 g_io_channel_set_close_on_unref (data.stderr_io, TRUE);
3586 g_io_channel_set_encoding (data.stderr_io, NULL, NULL);
3587 g_io_channel_set_buffered (data.stderr_io, FALSE);
3588 source = g_io_create_watch (data.stderr_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
3589 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
3590 g_source_attach (source, context);
3591 g_source_unref (source);
3595 source = g_timeout_source_new (0);
3596 g_source_set_ready_time (source, g_get_monotonic_time () + timeout);
3597 g_source_set_callback (source, (GSourceFunc) child_timeout, &data, NULL);
3598 g_source_attach (source, context);
3599 g_source_unref (source);
3602 g_main_loop_run (data.loop);
3603 g_main_loop_unref (data.loop);
3604 g_main_context_unref (context);
3606 test_trap_last_pid = pid;
3607 test_trap_last_status = data.child_status;
3608 test_trap_last_stdout = g_string_free (data.stdout_str, FALSE);
3609 test_trap_last_stderr = g_string_free (data.stderr_str, FALSE);
3611 g_clear_pointer (&data.stdout_io, g_io_channel_unref);
3612 g_clear_pointer (&data.stderr_io, g_io_channel_unref);
3617 * @usec_timeout: Timeout for the forked test in micro seconds.
3618 * @test_trap_flags: Flags to modify forking behaviour.
3620 * Fork the current test program to execute a test case that might
3621 * not return or that might abort.
3623 * If @usec_timeout is non-0, the forked test case is aborted and
3624 * considered failing if its run time exceeds it.
3626 * The forking behavior can be configured with the #GTestTrapFlags flags.
3628 * In the following example, the test code forks, the forked child
3629 * process produces some sample output and exits successfully.
3630 * The forking parent process then asserts successful child program
3631 * termination and validates child program outputs.
3633 * |[<!-- language="C" -->
3635 * test_fork_patterns (void)
3637 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
3639 * g_print ("some stdout text: somagic17\n");
3640 * g_printerr ("some stderr text: semagic43\n");
3641 * exit (0); // successful test run
3643 * g_test_trap_assert_passed ();
3644 * g_test_trap_assert_stdout ("*somagic17*");
3645 * g_test_trap_assert_stderr ("*semagic43*");
3649 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
3653 * Deprecated: This function is implemented only on Unix platforms,
3654 * and is not always reliable due to problems inherent in
3655 * fork-without-exec. Use g_test_trap_subprocess() instead.
3657 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
3659 g_test_trap_fork (guint64 usec_timeout,
3660 GTestTrapFlags test_trap_flags)
3663 int stdout_pipe[2] = { -1, -1 };
3664 int stderr_pipe[2] = { -1, -1 };
3668 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0)
3671 g_error ("failed to create pipes to fork test program: %s", g_strerror (errsv));
3673 test_trap_last_pid = fork ();
3675 if (test_trap_last_pid < 0)
3676 g_error ("failed to fork test program: %s", g_strerror (errsv));
3677 if (test_trap_last_pid == 0) /* child */
3680 test_in_forked_child = TRUE;
3681 close (stdout_pipe[0]);
3682 close (stderr_pipe[0]);
3683 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
3685 fd0 = g_open ("/dev/null", O_RDONLY, 0);
3687 g_error ("failed to open /dev/null for stdin redirection");
3689 if (safe_dup2 (stdout_pipe[1], 1) < 0 || safe_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && safe_dup2 (fd0, 0) < 0))
3692 g_error ("failed to dup2() in forked test program: %s", g_strerror (errsv));
3696 if (stdout_pipe[1] >= 3)
3697 close (stdout_pipe[1]);
3698 if (stderr_pipe[1] >= 3)
3699 close (stderr_pipe[1]);
3701 /* We typically expect these child processes to crash, and some
3702 * tests spawn a *lot* of them. Avoid spamming system crash
3703 * collection programs such as systemd-coredump and abrt.
3705 #ifdef HAVE_SYS_RESOURCE_H
3707 struct rlimit limit = { 0, 0 };
3708 (void) setrlimit (RLIMIT_CORE, &limit);
3717 close (stdout_pipe[1]);
3718 close (stderr_pipe[1]);
3720 wait_for_child (test_trap_last_pid,
3721 stdout_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT),
3722 stderr_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR),
3727 g_message ("Not implemented: g_test_trap_fork");
3732 G_GNUC_END_IGNORE_DEPRECATIONS
3735 * g_test_trap_subprocess:
3736 * @test_path: (nullable): Test to run in a subprocess
3737 * @usec_timeout: Timeout for the subprocess test in micro seconds.
3738 * @test_flags: Flags to modify subprocess behaviour.
3740 * Respawns the test program to run only @test_path in a subprocess.
3741 * This can be used for a test case that might not return, or that
3744 * If @test_path is %NULL then the same test is re-run in a subprocess.
3745 * You can use g_test_subprocess() to determine whether the test is in
3746 * a subprocess or not.
3748 * @test_path can also be the name of the parent test, followed by
3749 * "`/subprocess/`" and then a name for the specific subtest (or just
3750 * ending with "`/subprocess`" if the test only has one child test);
3751 * tests with names of this form will automatically be skipped in the
3754 * If @usec_timeout is non-0, the test subprocess is aborted and
3755 * considered failing if its run time exceeds it.
3757 * The subprocess behavior can be configured with the
3758 * #GTestSubprocessFlags flags.
3760 * You can use methods such as g_test_trap_assert_passed(),
3761 * g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to
3762 * check the results of the subprocess. (But note that
3763 * g_test_trap_assert_stdout() and g_test_trap_assert_stderr()
3764 * cannot be used if @test_flags specifies that the child should
3765 * inherit the parent stdout/stderr.)
3767 * If your `main ()` needs to behave differently in
3768 * the subprocess, you can call g_test_subprocess() (after calling
3769 * g_test_init()) to see whether you are in a subprocess.
3771 * The following example tests that calling
3772 * `my_object_new(1000000)` will abort with an error
3775 * |[<!-- language="C" -->
3777 * test_create_large_object (void)
3779 * if (g_test_subprocess ())
3781 * my_object_new (1000000);
3785 * // Reruns this same test in a subprocess
3786 * g_test_trap_subprocess (NULL, 0, G_TEST_SUBPROCESS_DEFAULT);
3787 * g_test_trap_assert_failed ();
3788 * g_test_trap_assert_stderr ("*ERROR*too large*");
3792 * main (int argc, char **argv)
3794 * g_test_init (&argc, &argv, NULL);
3796 * g_test_add_func ("/myobject/create_large_object",
3797 * test_create_large_object);
3798 * return g_test_run ();
3805 g_test_trap_subprocess (const char *test_path,
3806 guint64 usec_timeout,
3807 GTestSubprocessFlags test_flags)
3809 GError *error = NULL;
3812 int stdout_fd, stderr_fd;
3815 /* Sanity check that they used GTestSubprocessFlags, not GTestTrapFlags */
3816 g_assert ((test_flags & (G_TEST_TRAP_INHERIT_STDIN | G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR)) == 0);
3820 if (!g_test_suite_case_exists (g_test_get_root (), test_path))
3821 g_error ("g_test_trap_subprocess: test does not exist: %s", test_path);
3825 test_path = test_run_name;
3828 if (g_test_verbose ())
3829 g_print ("GTest: subprocess: %s\n", test_path);
3832 test_trap_last_subprocess = g_strdup (test_path);
3834 if (test_argv0 == NULL)
3835 g_error ("g_test_trap_subprocess() requires argv0 to be passed to g_test_init()");
3837 argv = g_ptr_array_new ();
3838 g_ptr_array_add (argv, (char *) test_argv0);
3839 g_ptr_array_add (argv, "-q");
3840 g_ptr_array_add (argv, "-p");
3841 g_ptr_array_add (argv, (char *)test_path);
3842 g_ptr_array_add (argv, "--GTestSubprocess");
3843 if (test_log_fd != -1)
3845 char log_fd_buf[128];
3847 g_ptr_array_add (argv, "--GTestLogFD");
3848 g_snprintf (log_fd_buf, sizeof (log_fd_buf), "%d", test_log_fd);
3849 g_ptr_array_add (argv, log_fd_buf);
3851 g_ptr_array_add (argv, NULL);
3853 flags = G_SPAWN_DO_NOT_REAP_CHILD;
3854 if (test_log_fd != -1)
3855 flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
3856 if (test_flags & G_TEST_TRAP_INHERIT_STDIN)
3857 flags |= G_SPAWN_CHILD_INHERITS_STDIN;
3859 if (!g_spawn_async_with_pipes (test_initial_cwd,
3860 (char **)argv->pdata,
3863 &pid, NULL, &stdout_fd, &stderr_fd,
3866 g_error ("g_test_trap_subprocess() failed: %s",
3869 g_ptr_array_free (argv, TRUE);
3871 wait_for_child (pid,
3872 stdout_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDOUT),
3873 stderr_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDERR),
3878 * g_test_subprocess:
3880 * Returns %TRUE (after g_test_init() has been called) if the test
3881 * program is running under g_test_trap_subprocess().
3883 * Returns: %TRUE if the test program is running under
3884 * g_test_trap_subprocess().
3889 g_test_subprocess (void)
3891 return test_in_subprocess;
3895 * g_test_trap_has_passed:
3897 * Check the result of the last g_test_trap_subprocess() call.
3899 * Returns: %TRUE if the last test subprocess terminated successfully.
3904 g_test_trap_has_passed (void)
3907 return (WIFEXITED (test_trap_last_status) &&
3908 WEXITSTATUS (test_trap_last_status) == 0);
3910 return test_trap_last_status == 0;
3915 * g_test_trap_reached_timeout:
3917 * Check the result of the last g_test_trap_subprocess() call.
3919 * Returns: %TRUE if the last test subprocess got killed due to a timeout.
3924 g_test_trap_reached_timeout (void)
3927 return (WIFSIGNALED (test_trap_last_status) &&
3928 WTERMSIG (test_trap_last_status) == SIGALRM);
3930 return test_trap_last_status == G_TEST_STATUS_TIMED_OUT;
3935 log_child_output (const gchar *process_id)
3940 if (WIFEXITED (test_trap_last_status)) /* normal exit */
3942 if (WEXITSTATUS (test_trap_last_status) == 0)
3943 g_test_message ("child process (%s) exit status: 0 (success)",
3946 g_test_message ("child process (%s) exit status: %d (error)",
3947 process_id, WEXITSTATUS (test_trap_last_status));
3949 else if (WIFSIGNALED (test_trap_last_status) &&
3950 WTERMSIG (test_trap_last_status) == SIGALRM)
3952 g_test_message ("child process (%s) timed out", process_id);
3954 else if (WIFSIGNALED (test_trap_last_status))
3956 const gchar *maybe_dumped_core = "";
3959 if (WCOREDUMP (test_trap_last_status))
3960 maybe_dumped_core = ", core dumped";
3963 g_test_message ("child process (%s) killed by signal %d (%s)%s",
3964 process_id, WTERMSIG (test_trap_last_status),
3965 g_strsignal (WTERMSIG (test_trap_last_status)),
3970 g_test_message ("child process (%s) unknown wait status %d",
3971 process_id, test_trap_last_status);
3974 if (test_trap_last_status == 0)
3975 g_test_message ("child process (%s) exit status: 0 (success)",
3978 g_test_message ("child process (%s) exit status: %d (error)",
3979 process_id, test_trap_last_status);
3982 escaped = g_strescape (test_trap_last_stdout, NULL);
3983 g_test_message ("child process (%s) stdout: \"%s\"", process_id, escaped);
3986 escaped = g_strescape (test_trap_last_stderr, NULL);
3987 g_test_message ("child process (%s) stderr: \"%s\"", process_id, escaped);
3990 /* so we can use short-circuiting:
3991 * logged_child_output = logged_child_output || log_child_output (...) */
3996 g_test_trap_assertions (const char *domain,
4000 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
4001 const char *pattern)
4003 gboolean must_pass = assertion_flags == 0;
4004 gboolean must_fail = assertion_flags == 1;
4005 gboolean match_result = 0 == (assertion_flags & 1);
4006 gboolean logged_child_output = FALSE;
4007 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
4008 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
4009 const char *match_error = match_result ? "failed to match" : "contains invalid match";
4013 if (test_trap_last_subprocess != NULL)
4015 process_id = g_strdup_printf ("%s [%d]", test_trap_last_subprocess,
4016 test_trap_last_pid);
4018 else if (test_trap_last_pid != 0)
4019 process_id = g_strdup_printf ("%d", test_trap_last_pid);
4021 if (test_trap_last_subprocess != NULL)
4022 process_id = g_strdup (test_trap_last_subprocess);
4025 g_error ("g_test_trap_ assertion with no trapped test");
4027 if (must_pass && !g_test_trap_has_passed())
4031 logged_child_output = logged_child_output || log_child_output (process_id);
4033 msg = g_strdup_printf ("child process (%s) failed unexpectedly", process_id);
4034 g_assertion_message (domain, file, line, func, msg);
4037 if (must_fail && g_test_trap_has_passed())
4041 logged_child_output = logged_child_output || log_child_output (process_id);
4043 msg = g_strdup_printf ("child process (%s) did not fail as expected", process_id);
4044 g_assertion_message (domain, file, line, func, msg);
4047 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
4051 logged_child_output = logged_child_output || log_child_output (process_id);
4053 msg = g_strdup_printf ("stdout of child process (%s) %s: %s\nstdout was:\n%s",
4054 process_id, match_error, stdout_pattern, test_trap_last_stdout);
4055 g_assertion_message (domain, file, line, func, msg);
4058 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
4062 logged_child_output = logged_child_output || log_child_output (process_id);
4064 msg = g_strdup_printf ("stderr of child process (%s) %s: %s\nstderr was:\n%s",
4065 process_id, match_error, stderr_pattern, test_trap_last_stderr);
4066 g_assertion_message (domain, file, line, func, msg);
4070 (void) logged_child_output; /* shut up scan-build about the final unread assignment */
4072 g_free (process_id);
4076 gstring_overwrite_int (GString *gstring,
4080 vuint = g_htonl (vuint);
4081 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
4085 gstring_append_int (GString *gstring,
4088 vuint = g_htonl (vuint);
4089 g_string_append_len (gstring, (const gchar*) &vuint, 4);
4093 gstring_append_double (GString *gstring,
4096 union { double vdouble; guint64 vuint64; } u;
4097 u.vdouble = vdouble;
4098 u.vuint64 = GUINT64_TO_BE (u.vuint64);
4099 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
4103 g_test_log_dump (GTestLogMsg *msg,
4106 GString *gstring = g_string_sized_new (1024);
4108 gstring_append_int (gstring, 0); /* message length */
4109 gstring_append_int (gstring, msg->log_type);
4110 gstring_append_int (gstring, msg->n_strings);
4111 gstring_append_int (gstring, msg->n_nums);
4112 gstring_append_int (gstring, 0); /* reserved */
4113 for (ui = 0; ui < msg->n_strings; ui++)
4115 guint l = strlen (msg->strings[ui]);
4116 gstring_append_int (gstring, l);
4117 g_string_append_len (gstring, msg->strings[ui], l);
4119 for (ui = 0; ui < msg->n_nums; ui++)
4120 gstring_append_double (gstring, msg->nums[ui]);
4121 *len = gstring->len;
4122 gstring_overwrite_int (gstring, 0, *len); /* message length */
4123 return (guint8*) g_string_free (gstring, FALSE);
4126 static inline long double
4127 net_double (const gchar **ipointer)
4129 union { guint64 vuint64; double vdouble; } u;
4130 guint64 aligned_int64;
4131 memcpy (&aligned_int64, *ipointer, 8);
4133 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
4137 static inline guint32
4138 net_int (const gchar **ipointer)
4140 guint32 aligned_int;
4141 memcpy (&aligned_int, *ipointer, 4);
4143 return g_ntohl (aligned_int);
4147 g_test_log_extract (GTestLogBuffer *tbuffer)
4149 const gchar *p = tbuffer->data->str;
4152 if (tbuffer->data->len < 4 * 5)
4154 mlength = net_int (&p);
4155 if (tbuffer->data->len < mlength)
4157 msg.log_type = net_int (&p);
4158 msg.n_strings = net_int (&p);
4159 msg.n_nums = net_int (&p);
4160 if (net_int (&p) == 0)
4163 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
4164 msg.nums = g_new0 (long double, msg.n_nums);
4165 for (ui = 0; ui < msg.n_strings; ui++)
4167 guint sl = net_int (&p);
4168 msg.strings[ui] = g_strndup (p, sl);
4171 for (ui = 0; ui < msg.n_nums; ui++)
4172 msg.nums[ui] = net_double (&p);
4173 if (p <= tbuffer->data->str + mlength)
4175 g_string_erase (tbuffer->data, 0, mlength);
4176 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup2 (&msg, sizeof (msg)));
4181 g_strfreev (msg.strings);
4184 g_error ("corrupt log stream from test program");
4189 * g_test_log_buffer_new:
4191 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
4194 g_test_log_buffer_new (void)
4196 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
4197 tb->data = g_string_sized_new (1024);
4202 * g_test_log_buffer_free:
4204 * Internal function for gtester to free test log messages, no ABI guarantees provided.
4207 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
4209 g_return_if_fail (tbuffer != NULL);
4210 while (tbuffer->msgs)
4211 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
4212 g_string_free (tbuffer->data, TRUE);
4217 * g_test_log_buffer_push:
4219 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
4222 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
4224 const guint8 *bytes)
4226 g_return_if_fail (tbuffer != NULL);
4229 gboolean more_messages;
4230 g_return_if_fail (bytes != NULL);
4231 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
4233 more_messages = g_test_log_extract (tbuffer);
4234 while (more_messages);
4239 * g_test_log_buffer_pop:
4241 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
4244 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
4246 GTestLogMsg *msg = NULL;
4247 g_return_val_if_fail (tbuffer != NULL, NULL);
4250 GSList *slist = g_slist_last (tbuffer->msgs);
4252 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
4258 * g_test_log_msg_free:
4260 * Internal function for gtester to free test log messages, no ABI guarantees provided.
4263 g_test_log_msg_free (GTestLogMsg *tmsg)
4265 g_return_if_fail (tmsg != NULL);
4266 g_strfreev (tmsg->strings);
4267 g_free (tmsg->nums);
4272 g_test_build_filename_va (GTestFileType file_type,
4273 const gchar *first_path,
4276 const gchar *pathv[16];
4277 gsize num_path_segments;
4279 if (file_type == G_TEST_DIST)
4280 pathv[0] = test_disted_files_dir;
4281 else if (file_type == G_TEST_BUILT)
4282 pathv[0] = test_built_files_dir;
4284 g_assert_not_reached ();
4286 pathv[1] = first_path;
4288 for (num_path_segments = 2; num_path_segments < G_N_ELEMENTS (pathv); num_path_segments++)
4290 pathv[num_path_segments] = va_arg (ap, const char *);
4291 if (pathv[num_path_segments] == NULL)
4295 g_assert_cmpint (num_path_segments, <, G_N_ELEMENTS (pathv));
4297 return g_build_filenamev ((gchar **) pathv);
4301 * g_test_build_filename:
4302 * @file_type: the type of file (built vs. distributed)
4303 * @first_path: the first segment of the pathname
4304 * @...: %NULL-terminated additional path segments
4306 * Creates the pathname to a data file that is required for a test.
4308 * This function is conceptually similar to g_build_filename() except
4309 * that the first argument has been replaced with a #GTestFileType
4312 * The data file should either have been distributed with the module
4313 * containing the test (%G_TEST_DIST) or built as part of the build
4314 * system of that module (%G_TEST_BUILT).
4316 * In order for this function to work in srcdir != builddir situations,
4317 * the G_TEST_SRCDIR and G_TEST_BUILDDIR environment variables need to
4318 * have been defined. As of 2.38, this is done by the glib.mk
4319 * included in GLib. Please ensure that your copy is up to date before
4320 * using this function.
4322 * In case neither variable is set, this function will fall back to
4323 * using the dirname portion of argv[0], possibly removing ".libs".
4324 * This allows for casual running of tests directly from the commandline
4325 * in the srcdir == builddir case and should also support running of
4326 * installed tests, assuming the data files have been installed in the
4327 * same relative path as the test binary.
4329 * Returns: the path of the file, to be freed using g_free()
4335 * @G_TEST_DIST: a file that was included in the distribution tarball
4336 * @G_TEST_BUILT: a file that was built on the compiling machine
4338 * The type of file to return the filename for, when used with
4339 * g_test_build_filename().
4341 * These two options correspond rather directly to the 'dist' and
4342 * 'built' terminology that automake uses and are explicitly used to
4343 * distinguish between the 'srcdir' and 'builddir' being separate. All
4344 * files in your project should either be dist (in the
4345 * `EXTRA_DIST` or `dist_schema_DATA`
4346 * sense, in which case they will always be in the srcdir) or built (in
4347 * the `BUILT_SOURCES` sense, in which case they will
4348 * always be in the builddir).
4350 * Note: as a general rule of automake, files that are generated only as
4351 * part of the build-from-git process (but then are distributed with the
4352 * tarball) always go in srcdir (even if doing a srcdir != builddir
4353 * build from git) and are considered as distributed files.
4358 g_test_build_filename (GTestFileType file_type,
4359 const gchar *first_path,
4365 g_assert (g_test_initialized ());
4367 va_start (ap, first_path);
4368 result = g_test_build_filename_va (file_type, first_path, ap);
4376 * @file_type: the type of file (built vs. distributed)
4378 * Gets the pathname of the directory containing test files of the type
4379 * specified by @file_type.
4381 * This is approximately the same as calling g_test_build_filename("."),
4382 * but you don't need to free the return value.
4384 * Returns: (type filename): the path of the directory, owned by GLib
4389 g_test_get_dir (GTestFileType file_type)
4391 g_assert (g_test_initialized ());
4393 if (file_type == G_TEST_DIST)
4394 return test_disted_files_dir;
4395 else if (file_type == G_TEST_BUILT)
4396 return test_built_files_dir;
4398 g_assert_not_reached ();
4402 * g_test_get_filename:
4403 * @file_type: the type of file (built vs. distributed)
4404 * @first_path: the first segment of the pathname
4405 * @...: %NULL-terminated additional path segments
4407 * Gets the pathname to a data file that is required for a test.
4409 * This is the same as g_test_build_filename() with two differences.
4410 * The first difference is that you must only use this function from within
4411 * a testcase function. The second difference is that you need not free
4412 * the return value — it will be automatically freed when the testcase
4415 * It is safe to use this function from a thread inside of a testcase
4416 * but you must ensure that all such uses occur before the main testcase
4417 * function returns (ie: it is best to ensure that all threads have been
4420 * Returns: the path, automatically freed at the end of the testcase
4425 g_test_get_filename (GTestFileType file_type,
4426 const gchar *first_path,
4433 g_assert (g_test_initialized ());
4434 if (test_filename_free_list == NULL)
4435 g_error ("g_test_get_filename() can only be used within testcase functions");
4437 va_start (ap, first_path);
4438 result = g_test_build_filename_va (file_type, first_path, ap);
4441 node = g_slist_prepend (NULL, result);
4443 node->next = *test_filename_free_list;
4444 while (!g_atomic_pointer_compare_and_exchange (test_filename_free_list, node->next, node));
4452 * Gets the test path for the test currently being run.
4454 * In essence, it will be the same string passed as the first argument to
4455 * e.g. g_test_add() when the test was added.
4457 * This function returns a valid string only within a test function.
4459 * Returns: the test path for the test currently being run
4464 g_test_get_path (void)
4466 return test_run_name;