1 /* GLib testing utilities
2 * Copyright (C) 2007 Imendio AB
3 * Authors: Tim Janik, Sven Herzberg
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 #include "gtestutils.h"
22 #include "gfileutils.h"
24 #include <sys/types.h>
34 #ifdef HAVE_SYS_RESOURCE_H
35 #include <sys/resource.h>
43 #ifdef HAVE_SYS_SELECT_H
44 #include <sys/select.h>
45 #endif /* HAVE_SYS_SELECT_H */
46 #include <glib/gstdio.h>
51 #include "gstrfuncs.h"
52 #include "gstrfuncsprivate.h"
56 #include "glib-private.h"
57 #include "gutilsprivate.h"
63 * @short_description: a test framework
65 * GLib provides a framework for writing and maintaining unit tests
66 * in parallel to the code they are testing. The API is designed according
67 * to established concepts found in the other test frameworks (JUnit, NUnit,
68 * RUnit), which in turn is based on smalltalk unit testing concepts.
70 * - Test case: Tests (test methods) are grouped together with their
71 * fixture into test cases.
73 * - Fixture: A test fixture consists of fixture data and setup and
74 * teardown methods to establish the environment for the test
75 * functions. We use fresh fixtures, i.e. fixtures are newly set
76 * up and torn down around each test invocation to avoid dependencies
79 * - Test suite: Test cases can be grouped into test suites, to allow
80 * subsets of the available tests to be run. Test suites can be
81 * grouped into other test suites as well.
83 * The API is designed to handle creation and registration of test suites
84 * and test cases implicitly. A simple call like
85 * |[<!-- language="C" -->
86 * g_test_add_func ("/misc/assertions", test_assertions);
88 * creates a test suite called "misc" with a single test case named
89 * "assertions", which consists of running the test_assertions function.
91 * In addition to the traditional g_assert_true(), the test framework provides
92 * an extended set of assertions for comparisons: g_assert_cmpfloat(),
93 * g_assert_cmpfloat_with_epsilon(), g_assert_cmpint(), g_assert_cmpuint(),
94 * g_assert_cmphex(), g_assert_cmpstr(), g_assert_cmpmem() and
95 * g_assert_cmpvariant(). The
96 * advantage of these variants over plain g_assert_true() is that the assertion
97 * messages can be more elaborate, and include the values of the compared
100 * Note that g_assert() should not be used in unit tests, since it is a no-op
101 * when compiling with `G_DISABLE_ASSERT`. Use g_assert() in production code,
102 * and g_assert_true() in unit tests.
104 * A full example of creating a test suite with two tests using fixtures:
105 * |[<!-- language="C" -->
107 * #include <locale.h>
111 * OtherObject *helper;
115 * my_object_fixture_set_up (MyObjectFixture *fixture,
116 * gconstpointer user_data)
118 * fixture->obj = my_object_new ();
119 * my_object_set_prop1 (fixture->obj, "some-value");
120 * my_object_do_some_complex_setup (fixture->obj, user_data);
122 * fixture->helper = other_object_new ();
126 * my_object_fixture_tear_down (MyObjectFixture *fixture,
127 * gconstpointer user_data)
129 * g_clear_object (&fixture->helper);
130 * g_clear_object (&fixture->obj);
134 * test_my_object_test1 (MyObjectFixture *fixture,
135 * gconstpointer user_data)
137 * g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "initial-value");
141 * test_my_object_test2 (MyObjectFixture *fixture,
142 * gconstpointer user_data)
144 * my_object_do_some_work_using_helper (fixture->obj, fixture->helper);
145 * g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "updated-value");
149 * main (int argc, char *argv[])
151 * setlocale (LC_ALL, "");
153 * g_test_init (&argc, &argv, NULL);
155 * // Define the tests.
156 * g_test_add ("/my-object/test1", MyObjectFixture, "some-user-data",
157 * my_object_fixture_set_up, test_my_object_test1,
158 * my_object_fixture_tear_down);
159 * g_test_add ("/my-object/test2", MyObjectFixture, "some-user-data",
160 * my_object_fixture_set_up, test_my_object_test2,
161 * my_object_fixture_tear_down);
163 * return g_test_run ();
167 * ### Integrating GTest in your project
169 * If you are using the [Meson](http://mesonbuild.com) build system, you will
170 * typically use the provided `test()` primitive to call the test binaries,
173 * |[<!-- language="plain" -->
176 * executable('foo', 'foo.c', dependencies: deps),
178 * 'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
179 * 'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
185 * executable('bar', 'bar.c', dependencies: deps),
187 * 'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
188 * 'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
193 * If you are using Autotools, you're strongly encouraged to use the Automake
194 * [TAP](https://testanything.org/) harness; GLib provides template files for
195 * easily integrating with it:
197 * - [glib-tap.mk](https://gitlab.gnome.org/GNOME/glib/blob/glib-2-58/glib-tap.mk)
198 * - [tap-test](https://gitlab.gnome.org/GNOME/glib/blob/glib-2-58/tap-test)
199 * - [tap-driver.sh](https://gitlab.gnome.org/GNOME/glib/blob/glib-2-58/tap-driver.sh)
201 * You can copy these files in your own project's root directory, and then
202 * set up your `Makefile.am` file to reference them, for instance:
204 * |[<!-- language="plain" -->
205 * include $(top_srcdir)/glib-tap.mk
212 * # data distributed in the tarball
217 * # data not distributed in the tarball
222 * Make sure to distribute the TAP files, using something like the following
223 * in your top-level `Makefile.am`:
225 * |[<!-- language="plain" -->
231 * `glib-tap.mk` will be distributed implicitly due to being included in a
232 * `Makefile.am`. All three files should be added to version control.
234 * If you don't have access to the Autotools TAP harness, you can use the
235 * [gtester][gtester] and [gtester-report][gtester-report] tools, and use
236 * the [glib.mk](https://gitlab.gnome.org/GNOME/glib/blob/glib-2-58/glib.mk)
237 * Automake template provided by GLib. Note, however, that since GLib 2.62,
238 * [gtester][gtester] and [gtester-report][gtester-report] have been deprecated
239 * in favour of using TAP. The `--tap` argument to tests is enabled by default
244 * g_test_initialized:
246 * Returns %TRUE if g_test_init() has been called.
248 * Returns: %TRUE if g_test_init() has been called.
256 * Returns %TRUE if tests are run in quick mode.
257 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
258 * there is no "medium speed".
260 * By default, tests are run in quick mode. In tests that use
261 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
262 * can be used to change this.
264 * Returns: %TRUE if in quick mode
270 * Returns %TRUE if tests are run in slow mode.
271 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
272 * there is no "medium speed".
274 * By default, tests are run in quick mode. In tests that use
275 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
276 * can be used to change this.
278 * Returns: the opposite of g_test_quick()
284 * Returns %TRUE if tests are run in thorough mode, equivalent to
287 * By default, tests are run in quick mode. In tests that use
288 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
289 * can be used to change this.
291 * Returns: the same thing as g_test_slow()
297 * Returns %TRUE if tests are run in performance mode.
299 * By default, tests are run in quick mode. In tests that use
300 * g_test_init(), the option `-m perf` enables performance tests, while
301 * `-m quick` disables them.
303 * Returns: %TRUE if in performance mode
309 * Returns %TRUE if tests may provoke assertions and other formally-undefined
310 * behaviour, to verify that appropriate warnings are given. It might, in some
311 * cases, be useful to turn this off with if running tests under valgrind;
312 * in tests that use g_test_init(), the option `-m no-undefined` disables
313 * those tests, while `-m undefined` explicitly enables them (the default
316 * Returns: %TRUE if tests may provoke programming errors
322 * Returns %TRUE if tests are run in verbose mode.
323 * In tests that use g_test_init(), the option `--verbose` enables this,
324 * while `-q` or `--quiet` disables it.
325 * The default is neither g_test_verbose() nor g_test_quiet().
327 * Returns: %TRUE if in verbose mode
333 * Returns %TRUE if tests are run in quiet mode.
334 * In tests that use g_test_init(), the option `-q` or `--quiet` enables
335 * this, while `--verbose` disables it.
336 * The default is neither g_test_verbose() nor g_test_quiet().
338 * Returns: %TRUE if in quiet mode
342 * g_test_queue_unref:
343 * @gobject: the object to unref
345 * Enqueue an object to be released with g_object_unref() during
346 * the next teardown phase. This is equivalent to calling
347 * g_test_queue_destroy() with a destroy callback of g_object_unref().
353 * GTestSubprocessFlags:
354 * @G_TEST_SUBPROCESS_INHERIT_STDIN: If this flag is given, the child
355 * process will inherit the parent's stdin. Otherwise, the child's
356 * stdin is redirected to `/dev/null`.
357 * @G_TEST_SUBPROCESS_INHERIT_STDOUT: If this flag is given, the child
358 * process will inherit the parent's stdout. Otherwise, the child's
359 * stdout will not be visible, but it will be captured to allow
360 * later tests with g_test_trap_assert_stdout().
361 * @G_TEST_SUBPROCESS_INHERIT_STDERR: If this flag is given, the child
362 * process will inherit the parent's stderr. Otherwise, the child's
363 * stderr will not be visible, but it will be captured to allow
364 * later tests with g_test_trap_assert_stderr().
366 * Flags to pass to g_test_trap_subprocess() to control input and output.
368 * Note that in contrast with g_test_trap_fork(), the default is to
369 * not show stdout and stderr.
373 * g_test_trap_assert_passed:
375 * Assert that the last test subprocess passed.
376 * See g_test_trap_subprocess().
382 * g_test_trap_assert_failed:
384 * Assert that the last test subprocess failed.
385 * See g_test_trap_subprocess().
387 * This is sometimes used to test situations that are formally considered to
388 * be undefined behaviour, like inputs that fail a g_return_if_fail()
389 * check. In these situations you should skip the entire test, including the
390 * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
391 * to indicate that undefined behaviour may be tested.
397 * g_test_trap_assert_stdout:
398 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
400 * Assert that the stdout output of the last test subprocess matches
401 * @soutpattern. See g_test_trap_subprocess().
407 * g_test_trap_assert_stdout_unmatched:
408 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
410 * Assert that the stdout output of the last test subprocess
411 * does not match @soutpattern. See g_test_trap_subprocess().
417 * g_test_trap_assert_stderr:
418 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
420 * Assert that the stderr output of the last test subprocess
421 * matches @serrpattern. See g_test_trap_subprocess().
423 * This is sometimes used to test situations that are formally
424 * considered to be undefined behaviour, like code that hits a
425 * g_assert() or g_error(). In these situations you should skip the
426 * entire test, including the call to g_test_trap_subprocess(), unless
427 * g_test_undefined() returns %TRUE to indicate that undefined
428 * behaviour may be tested.
434 * g_test_trap_assert_stderr_unmatched:
435 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
437 * Assert that the stderr output of the last test subprocess
438 * does not match @serrpattern. See g_test_trap_subprocess().
446 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
447 * for details on test case random numbers.
454 * @expr: the expression to check
456 * Debugging macro to terminate the application if the assertion
457 * fails. If the assertion fails (i.e. the expression is not true),
458 * an error message is logged and the application is terminated.
460 * The macro can be turned off in final releases of code by defining
461 * `G_DISABLE_ASSERT` when compiling the application, so code must
462 * not depend on any side effects from @expr. Similarly, it must not be used
463 * in unit tests, otherwise the unit tests will be ineffective if compiled with
464 * `G_DISABLE_ASSERT`. Use g_assert_true() and related macros in unit tests
469 * g_assert_not_reached:
471 * Debugging macro to terminate the application if it is ever
472 * reached. If it is reached, an error message is logged and the
473 * application is terminated.
475 * The macro can be turned off in final releases of code by defining
476 * `G_DISABLE_ASSERT` when compiling the application. Hence, it should not be
477 * used in unit tests, where assertions should always be effective.
482 * @expr: the expression to check
484 * Debugging macro to check that an expression is true.
486 * If the assertion fails (i.e. the expression is not true),
487 * an error message is logged and the application is either
488 * terminated or the testcase marked as failed.
490 * Note that unlike g_assert(), this macro is unaffected by whether
491 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
492 * conversely, g_assert() should not be used in tests.
494 * See g_test_set_nonfatal_assertions().
501 * @expr: the expression to check
503 * Debugging macro to check an expression is false.
505 * If the assertion fails (i.e. the expression is not false),
506 * an error message is logged and the application is either
507 * terminated or the testcase marked as failed.
509 * Note that unlike g_assert(), this macro is unaffected by whether
510 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
511 * conversely, g_assert() should not be used in tests.
513 * See g_test_set_nonfatal_assertions().
520 * @expr: the expression to check
522 * Debugging macro to check an expression is %NULL.
524 * If the assertion fails (i.e. the expression is not %NULL),
525 * an error message is logged and the application is either
526 * terminated or the testcase marked as failed.
528 * Note that unlike g_assert(), this macro is unaffected by whether
529 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
530 * conversely, g_assert() should not be used in tests.
532 * See g_test_set_nonfatal_assertions().
539 * @expr: the expression to check
541 * Debugging macro to check an expression is not %NULL.
543 * If the assertion fails (i.e. the expression is %NULL),
544 * an error message is logged and the application is either
545 * terminated or the testcase marked as failed.
547 * Note that unlike g_assert(), this macro is unaffected by whether
548 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
549 * conversely, g_assert() should not be used in tests.
551 * See g_test_set_nonfatal_assertions().
558 * @s1: a string (may be %NULL)
559 * @cmp: The comparison operator to use.
560 * One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
561 * @s2: another string (may be %NULL)
563 * Debugging macro to compare two strings. If the comparison fails,
564 * an error message is logged and the application is either terminated
565 * or the testcase marked as failed.
566 * The strings are compared using g_strcmp0().
568 * The effect of `g_assert_cmpstr (s1, op, s2)` is
569 * the same as `g_assert_true (g_strcmp0 (s1, s2) op 0)`.
570 * The advantage of this macro is that it can produce a message that
571 * includes the actual values of @s1 and @s2.
573 * |[<!-- language="C" -->
574 * g_assert_cmpstr (mystring, ==, "fubar");
583 * @cmp: The comparison operator to use.
584 * One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
585 * @n2: another integer
587 * Debugging macro to compare two integers.
589 * The effect of `g_assert_cmpint (n1, op, n2)` is
590 * the same as `g_assert_true (n1 op n2)`. The advantage
591 * of this macro is that it can produce a message that includes the
592 * actual values of @n1 and @n2.
599 * @n1: an unsigned integer
600 * @cmp: The comparison operator to use.
601 * One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
602 * @n2: another unsigned integer
604 * Debugging macro to compare two unsigned integers.
606 * The effect of `g_assert_cmpuint (n1, op, n2)` is
607 * the same as `g_assert_true (n1 op n2)`. The advantage
608 * of this macro is that it can produce a message that includes the
609 * actual values of @n1 and @n2.
616 * @n1: an unsigned integer
617 * @cmp: The comparison operator to use.
618 * One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
619 * @n2: another unsigned integer
621 * Debugging macro to compare to unsigned integers.
623 * This is a variant of g_assert_cmpuint() that displays the numbers
624 * in hexadecimal notation in the message.
631 * @n1: a floating point number
632 * @cmp: The comparison operator to use.
633 * One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
634 * @n2: another floating point number
636 * Debugging macro to compare two floating point numbers.
638 * The effect of `g_assert_cmpfloat (n1, op, n2)` is
639 * the same as `g_assert_true (n1 op n2)`. The advantage
640 * of this macro is that it can produce a message that includes the
641 * actual values of @n1 and @n2.
647 * g_assert_cmpfloat_with_epsilon:
648 * @n1: a floating point number
649 * @n2: another floating point number
650 * @epsilon: a numeric value that expresses the expected tolerance
651 * between @n1 and @n2
653 * Debugging macro to compare two floating point numbers within an epsilon.
655 * The effect of `g_assert_cmpfloat_with_epsilon (n1, n2, epsilon)` is
656 * the same as `g_assert_true (abs (n1 - n2) < epsilon)`. The advantage
657 * of this macro is that it can produce a message that includes the
658 * actual values of @n1 and @n2.
665 * @expr: the expression to check
667 * Debugging macro to check that an expression has a non-negative return value,
668 * as used by traditional POSIX functions (such as `rmdir()`) to indicate
671 * If the assertion fails (i.e. the @expr returns a negative value), an error
672 * message is logged and the testcase is marked as failed. The error message
673 * will contain the value of `errno` and its human-readable message from
676 * This macro will clear the value of `errno` before executing @expr.
683 * @m1: (nullable): pointer to a buffer
685 * @m2: (nullable): pointer to another buffer
688 * Debugging macro to compare memory regions. If the comparison fails,
689 * an error message is logged and the application is either terminated
690 * or the testcase marked as failed.
692 * The effect of `g_assert_cmpmem (m1, l1, m2, l2)` is
693 * the same as `g_assert_true (l1 == l2 && memcmp (m1, m2, l1) == 0)`.
694 * The advantage of this macro is that it can produce a message that
695 * includes the actual values of @l1 and @l2.
697 * @m1 may be %NULL if (and only if) @l1 is zero; similarly for @m2 and @l2.
699 * |[<!-- language="C" -->
700 * g_assert_cmpmem (buf->data, buf->len, expected, sizeof (expected));
707 * g_assert_cmpvariant:
708 * @v1: pointer to a #GVariant
709 * @v2: pointer to another #GVariant
711 * Debugging macro to compare two #GVariants. If the comparison fails,
712 * an error message is logged and the application is either terminated
713 * or the testcase marked as failed. The variants are compared using
716 * The effect of `g_assert_cmpvariant (v1, v2)` is the same as
717 * `g_assert_true (g_variant_equal (v1, v2))`. The advantage of this macro is
718 * that it can produce a message that includes the actual values of @v1 and @v2.
725 * @err: a #GError, possibly %NULL
727 * Debugging macro to check that a #GError is not set.
729 * The effect of `g_assert_no_error (err)` is
730 * the same as `g_assert_true (err == NULL)`. The advantage
731 * of this macro is that it can produce a message that includes
732 * the error message and code.
739 * @err: a #GError, possibly %NULL
740 * @dom: the expected error domain (a #GQuark)
741 * @c: the expected error code
743 * Debugging macro to check that a method has returned
744 * the correct #GError.
746 * The effect of `g_assert_error (err, dom, c)` is
747 * the same as `g_assert_true (err != NULL && err->domain
748 * == dom && err->code == c)`. The advantage of this
749 * macro is that it can produce a message that includes the incorrect
750 * error message and code.
752 * This can only be used to test for a specific error. If you want to
753 * test that @err is set, but don't care what it's set to, just use
754 * `g_assert_nonnull (err)`.
762 * An opaque structure representing a test case.
768 * An opaque structure representing a test suite.
772 /* Global variable for storing assertion messages; this is the counterpart to
773 * glibc's (private) __abort_msg variable, and allows developers and crash
774 * analysis systems like Apport and ABRT to fish out assertion messages from
775 * core dumps, instead of having to catch them on screen output.
777 GLIB_VAR char *__glib_assert_msg;
778 char *__glib_assert_msg = NULL;
780 /* --- constants --- */
781 #define G_TEST_STATUS_TIMED_OUT 1024
783 /* --- structures --- */
788 void (*fixture_setup) (void*, gconstpointer);
789 void (*fixture_test) (void*, gconstpointer);
790 void (*fixture_teardown) (void*, gconstpointer);
799 typedef struct DestroyEntry DestroyEntry;
803 GDestroyNotify destroy_func;
804 gpointer destroy_data;
807 /* --- prototypes --- */
808 static void test_run_seed (const gchar *rseed);
809 static void test_trap_clear (void);
810 static guint8* g_test_log_dump (GTestLogMsg *msg,
812 static void gtest_default_log_handler (const gchar *log_domain,
813 GLogLevelFlags log_level,
814 const gchar *message,
815 gpointer unused_data);
818 static const char * const g_test_result_names[] = {
825 /* --- variables --- */
826 static int test_log_fd = -1;
827 static gboolean test_mode_fatal = TRUE;
828 static gboolean g_test_run_once = TRUE;
829 static gboolean test_isolate_dirs = FALSE;
830 static gchar *test_isolate_dirs_tmpdir = NULL;
831 static const gchar *test_tmpdir = NULL;
832 static gboolean test_run_list = FALSE;
833 static gchar *test_run_seedstr = NULL;
834 G_LOCK_DEFINE_STATIC (test_run_rand);
835 static GRand *test_run_rand = NULL;
836 static gchar *test_run_name = "";
837 static GSList **test_filename_free_list;
838 static guint test_run_forks = 0;
839 static guint test_run_count = 0;
840 static guint test_count = 0;
841 static guint test_skipped_count = 0;
842 static GTestResult test_run_success = G_TEST_RUN_FAILURE;
843 static gchar *test_run_msg = NULL;
844 static guint test_startup_skip_count = 0;
845 static GTimer *test_user_timer = NULL;
846 static double test_user_stamp = 0;
847 static GSList *test_paths = NULL;
848 static GSList *test_paths_skipped = NULL;
849 static GTestSuite *test_suite_root = NULL;
850 static int test_trap_last_status = 0; /* unmodified platform-specific status */
851 static GPid test_trap_last_pid = 0;
852 static char *test_trap_last_subprocess = NULL;
853 static char *test_trap_last_stdout = NULL;
854 static char *test_trap_last_stderr = NULL;
855 static char *test_uri_base = NULL;
856 static gboolean test_debug_log = FALSE;
857 static gboolean test_tap_log = TRUE; /* default to TAP as of GLib 2.62; see #1619; the non-TAP output mode is deprecated */
858 static gboolean test_nonfatal_assertions = FALSE;
859 static DestroyEntry *test_destroy_queue = NULL;
860 static char *test_argv0 = NULL;
861 static char *test_argv0_dirname;
862 static const char *test_disted_files_dir;
863 static const char *test_built_files_dir;
864 static char *test_initial_cwd = NULL;
865 static gboolean test_in_forked_child = FALSE;
866 static gboolean test_in_subprocess = FALSE;
867 static GTestConfig mutable_test_config_vars = {
868 FALSE, /* test_initialized */
869 TRUE, /* test_quick */
870 FALSE, /* test_perf */
871 FALSE, /* test_verbose */
872 FALSE, /* test_quiet */
873 TRUE, /* test_undefined */
875 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
876 static gboolean no_g_set_prgname = FALSE;
878 /* --- functions --- */
880 g_test_log_type_name (GTestLogType log_type)
884 case G_TEST_LOG_NONE: return "none";
885 case G_TEST_LOG_ERROR: return "error";
886 case G_TEST_LOG_START_BINARY: return "binary";
887 case G_TEST_LOG_LIST_CASE: return "list";
888 case G_TEST_LOG_SKIP_CASE: return "skip";
889 case G_TEST_LOG_START_CASE: return "start";
890 case G_TEST_LOG_STOP_CASE: return "stop";
891 case G_TEST_LOG_MIN_RESULT: return "minperf";
892 case G_TEST_LOG_MAX_RESULT: return "maxperf";
893 case G_TEST_LOG_MESSAGE: return "message";
894 case G_TEST_LOG_START_SUITE: return "start suite";
895 case G_TEST_LOG_STOP_SUITE: return "stop suite";
901 g_test_log_send (guint n_bytes,
902 const guint8 *buffer)
904 if (test_log_fd >= 0)
908 r = write (test_log_fd, buffer, n_bytes);
909 while (r < 0 && errno == EINTR);
913 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
916 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
917 msg = g_test_log_buffer_pop (lbuffer);
918 g_warn_if_fail (msg != NULL);
919 g_warn_if_fail (lbuffer->data->len == 0);
920 g_test_log_buffer_free (lbuffer);
922 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
923 for (ui = 0; ui < msg->n_strings; ui++)
924 g_printerr (":{%s}", msg->strings[ui]);
928 for (ui = 0; ui < msg->n_nums; ui++)
930 if ((long double) (long) msg->nums[ui] == msg->nums[ui])
931 g_printerr ("%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
933 g_printerr ("%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
937 g_printerr (":LOG*}\n");
938 g_test_log_msg_free (msg);
943 g_test_log (GTestLogType lbit,
944 const gchar *string1,
945 const gchar *string2,
952 gchar *astrings[3] = { NULL, NULL, NULL };
958 case G_TEST_LOG_START_BINARY:
960 g_print ("# random seed: %s\n", string2);
961 else if (g_test_verbose ())
962 g_print ("GTest: random seed: %s\n", string2);
964 case G_TEST_LOG_START_SUITE:
967 /* We only print the TAP "plan" (1..n) ahead of time if we did
968 * not use the -p option to select specific tests to be run. */
970 g_print ("# Start of %s tests\n", string1);
971 else if (test_paths == NULL)
972 g_print ("1..%d\n", test_count);
975 case G_TEST_LOG_STOP_SUITE:
978 /* If we didn't print the TAP "plan" at the beginning because
979 * we were using -p, we need to print how many tests we ran at
980 * the end instead. */
982 g_print ("# End of %s tests\n", string1);
983 else if (test_paths != NULL)
984 g_print ("1..%d\n", test_run_count);
987 case G_TEST_LOG_STOP_CASE:
989 fail = result == G_TEST_RUN_FAILURE;
994 /* The TAP representation for an expected failure starts with
995 * "not ok", even though it does not actually count as failing
996 * due to the use of the TODO directive. "ok # TODO" would mean
997 * a test that was expected to fail unexpectedly succeeded,
998 * for which GTestResult does not currently have a
1000 if (fail || result == G_TEST_RUN_INCOMPLETE)
1005 g_print ("%s %d %s", ok, test_run_count, string1);
1006 if (result == G_TEST_RUN_INCOMPLETE)
1007 g_print (" # TODO %s\n", string2 ? string2 : "");
1008 else if (result == G_TEST_RUN_SKIPPED)
1009 g_print (" # SKIP %s\n", string2 ? string2 : "");
1013 else if (g_test_verbose ())
1014 g_print ("GTest: result: %s\n", g_test_result_names[result]);
1015 else if (!g_test_quiet ())
1016 g_print ("%s\n", g_test_result_names[result]);
1017 if (fail && test_mode_fatal)
1020 g_print ("Bail out!\n");
1023 if (result == G_TEST_RUN_SKIPPED || result == G_TEST_RUN_INCOMPLETE)
1024 test_skipped_count++;
1026 case G_TEST_LOG_SKIP_CASE:
1028 g_print ("ok %d %s # SKIP\n", test_run_count, string1);
1030 case G_TEST_LOG_MIN_RESULT:
1032 g_print ("# min perf: %s\n", string1);
1033 else if (g_test_verbose ())
1034 g_print ("(MINPERF:%s)\n", string1);
1036 case G_TEST_LOG_MAX_RESULT:
1038 g_print ("# max perf: %s\n", string1);
1039 else if (g_test_verbose ())
1040 g_print ("(MAXPERF:%s)\n", string1);
1042 case G_TEST_LOG_MESSAGE:
1044 g_print ("# %s\n", string1);
1045 else if (g_test_verbose ())
1046 g_print ("(MSG: %s)\n", string1);
1048 case G_TEST_LOG_ERROR:
1050 g_print ("Bail out! %s\n", string1);
1051 else if (g_test_verbose ())
1052 g_print ("(ERROR: %s)\n", string1);
1057 msg.log_type = lbit;
1058 msg.n_strings = (string1 != NULL) + (string1 && string2);
1059 msg.strings = astrings;
1060 astrings[0] = (gchar*) string1;
1061 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
1062 msg.n_nums = n_args;
1064 dbuffer = g_test_log_dump (&msg, &dbufferlen);
1065 g_test_log_send (dbufferlen, dbuffer);
1070 case G_TEST_LOG_START_CASE:
1073 else if (g_test_verbose ())
1074 g_print ("GTest: run: %s\n", string1);
1075 else if (!g_test_quiet ())
1076 g_print ("%s: ", string1);
1082 /* We intentionally parse the command line without GOptionContext
1083 * because otherwise you would never be able to test it.
1086 parse_args (gint *argc_p,
1089 guint argc = *argc_p;
1090 gchar **argv = *argv_p;
1093 test_argv0 = argv[0];
1094 test_initial_cwd = g_get_current_dir ();
1096 /* parse known args */
1097 for (i = 1; i < argc; i++)
1099 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
1101 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1102 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1103 g_log_set_always_fatal (fatal_mask);
1106 else if (strcmp (argv[i], "--keep-going") == 0 ||
1107 strcmp (argv[i], "-k") == 0)
1109 test_mode_fatal = FALSE;
1112 else if (strcmp (argv[i], "--debug-log") == 0)
1114 test_debug_log = TRUE;
1117 else if (strcmp (argv[i], "--tap") == 0)
1119 test_tap_log = TRUE;
1122 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
1124 gchar *equal = argv[i] + 12;
1126 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
1127 else if (i + 1 < argc)
1130 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
1134 /* Force non-TAP output when using gtester */
1135 test_tap_log = FALSE;
1137 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
1139 gchar *equal = argv[i] + 16;
1141 test_startup_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
1142 else if (i + 1 < argc)
1145 test_startup_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
1149 else if (strcmp ("--GTestSubprocess", argv[i]) == 0)
1151 test_in_subprocess = TRUE;
1152 /* We typically expect these child processes to crash, and some
1153 * tests spawn a *lot* of them. Avoid spamming system crash
1154 * collection programs such as systemd-coredump and abrt.
1156 #ifdef HAVE_SYS_RESOURCE_H
1158 struct rlimit limit = { 0, 0 };
1159 (void) setrlimit (RLIMIT_CORE, &limit);
1164 /* Force non-TAP output when spawning a subprocess, since people often
1165 * test the stdout/stderr of the subprocess strictly */
1166 test_tap_log = FALSE;
1168 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
1170 gchar *equal = argv[i] + 2;
1172 test_paths = g_slist_prepend (test_paths, equal + 1);
1173 else if (i + 1 < argc)
1176 test_paths = g_slist_prepend (test_paths, argv[i]);
1180 else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
1182 gchar *equal = argv[i] + 2;
1184 test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
1185 else if (i + 1 < argc)
1188 test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
1192 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
1194 gchar *equal = argv[i] + 2;
1195 const gchar *mode = "";
1198 else if (i + 1 < argc)
1203 if (strcmp (mode, "perf") == 0)
1204 mutable_test_config_vars.test_perf = TRUE;
1205 else if (strcmp (mode, "slow") == 0)
1206 mutable_test_config_vars.test_quick = FALSE;
1207 else if (strcmp (mode, "thorough") == 0)
1208 mutable_test_config_vars.test_quick = FALSE;
1209 else if (strcmp (mode, "quick") == 0)
1211 mutable_test_config_vars.test_quick = TRUE;
1212 mutable_test_config_vars.test_perf = FALSE;
1214 else if (strcmp (mode, "undefined") == 0)
1215 mutable_test_config_vars.test_undefined = TRUE;
1216 else if (strcmp (mode, "no-undefined") == 0)
1217 mutable_test_config_vars.test_undefined = FALSE;
1219 g_error ("unknown test mode: -m %s", mode);
1222 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
1224 mutable_test_config_vars.test_quiet = TRUE;
1225 mutable_test_config_vars.test_verbose = FALSE;
1228 else if (strcmp ("--verbose", argv[i]) == 0)
1230 mutable_test_config_vars.test_quiet = FALSE;
1231 mutable_test_config_vars.test_verbose = TRUE;
1234 else if (strcmp ("-l", argv[i]) == 0)
1236 test_run_list = TRUE;
1239 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
1241 gchar *equal = argv[i] + 6;
1243 test_run_seedstr = equal + 1;
1244 else if (i + 1 < argc)
1247 test_run_seedstr = argv[i];
1251 else if (strcmp ("-?", argv[i]) == 0 ||
1252 strcmp ("-h", argv[i]) == 0 ||
1253 strcmp ("--help", argv[i]) == 0)
1256 " %s [OPTION...]\n\n"
1258 " -h, --help Show help options\n\n"
1260 " --g-fatal-warnings Make all warnings fatal\n"
1261 " -l List test cases available in a test executable\n"
1262 " -m {perf|slow|thorough|quick} Execute tests according to mode\n"
1263 " -m {undefined|no-undefined} Execute tests according to mode\n"
1264 " -p TESTPATH Only start test cases matching TESTPATH\n"
1265 " -s TESTPATH Skip all tests matching TESTPATH\n"
1266 " --seed=SEEDSTRING Start tests with random seed SEEDSTRING\n"
1267 " --debug-log debug test logging output\n"
1268 " -q, --quiet Run tests quietly\n"
1269 " --verbose Run tests verbosely\n",
1275 /* We've been prepending to test_paths, but its order matters, so
1277 test_paths = g_slist_reverse (test_paths);
1281 for (i = 1; i < argc; i++)
1284 argv[e++] = argv[i];
1291 /* A fairly naive `rm -rf` implementation to clean up after unit tests. */
1293 rm_rf (const gchar *path)
1298 dir = g_dir_open (path, 0, NULL);
1301 /* Assume it’s a file. */
1306 while ((entry = g_dir_read_name (dir)) != NULL)
1308 gchar *sub_path = g_build_filename (path, entry, NULL);
1318 /* Implement the %G_TEST_OPTION_ISOLATE_DIRS option, iff it’s enabled. Create
1319 * a temporary directory for this unit test (disambiguated using @test_run_name)
1320 * and use g_set_user_dirs() to point various XDG directories into it, without
1321 * having to call setenv() in a process which potentially has threads running.
1323 * Note that this is called for each unit test, and hence won’t have taken
1324 * effect before g_test_run() is called in the unit test’s main(). Hence
1325 * references to XDG variables in main() will not be using the temporary
1328 test_do_isolate_dirs (GError **error)
1330 gchar *subdir = NULL;
1331 gchar *home_dir = NULL, *cache_dir = NULL, *config_dir = NULL;
1332 gchar *data_dir = NULL, *runtime_dir = NULL;
1333 gchar *config_dirs[3];
1334 gchar *data_dirs[3];
1336 if (!test_isolate_dirs)
1339 /* The @test_run_name includes the test suites, so may be several directories
1340 * deep. Add a `.dirs` directory to contain all the paths we create, and
1341 * guarantee none of them clash with test paths below the current one — test
1342 * paths may not contain components starting with `.`. */
1343 subdir = g_build_filename (test_tmpdir, test_run_name, ".dirs", NULL);
1345 /* We have to create the runtime directory (because it must be bound to
1346 * the session lifetime, which we consider to be the lifetime of the unit
1347 * test for testing purposes — see
1348 * https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html.
1349 * We don’t need to create the other directories — the specification
1350 * requires that client code create them if they don’t exist. Not creating
1351 * them automatically is a good test of clients’ adherence to the spec
1352 * and error handling of missing directories. */
1353 runtime_dir = g_build_filename (subdir, "runtime", NULL);
1354 if (g_mkdir_with_parents (runtime_dir, 0700) != 0)
1356 gint saved_errno = errno;
1357 g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
1358 "Failed to create XDG_RUNTIME_DIR ‘%s’: %s",
1359 runtime_dir, g_strerror (saved_errno));
1360 g_free (runtime_dir);
1365 home_dir = g_build_filename (subdir, "home", NULL);
1366 cache_dir = g_build_filename (subdir, "cache", NULL);
1367 config_dir = g_build_filename (subdir, "config", NULL);
1368 data_dir = g_build_filename (subdir, "data", NULL);
1370 config_dirs[0] = g_build_filename (subdir, "system-config1", NULL);
1371 config_dirs[1] = g_build_filename (subdir, "system-config2", NULL);
1372 config_dirs[2] = NULL;
1374 data_dirs[0] = g_build_filename (subdir, "system-data1", NULL);
1375 data_dirs[1] = g_build_filename (subdir, "system-data2", NULL);
1376 data_dirs[2] = NULL;
1378 /* Remember to update the documentation for %G_TEST_OPTION_ISOLATE_DIRS if
1379 * this list changes. */
1380 g_set_user_dirs ("HOME", home_dir,
1381 "XDG_CACHE_HOME", cache_dir,
1382 "XDG_CONFIG_DIRS", config_dirs,
1383 "XDG_CONFIG_HOME", config_dir,
1384 "XDG_DATA_DIRS", data_dirs,
1385 "XDG_DATA_HOME", data_dir,
1386 "XDG_RUNTIME_DIR", runtime_dir,
1389 g_free (runtime_dir);
1391 g_free (config_dir);
1394 g_free (data_dirs[1]);
1395 g_free (data_dirs[0]);
1396 g_free (config_dirs[1]);
1397 g_free (config_dirs[0]);
1403 /* Clean up after test_do_isolate_dirs(). */
1405 test_rm_isolate_dirs (void)
1407 gchar *subdir = NULL;
1409 if (!test_isolate_dirs)
1412 subdir = g_build_filename (test_tmpdir, test_run_name, NULL);
1419 * @argc: Address of the @argc parameter of the main() function.
1420 * Changed if any arguments were handled.
1421 * @argv: Address of the @argv parameter of main().
1422 * Any parameters understood by g_test_init() stripped before return.
1423 * @...: %NULL-terminated list of special options, documented below.
1425 * Initialize the GLib testing framework, e.g. by seeding the
1426 * test random number generator, the name for g_get_prgname()
1427 * and parsing test related command line args.
1429 * So far, the following arguments are understood:
1431 * - `-l`: List test cases available in a test executable.
1432 * - `--seed=SEED`: Provide a random seed to reproduce test
1433 * runs using random numbers.
1434 * - `--verbose`: Run tests verbosely.
1435 * - `-q`, `--quiet`: Run tests quietly.
1436 * - `-p PATH`: Execute all tests matching the given path.
1437 * - `-s PATH`: Skip all tests matching the given path.
1438 * This can also be used to force a test to run that would otherwise
1439 * be skipped (ie, a test whose name contains "/subprocess").
1440 * - `-m {perf|slow|thorough|quick|undefined|no-undefined}`: Execute tests according to these test modes:
1442 * `perf`: Performance tests, may take long and report results (off by default).
1444 * `slow`, `thorough`: Slow and thorough tests, may take quite long and maximize coverage
1447 * `quick`: Quick tests, should run really quickly and give good coverage (the default).
1449 * `undefined`: Tests for undefined behaviour, may provoke programming errors
1450 * under g_test_trap_subprocess() or g_test_expect_message() to check
1451 * that appropriate assertions or warnings are given (the default).
1453 * `no-undefined`: Avoid tests for undefined behaviour
1455 * - `--debug-log`: Debug test logging output.
1457 * Options which can be passed to @... are:
1459 * - `"no_g_set_prgname"`: Causes g_test_init() to not call g_set_prgname().
1460 * - %G_TEST_OPTION_ISOLATE_DIRS: Creates a unique temporary directory for each
1461 * unit test and uses g_set_user_dirs() to set XDG directories to point into
1462 * that temporary directory for the duration of the unit test. See the
1463 * documentation for %G_TEST_OPTION_ISOLATE_DIRS.
1465 * Since 2.58, if tests are compiled with `G_DISABLE_ASSERT` defined,
1466 * g_test_init() will print an error and exit. This is to prevent no-op tests
1467 * from being executed, as g_assert() is commonly (erroneously) used in unit
1468 * tests, and is a no-op when compiled with `G_DISABLE_ASSERT`. Ensure your
1469 * tests are compiled without `G_DISABLE_ASSERT` defined.
1474 (g_test_init) (int *argc,
1478 static char seedstr[4 + 4 * 8 + 1];
1481 /* make warnings and criticals fatal for all test programs */
1482 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1484 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1485 g_log_set_always_fatal (fatal_mask);
1486 /* check caller args */
1487 g_return_if_fail (argc != NULL);
1488 g_return_if_fail (argv != NULL);
1489 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
1490 mutable_test_config_vars.test_initialized = TRUE;
1492 va_start (args, argv);
1493 while ((option = va_arg (args, char *)))
1495 if (g_strcmp0 (option, "no_g_set_prgname") == 0)
1496 no_g_set_prgname = TRUE;
1497 else if (g_strcmp0 (option, G_TEST_OPTION_ISOLATE_DIRS) == 0)
1498 test_isolate_dirs = TRUE;
1502 /* setup random seed string */
1503 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
1504 test_run_seedstr = seedstr;
1506 /* parse args, sets up mode, changes seed, etc. */
1507 parse_args (argc, argv);
1509 if (!g_get_prgname() && !no_g_set_prgname)
1510 g_set_prgname ((*argv)[0]);
1512 /* Set up the temporary directory for isolating the test. We have to do this
1513 * early, as we want the return values from g_get_user_data_dir() (and
1514 * friends) to return subdirectories of the temporary directory throughout
1515 * the setup function, test, and teardown function, for each unit test.
1516 * See test_do_isolate_dirs().
1518 * The directory is deleted at the bottom of g_test_run().
1520 * Rather than setting the XDG_* environment variables we use a new
1521 * G_TEST_TMPDIR variable which gives the top-level temporary directory. This
1522 * allows test subprocesses to reuse the same temporary directory when
1523 * g_test_init() is called in them. */
1524 if (test_isolate_dirs)
1526 if (g_getenv ("G_TEST_TMPDIR") == NULL)
1528 gchar *test_prgname = NULL;
1530 GError *local_error = NULL;
1532 test_prgname = g_path_get_basename (g_get_prgname ());
1533 if (*test_prgname == '\0')
1535 g_free (test_prgname);
1536 test_prgname = g_strdup ("unknown");
1538 tmpl = g_strdup_printf ("test_%s_XXXXXX", test_prgname);
1539 g_free (test_prgname);
1541 test_isolate_dirs_tmpdir = g_dir_make_tmp (tmpl, &local_error);
1542 if (local_error != NULL)
1544 g_printerr ("%s: Failed to create temporary directory: %s\n",
1545 (*argv)[0], local_error->message);
1546 g_error_free (local_error);
1551 /* Propagate the temporary directory to subprocesses. */
1552 g_setenv ("G_TEST_TMPDIR", test_isolate_dirs_tmpdir, TRUE);
1554 /* And clear the traditional environment variables so subprocesses
1555 * spawned by the code under test can’t trash anything. If a test
1556 * spawns a process, the test is responsible for propagating
1557 * appropriate environment variables.
1559 * We assume that any in-process code will use g_get_user_data_dir()
1560 * and friends, rather than getenv() directly.
1562 * We set them to ‘/dev/null’ as that should fairly obviously not
1563 * accidentally work, and should be fairly greppable. */
1565 const gchar *overridden_environment_variables[] =
1577 for (i = 0; i < G_N_ELEMENTS (overridden_environment_variables); i++)
1578 g_setenv (overridden_environment_variables[i], "/dev/null", TRUE);
1582 /* Cache this for the remainder of this process’ lifetime. */
1583 test_tmpdir = g_getenv ("G_TEST_TMPDIR");
1586 /* verify GRand reliability, needed for reliable seeds */
1589 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
1590 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
1591 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
1592 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
1593 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
1597 /* check rand seed */
1598 test_run_seed (test_run_seedstr);
1600 /* report program start */
1601 g_log_set_default_handler (gtest_default_log_handler, NULL);
1602 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
1604 test_argv0_dirname = g_path_get_dirname (test_argv0);
1606 /* Make sure we get the real dirname that the test was run from */
1607 if (g_str_has_suffix (test_argv0_dirname, "/.libs"))
1610 tmp = g_path_get_dirname (test_argv0_dirname);
1611 g_free (test_argv0_dirname);
1612 test_argv0_dirname = tmp;
1615 test_disted_files_dir = g_getenv ("G_TEST_SRCDIR");
1616 if (!test_disted_files_dir)
1617 test_disted_files_dir = test_argv0_dirname;
1619 test_built_files_dir = g_getenv ("G_TEST_BUILDDIR");
1620 if (!test_built_files_dir)
1621 test_built_files_dir = test_argv0_dirname;
1625 test_run_seed (const gchar *rseed)
1627 guint seed_failed = 0;
1629 g_rand_free (test_run_rand);
1630 test_run_rand = NULL;
1631 while (strchr (" \t\v\r\n\f", *rseed))
1633 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
1635 const char *s = rseed + 4;
1636 if (strlen (s) >= 32) /* require 4 * 8 chars */
1638 guint32 seedarray[4];
1639 gchar *p, hexbuf[9] = { 0, };
1640 memcpy (hexbuf, s + 0, 8);
1641 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
1642 seed_failed += p != NULL && *p != 0;
1643 memcpy (hexbuf, s + 8, 8);
1644 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
1645 seed_failed += p != NULL && *p != 0;
1646 memcpy (hexbuf, s + 16, 8);
1647 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
1648 seed_failed += p != NULL && *p != 0;
1649 memcpy (hexbuf, s + 24, 8);
1650 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
1651 seed_failed += p != NULL && *p != 0;
1654 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
1659 g_error ("Unknown or invalid random seed: %s", rseed);
1665 * Get a reproducible random integer number.
1667 * The random numbers generated by the g_test_rand_*() family of functions
1668 * change with every new test program start, unless the --seed option is
1669 * given when starting test programs.
1671 * For individual test cases however, the random number generator is
1672 * reseeded, to avoid dependencies between tests and to make --seed
1673 * effective for all test cases.
1675 * Returns: a random number from the seeded random number generator.
1680 g_test_rand_int (void)
1684 G_LOCK (test_run_rand);
1685 r = g_rand_int (test_run_rand);
1686 G_UNLOCK (test_run_rand);
1692 * g_test_rand_int_range:
1693 * @begin: the minimum value returned by this function
1694 * @end: the smallest value not to be returned by this function
1696 * Get a reproducible random integer number out of a specified range,
1697 * see g_test_rand_int() for details on test case random numbers.
1699 * Returns: a number with @begin <= number < @end.
1704 g_test_rand_int_range (gint32 begin,
1709 G_LOCK (test_run_rand);
1710 r = g_rand_int_range (test_run_rand, begin, end);
1711 G_UNLOCK (test_run_rand);
1717 * g_test_rand_double:
1719 * Get a reproducible random floating point number,
1720 * see g_test_rand_int() for details on test case random numbers.
1722 * Returns: a random number from the seeded random number generator.
1727 g_test_rand_double (void)
1731 G_LOCK (test_run_rand);
1732 r = g_rand_double (test_run_rand);
1733 G_UNLOCK (test_run_rand);
1739 * g_test_rand_double_range:
1740 * @range_start: the minimum value returned by this function
1741 * @range_end: the minimum value not returned by this function
1743 * Get a reproducible random floating pointer number out of a specified range,
1744 * see g_test_rand_int() for details on test case random numbers.
1746 * Returns: a number with @range_start <= number < @range_end.
1751 g_test_rand_double_range (double range_start,
1756 G_LOCK (test_run_rand);
1757 r = g_rand_double_range (test_run_rand, range_start, range_end);
1758 G_UNLOCK (test_run_rand);
1764 * g_test_timer_start:
1766 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1767 * to be done. Call this function again to restart the timer.
1772 g_test_timer_start (void)
1774 if (!test_user_timer)
1775 test_user_timer = g_timer_new();
1776 test_user_stamp = 0;
1777 g_timer_start (test_user_timer);
1781 * g_test_timer_elapsed:
1783 * Get the time since the last start of the timer with g_test_timer_start().
1785 * Returns: the time since the last start of the timer, as a double
1790 g_test_timer_elapsed (void)
1792 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1793 return test_user_stamp;
1797 * g_test_timer_last:
1799 * Report the last result of g_test_timer_elapsed().
1801 * Returns: the last result of g_test_timer_elapsed(), as a double
1806 g_test_timer_last (void)
1808 return test_user_stamp;
1812 * g_test_minimized_result:
1813 * @minimized_quantity: the reported value
1814 * @format: the format string of the report message
1815 * @...: arguments to pass to the printf() function
1817 * Report the result of a performance or measurement test.
1818 * The test should generally strive to minimize the reported
1819 * quantities (smaller values are better than larger ones),
1820 * this and @minimized_quantity can determine sorting
1821 * order for test result reports.
1826 g_test_minimized_result (double minimized_quantity,
1830 long double largs = minimized_quantity;
1834 va_start (args, format);
1835 buffer = g_strdup_vprintf (format, args);
1838 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1843 * g_test_maximized_result:
1844 * @maximized_quantity: the reported value
1845 * @format: the format string of the report message
1846 * @...: arguments to pass to the printf() function
1848 * Report the result of a performance or measurement test.
1849 * The test should generally strive to maximize the reported
1850 * quantities (larger values are better than smaller ones),
1851 * this and @maximized_quantity can determine sorting
1852 * order for test result reports.
1857 g_test_maximized_result (double maximized_quantity,
1861 long double largs = maximized_quantity;
1865 va_start (args, format);
1866 buffer = g_strdup_vprintf (format, args);
1869 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1875 * @format: the format string
1876 * @...: printf-like arguments to @format
1878 * Add a message to the test report.
1883 g_test_message (const char *format,
1889 va_start (args, format);
1890 buffer = g_strdup_vprintf (format, args);
1893 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1899 * @uri_pattern: the base pattern for bug URIs
1901 * Specify the base URI for bug reports.
1903 * The base URI is used to construct bug report messages for
1904 * g_test_message() when g_test_bug() is called.
1905 * Calling this function outside of a test case sets the
1906 * default base URI for all test cases. Calling it from within
1907 * a test case changes the base URI for the scope of the test
1909 * Bug URIs are constructed by appending a bug specific URI
1910 * portion to @uri_pattern, or by replacing the special string
1911 * '\%s' within @uri_pattern if that is present.
1913 * If g_test_bug_base() is not called, bug URIs are formed solely
1914 * from the value provided by g_test_bug().
1919 g_test_bug_base (const char *uri_pattern)
1921 g_free (test_uri_base);
1922 test_uri_base = g_strdup (uri_pattern);
1927 * @bug_uri_snippet: Bug specific bug tracker URI portion.
1929 * This function adds a message to test reports that
1930 * associates a bug URI with a test case.
1931 * Bug URIs are constructed from a base URI set with g_test_bug_base()
1932 * and @bug_uri_snippet. If g_test_bug_base() has not been called, it is
1933 * assumed to be the empty string, so a full URI can be provided to
1934 * g_test_bug() instead.
1937 * See also: g_test_summary()
1940 g_test_bug (const char *bug_uri_snippet)
1942 const char *c = NULL;
1944 g_return_if_fail (bug_uri_snippet != NULL);
1946 if (test_uri_base != NULL)
1947 c = strstr (test_uri_base, "%s");
1950 char *b = g_strndup (test_uri_base, c - test_uri_base);
1951 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1953 g_test_message ("Bug Reference: %s", s);
1957 g_test_message ("Bug Reference: %s%s",
1958 test_uri_base ? test_uri_base : "", bug_uri_snippet);
1963 * @summary: One or two sentences summarising what the test checks, and how it
1966 * Set the summary for a test, which describes what the test checks, and how it
1967 * goes about checking it. This may be included in test report output, and is
1968 * useful documentation for anyone reading the source code or modifying a test
1969 * in future. It must be a single line.
1971 * This should be called at the top of a test function.
1974 * |[<!-- language="C" -->
1976 * test_array_sort (void)
1978 * g_test_summary ("Test my_array_sort() sorts the array correctly and stably, "
1979 * "including testing zero length and one-element arrays.");
1986 * See also: g_test_bug()
1989 g_test_summary (const char *summary)
1991 g_return_if_fail (summary != NULL);
1992 g_return_if_fail (strchr (summary, '\n') == NULL);
1993 g_return_if_fail (strchr (summary, '\r') == NULL);
1995 g_test_message ("%s summary: %s", test_run_name, summary);
2001 * Get the toplevel test suite for the test path API.
2003 * Returns: the toplevel #GTestSuite
2008 g_test_get_root (void)
2010 if (!test_suite_root)
2012 test_suite_root = g_test_create_suite ("root");
2013 g_free (test_suite_root->name);
2014 test_suite_root->name = g_strdup ("");
2017 return test_suite_root;
2023 * Runs all tests under the toplevel suite which can be retrieved
2024 * with g_test_get_root(). Similar to g_test_run_suite(), the test
2025 * cases to be run are filtered according to test path arguments
2026 * (`-p testpath` and `-s testpath`) as parsed by g_test_init().
2027 * g_test_run_suite() or g_test_run() may only be called once in a
2030 * In general, the tests and sub-suites within each suite are run in
2031 * the order in which they are defined. However, note that prior to
2032 * GLib 2.36, there was a bug in the `g_test_add_*`
2033 * functions which caused them to create multiple suites with the same
2034 * name, meaning that if you created tests "/foo/simple",
2035 * "/bar/simple", and "/foo/using-bar" in that order, they would get
2036 * run in that order (since g_test_run() would run the first "/foo"
2037 * suite, then the "/bar" suite, then the second "/foo" suite). As of
2038 * 2.36, this bug is fixed, and adding the tests in that order would
2039 * result in a running order of "/foo/simple", "/foo/using-bar",
2040 * "/bar/simple". If this new ordering is sub-optimal (because it puts
2041 * more-complicated tests before simpler ones, making it harder to
2042 * figure out exactly what has failed), you can fix it by changing the
2043 * test paths to group tests by suite in a way that will result in the
2044 * desired running order. Eg, "/simple/foo", "/simple/bar",
2045 * "/complex/foo-using-bar".
2047 * However, you should never make the actual result of a test depend
2048 * on the order that tests are run in. If you need to ensure that some
2049 * particular code runs before or after a given test case, use
2050 * g_test_add(), which lets you specify setup and teardown functions.
2052 * If all tests are skipped or marked as incomplete (expected failures),
2053 * this function will return 0 if producing TAP output, or 77 (treated
2054 * as "skip test" by Automake) otherwise.
2056 * Returns: 0 on success, 1 on failure (assuming it returns at all),
2057 * 0 or 77 if all tests were skipped with g_test_skip() and/or
2058 * g_test_incomplete()
2065 if (g_test_run_suite (g_test_get_root()) != 0)
2068 /* Clean up the temporary directory. */
2069 if (test_isolate_dirs_tmpdir != NULL)
2071 rm_rf (test_isolate_dirs_tmpdir);
2072 g_free (test_isolate_dirs_tmpdir);
2073 test_isolate_dirs_tmpdir = NULL;
2076 /* 77 is special to Automake's default driver, but not Automake's TAP driver
2077 * or Perl's prove(1) TAP driver. */
2081 if (test_run_count > 0 && test_run_count == test_skipped_count)
2088 * g_test_create_case:
2089 * @test_name: the name for the test case
2090 * @data_size: the size of the fixture data structure
2091 * @test_data: test data argument for the test functions
2092 * @data_setup: (scope async): the function to set up the fixture data
2093 * @data_test: (scope async): the actual test function
2094 * @data_teardown: (scope async): the function to teardown the fixture data
2096 * Create a new #GTestCase, named @test_name.
2098 * This API is fairly low level, and calling g_test_add() or g_test_add_func()
2101 * When this test is executed, a fixture structure of size @data_size
2102 * will be automatically allocated and filled with zeros. Then @data_setup is
2103 * called to initialize the fixture. After fixture setup, the actual test
2104 * function @data_test is called. Once the test run completes, the
2105 * fixture structure is torn down by calling @data_teardown and
2106 * after that the memory is automatically released by the test framework.
2108 * Splitting up a test run into fixture setup, test function and
2109 * fixture teardown is most useful if the same fixture type is used for
2110 * multiple tests. In this cases, g_test_create_case() will be
2111 * called with the same type of fixture (the @data_size argument), but varying
2112 * @test_name and @data_test arguments.
2114 * Returns: a newly allocated #GTestCase.
2119 g_test_create_case (const char *test_name,
2121 gconstpointer test_data,
2122 GTestFixtureFunc data_setup,
2123 GTestFixtureFunc data_test,
2124 GTestFixtureFunc data_teardown)
2128 g_return_val_if_fail (test_name != NULL, NULL);
2129 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
2130 g_return_val_if_fail (test_name[0] != 0, NULL);
2131 g_return_val_if_fail (data_test != NULL, NULL);
2133 tc = g_slice_new0 (GTestCase);
2134 tc->name = g_strdup (test_name);
2135 tc->test_data = (gpointer) test_data;
2136 tc->fixture_size = data_size;
2137 tc->fixture_setup = (void*) data_setup;
2138 tc->fixture_test = (void*) data_test;
2139 tc->fixture_teardown = (void*) data_teardown;
2145 find_suite (gconstpointer l, gconstpointer s)
2147 const GTestSuite *suite = l;
2148 const gchar *str = s;
2150 return strcmp (suite->name, str);
2154 find_case (gconstpointer l, gconstpointer s)
2156 const GTestCase *tc = l;
2157 const gchar *str = s;
2159 return strcmp (tc->name, str);
2164 * @fixture: (not nullable): the test fixture
2165 * @user_data: the data provided when registering the test
2167 * The type used for functions that operate on test fixtures. This is
2168 * used for the fixture setup and teardown functions as well as for the
2169 * testcases themselves.
2171 * @user_data is a pointer to the data that was given when registering
2174 * @fixture will be a pointer to the area of memory allocated by the
2175 * test framework, of the size requested. If the requested size was
2176 * zero then @fixture will be equal to @user_data.
2181 g_test_add_vtable (const char *testpath,
2183 gconstpointer test_data,
2184 GTestFixtureFunc data_setup,
2185 GTestFixtureFunc fixture_test_func,
2186 GTestFixtureFunc data_teardown)
2192 g_return_if_fail (testpath != NULL);
2193 g_return_if_fail (g_path_is_absolute (testpath));
2194 g_return_if_fail (fixture_test_func != NULL);
2195 g_return_if_fail (!test_isolate_dirs || strstr (testpath, "/.") == NULL);
2197 suite = g_test_get_root();
2198 segments = g_strsplit (testpath, "/", -1);
2199 for (ui = 0; segments[ui] != NULL; ui++)
2201 const char *seg = segments[ui];
2202 gboolean islast = segments[ui + 1] == NULL;
2203 if (islast && !seg[0])
2204 g_error ("invalid test case path: %s", testpath);
2206 continue; /* initial or duplicate slash */
2211 l = g_slist_find_custom (suite->suites, seg, find_suite);
2218 csuite = g_test_create_suite (seg);
2219 g_test_suite_add_suite (suite, csuite);
2227 if (g_slist_find_custom (suite->cases, seg, find_case))
2228 g_error ("duplicate test case path: %s", testpath);
2230 tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
2231 g_test_suite_add (suite, tc);
2234 g_strfreev (segments);
2240 * Indicates that a test failed. This function can be called
2241 * multiple times from the same test. You can use this function
2242 * if your test failed in a recoverable way.
2244 * Do not use this function if the failure of a test could cause
2245 * other tests to malfunction.
2247 * Calling this function will not stop the test from running, you
2248 * need to return from the test function yourself. So you can
2249 * produce additional diagnostic messages or even continue running
2252 * If not called from inside a test, this function does nothing.
2259 test_run_success = G_TEST_RUN_FAILURE;
2263 * g_test_incomplete:
2264 * @msg: (nullable): explanation
2266 * Indicates that a test failed because of some incomplete
2267 * functionality. This function can be called multiple times
2268 * from the same test.
2270 * Calling this function will not stop the test from running, you
2271 * need to return from the test function yourself. So you can
2272 * produce additional diagnostic messages or even continue running
2275 * If not called from inside a test, this function does nothing.
2280 g_test_incomplete (const gchar *msg)
2282 test_run_success = G_TEST_RUN_INCOMPLETE;
2283 g_free (test_run_msg);
2284 test_run_msg = g_strdup (msg);
2289 * @msg: (nullable): explanation
2291 * Indicates that a test was skipped.
2293 * Calling this function will not stop the test from running, you
2294 * need to return from the test function yourself. So you can
2295 * produce additional diagnostic messages or even continue running
2298 * If not called from inside a test, this function does nothing.
2303 g_test_skip (const gchar *msg)
2305 test_run_success = G_TEST_RUN_SKIPPED;
2306 g_free (test_run_msg);
2307 test_run_msg = g_strdup (msg);
2313 * Returns whether a test has already failed. This will
2314 * be the case when g_test_fail(), g_test_incomplete()
2315 * or g_test_skip() have been called, but also if an
2316 * assertion has failed.
2318 * This can be useful to return early from a test if
2319 * continuing after a failed assertion might be harmful.
2321 * The return value of this function is only meaningful
2322 * if it is called from inside a test function.
2324 * Returns: %TRUE if the test has failed
2329 g_test_failed (void)
2331 return test_run_success != G_TEST_RUN_SUCCESS;
2335 * g_test_set_nonfatal_assertions:
2337 * Changes the behaviour of the various `g_assert_*()` macros,
2338 * g_test_assert_expected_messages() and the various
2339 * `g_test_trap_assert_*()` macros to not abort to program, but instead
2340 * call g_test_fail() and continue. (This also changes the behavior of
2341 * g_test_fail() so that it will not cause the test program to abort
2342 * after completing the failed test.)
2344 * Note that the g_assert_not_reached() and g_assert() macros are not
2347 * This function can only be called after g_test_init().
2352 g_test_set_nonfatal_assertions (void)
2354 if (!g_test_config_vars->test_initialized)
2355 g_error ("g_test_set_nonfatal_assertions called without g_test_init");
2356 test_nonfatal_assertions = TRUE;
2357 test_mode_fatal = FALSE;
2363 * The type used for test case functions.
2370 * @testpath: /-separated test case path name for the test.
2371 * @test_func: (scope async): The test function to invoke for this test.
2373 * Create a new test case, similar to g_test_create_case(). However
2374 * the test is assumed to use no fixture, and test suites are automatically
2375 * created on the fly and added to the root fixture, based on the
2376 * slash-separated portions of @testpath.
2378 * If @testpath includes the component "subprocess" anywhere in it,
2379 * the test will be skipped by default, and only run if explicitly
2380 * required via the `-p` command-line option or g_test_trap_subprocess().
2382 * No component of @testpath may start with a dot (`.`) if the
2383 * %G_TEST_OPTION_ISOLATE_DIRS option is being used; and it is recommended to
2384 * do so even if it isn’t.
2389 g_test_add_func (const char *testpath,
2390 GTestFunc test_func)
2392 g_return_if_fail (testpath != NULL);
2393 g_return_if_fail (testpath[0] == '/');
2394 g_return_if_fail (test_func != NULL);
2395 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
2400 * @user_data: the data provided when registering the test
2402 * The type used for test case functions that take an extra pointer
2409 * g_test_add_data_func:
2410 * @testpath: /-separated test case path name for the test.
2411 * @test_data: Test data argument for the test function.
2412 * @test_func: (scope async): The test function to invoke for this test.
2414 * Create a new test case, similar to g_test_create_case(). However
2415 * the test is assumed to use no fixture, and test suites are automatically
2416 * created on the fly and added to the root fixture, based on the
2417 * slash-separated portions of @testpath. The @test_data argument
2418 * will be passed as first argument to @test_func.
2420 * If @testpath includes the component "subprocess" anywhere in it,
2421 * the test will be skipped by default, and only run if explicitly
2422 * required via the `-p` command-line option or g_test_trap_subprocess().
2424 * No component of @testpath may start with a dot (`.`) if the
2425 * %G_TEST_OPTION_ISOLATE_DIRS option is being used; and it is recommended to
2426 * do so even if it isn’t.
2431 g_test_add_data_func (const char *testpath,
2432 gconstpointer test_data,
2433 GTestDataFunc test_func)
2435 g_return_if_fail (testpath != NULL);
2436 g_return_if_fail (testpath[0] == '/');
2437 g_return_if_fail (test_func != NULL);
2439 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
2443 * g_test_add_data_func_full:
2444 * @testpath: /-separated test case path name for the test.
2445 * @test_data: Test data argument for the test function.
2446 * @test_func: The test function to invoke for this test.
2447 * @data_free_func: #GDestroyNotify for @test_data.
2449 * Create a new test case, as with g_test_add_data_func(), but freeing
2450 * @test_data after the test run is complete.
2455 g_test_add_data_func_full (const char *testpath,
2457 GTestDataFunc test_func,
2458 GDestroyNotify data_free_func)
2460 g_return_if_fail (testpath != NULL);
2461 g_return_if_fail (testpath[0] == '/');
2462 g_return_if_fail (test_func != NULL);
2464 g_test_add_vtable (testpath, 0, test_data, NULL,
2465 (GTestFixtureFunc) test_func,
2466 (GTestFixtureFunc) data_free_func);
2470 g_test_suite_case_exists (GTestSuite *suite,
2471 const char *test_path)
2478 slash = strchr (test_path, '/');
2482 for (iter = suite->suites; iter; iter = iter->next)
2484 GTestSuite *child_suite = iter->data;
2486 if (!strncmp (child_suite->name, test_path, slash - test_path))
2487 if (g_test_suite_case_exists (child_suite, slash))
2493 for (iter = suite->cases; iter; iter = iter->next)
2496 if (!strcmp (tc->name, test_path))
2505 * g_test_create_suite:
2506 * @suite_name: a name for the suite
2508 * Create a new test suite with the name @suite_name.
2510 * Returns: A newly allocated #GTestSuite instance.
2515 g_test_create_suite (const char *suite_name)
2518 g_return_val_if_fail (suite_name != NULL, NULL);
2519 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
2520 g_return_val_if_fail (suite_name[0] != 0, NULL);
2521 ts = g_slice_new0 (GTestSuite);
2522 ts->name = g_strdup (suite_name);
2528 * @suite: a #GTestSuite
2529 * @test_case: a #GTestCase
2531 * Adds @test_case to @suite.
2536 g_test_suite_add (GTestSuite *suite,
2537 GTestCase *test_case)
2539 g_return_if_fail (suite != NULL);
2540 g_return_if_fail (test_case != NULL);
2542 suite->cases = g_slist_append (suite->cases, test_case);
2546 * g_test_suite_add_suite:
2547 * @suite: a #GTestSuite
2548 * @nestedsuite: another #GTestSuite
2550 * Adds @nestedsuite to @suite.
2555 g_test_suite_add_suite (GTestSuite *suite,
2556 GTestSuite *nestedsuite)
2558 g_return_if_fail (suite != NULL);
2559 g_return_if_fail (nestedsuite != NULL);
2561 suite->suites = g_slist_append (suite->suites, nestedsuite);
2565 * g_test_queue_free:
2566 * @gfree_pointer: the pointer to be stored.
2568 * Enqueue a pointer to be released with g_free() during the next
2569 * teardown phase. This is equivalent to calling g_test_queue_destroy()
2570 * with a destroy callback of g_free().
2575 g_test_queue_free (gpointer gfree_pointer)
2578 g_test_queue_destroy (g_free, gfree_pointer);
2582 * g_test_queue_destroy:
2583 * @destroy_func: Destroy callback for teardown phase.
2584 * @destroy_data: Destroy callback data.
2586 * This function enqueus a callback @destroy_func to be executed
2587 * during the next test case teardown phase. This is most useful
2588 * to auto destruct allocated test resources at the end of a test run.
2589 * Resources are released in reverse queue order, that means enqueueing
2590 * callback A before callback B will cause B() to be called before
2591 * A() during teardown.
2596 g_test_queue_destroy (GDestroyNotify destroy_func,
2597 gpointer destroy_data)
2599 DestroyEntry *dentry;
2601 g_return_if_fail (destroy_func != NULL);
2603 dentry = g_slice_new0 (DestroyEntry);
2604 dentry->destroy_func = destroy_func;
2605 dentry->destroy_data = destroy_data;
2606 dentry->next = test_destroy_queue;
2607 test_destroy_queue = dentry;
2611 test_case_run (GTestCase *tc)
2613 gchar *old_base = g_strdup (test_uri_base);
2614 GSList **old_free_list, *filename_free_list = NULL;
2615 gboolean success = G_TEST_RUN_SUCCESS;
2617 old_free_list = test_filename_free_list;
2618 test_filename_free_list = &filename_free_list;
2620 if (++test_run_count <= test_startup_skip_count)
2621 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
2622 else if (test_run_list)
2624 g_print ("%s\n", test_run_name);
2625 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
2629 GTimer *test_run_timer = g_timer_new();
2630 long double largs[3];
2632 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
2634 test_run_success = G_TEST_RUN_SUCCESS;
2635 g_clear_pointer (&test_run_msg, g_free);
2636 g_test_log_set_fatal_handler (NULL, NULL);
2637 if (test_paths_skipped && g_slist_find_custom (test_paths_skipped, test_run_name, (GCompareFunc)g_strcmp0))
2638 g_test_skip ("by request (-s option)");
2641 GError *local_error = NULL;
2643 if (!test_do_isolate_dirs (&local_error))
2645 g_test_log (G_TEST_LOG_ERROR, local_error->message, NULL, 0, NULL);
2647 g_error_free (local_error);
2651 g_timer_start (test_run_timer);
2652 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
2653 test_run_seed (test_run_seedstr);
2654 if (tc->fixture_setup)
2655 tc->fixture_setup (fixture, tc->test_data);
2656 tc->fixture_test (fixture, tc->test_data);
2658 while (test_destroy_queue)
2660 DestroyEntry *dentry = test_destroy_queue;
2661 test_destroy_queue = dentry->next;
2662 dentry->destroy_func (dentry->destroy_data);
2663 g_slice_free (DestroyEntry, dentry);
2665 if (tc->fixture_teardown)
2666 tc->fixture_teardown (fixture, tc->test_data);
2667 if (tc->fixture_size)
2669 g_timer_stop (test_run_timer);
2672 test_rm_isolate_dirs ();
2674 success = test_run_success;
2675 test_run_success = G_TEST_RUN_FAILURE;
2676 largs[0] = success; /* OK */
2677 largs[1] = test_run_forks;
2678 largs[2] = g_timer_elapsed (test_run_timer, NULL);
2679 g_test_log (G_TEST_LOG_STOP_CASE, test_run_name, test_run_msg, G_N_ELEMENTS (largs), largs);
2680 g_clear_pointer (&test_run_msg, g_free);
2681 g_timer_destroy (test_run_timer);
2684 g_slist_free_full (filename_free_list, g_free);
2685 test_filename_free_list = old_free_list;
2686 g_free (test_uri_base);
2687 test_uri_base = old_base;
2689 return (success == G_TEST_RUN_SUCCESS ||
2690 success == G_TEST_RUN_SKIPPED ||
2691 success == G_TEST_RUN_INCOMPLETE);
2695 path_has_prefix (const char *path,
2698 int prefix_len = strlen (prefix);
2700 return (strncmp (path, prefix, prefix_len) == 0 &&
2701 (path[prefix_len] == '\0' ||
2702 path[prefix_len] == '/'));
2706 test_should_run (const char *test_path,
2707 const char *cmp_path)
2709 if (strstr (test_run_name, "/subprocess"))
2711 if (g_strcmp0 (test_path, cmp_path) == 0)
2714 if (g_test_verbose ())
2715 g_print ("GTest: skipping: %s\n", test_run_name);
2719 return !cmp_path || path_has_prefix (test_path, cmp_path);
2722 /* Recurse through @suite, running tests matching @path (or all tests
2723 * if @path is %NULL).
2726 g_test_run_suite_internal (GTestSuite *suite,
2730 gchar *old_name = test_run_name;
2733 g_return_val_if_fail (suite != NULL, -1);
2735 g_test_log (G_TEST_LOG_START_SUITE, suite->name, NULL, 0, NULL);
2737 for (iter = suite->cases; iter; iter = iter->next)
2739 GTestCase *tc = iter->data;
2741 test_run_name = g_build_path ("/", old_name, tc->name, NULL);
2742 if (test_should_run (test_run_name, path))
2744 if (!test_case_run (tc))
2747 g_free (test_run_name);
2750 for (iter = suite->suites; iter; iter = iter->next)
2752 GTestSuite *ts = iter->data;
2754 test_run_name = g_build_path ("/", old_name, ts->name, NULL);
2755 if (!path || path_has_prefix (path, test_run_name))
2756 n_bad += g_test_run_suite_internal (ts, path);
2757 g_free (test_run_name);
2760 test_run_name = old_name;
2762 g_test_log (G_TEST_LOG_STOP_SUITE, suite->name, NULL, 0, NULL);
2768 g_test_suite_count (GTestSuite *suite)
2773 g_return_val_if_fail (suite != NULL, -1);
2775 for (iter = suite->cases; iter; iter = iter->next)
2777 GTestCase *tc = iter->data;
2779 if (strcmp (tc->name, "subprocess") != 0)
2783 for (iter = suite->suites; iter; iter = iter->next)
2785 GTestSuite *ts = iter->data;
2787 if (strcmp (ts->name, "subprocess") != 0)
2788 n += g_test_suite_count (ts);
2796 * @suite: a #GTestSuite
2798 * Execute the tests within @suite and all nested #GTestSuites.
2799 * The test suites to be executed are filtered according to
2800 * test path arguments (`-p testpath` and `-s testpath`) as parsed by
2801 * g_test_init(). See the g_test_run() documentation for more
2802 * information on the order that tests are run in.
2804 * g_test_run_suite() or g_test_run() may only be called once
2807 * Returns: 0 on success
2812 g_test_run_suite (GTestSuite *suite)
2816 g_return_val_if_fail (g_test_run_once == TRUE, -1);
2818 g_test_run_once = FALSE;
2819 test_count = g_test_suite_count (suite);
2821 test_run_name = g_strdup_printf ("/%s", suite->name);
2827 for (iter = test_paths; iter; iter = iter->next)
2828 n_bad += g_test_run_suite_internal (suite, iter->data);
2831 n_bad = g_test_run_suite_internal (suite, NULL);
2833 g_free (test_run_name);
2834 test_run_name = NULL;
2840 gtest_default_log_handler (const gchar *log_domain,
2841 GLogLevelFlags log_level,
2842 const gchar *message,
2843 gpointer unused_data)
2845 const gchar *strv[16];
2846 gboolean fatal = FALSE;
2852 strv[i++] = log_domain;
2855 if (log_level & G_LOG_FLAG_FATAL)
2857 strv[i++] = "FATAL-";
2860 if (log_level & G_LOG_FLAG_RECURSION)
2861 strv[i++] = "RECURSIVE-";
2862 if (log_level & G_LOG_LEVEL_ERROR)
2863 strv[i++] = "ERROR";
2864 if (log_level & G_LOG_LEVEL_CRITICAL)
2865 strv[i++] = "CRITICAL";
2866 if (log_level & G_LOG_LEVEL_WARNING)
2867 strv[i++] = "WARNING";
2868 if (log_level & G_LOG_LEVEL_MESSAGE)
2869 strv[i++] = "MESSAGE";
2870 if (log_level & G_LOG_LEVEL_INFO)
2872 if (log_level & G_LOG_LEVEL_DEBUG)
2873 strv[i++] = "DEBUG";
2875 strv[i++] = message;
2878 msg = g_strjoinv ("", (gchar**) strv);
2879 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
2880 g_log_default_handler (log_domain, log_level, message, unused_data);
2886 g_assertion_message (const char *domain,
2890 const char *message)
2896 message = "code should not be reached";
2897 g_snprintf (lstr, 32, "%d", line);
2898 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
2899 "ERROR:", file, ":", lstr, ":",
2900 func, func[0] ? ":" : "",
2901 " ", message, NULL);
2902 g_printerr ("**\n%s\n", s);
2904 /* Don't print a fatal error indication if assertions are non-fatal, or
2905 * if we are a child process that might be sharing the parent's stdout. */
2906 if (test_nonfatal_assertions || test_in_subprocess || test_in_forked_child)
2907 g_test_log (G_TEST_LOG_MESSAGE, s, NULL, 0, NULL);
2909 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
2911 if (test_nonfatal_assertions)
2918 /* store assertion message in global variable, so that it can be found in a
2920 if (__glib_assert_msg != NULL)
2921 /* free the old one */
2922 free (__glib_assert_msg);
2923 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
2924 strcpy (__glib_assert_msg, s);
2928 if (test_in_subprocess)
2930 /* If this is a test case subprocess then it probably hit this
2931 * assertion on purpose, so just exit() rather than abort()ing,
2932 * to avoid triggering any system crash-reporting daemon.
2941 * g_assertion_message_expr: (skip)
2942 * @domain: (nullable): log domain
2943 * @file: file containing the assertion
2944 * @line: line number of the assertion
2945 * @func: function containing the assertion
2946 * @expr: (nullable): expression which failed
2948 * Internal function used to print messages from the public g_assert() and
2949 * g_assert_not_reached() macros.
2952 g_assertion_message_expr (const char *domain,
2960 s = g_strdup ("code should not be reached");
2962 s = g_strconcat ("assertion failed: (", expr, ")", NULL);
2963 g_assertion_message (domain, file, line, func, s);
2966 /* Normally g_assertion_message() won't return, but we need this for
2967 * when test_nonfatal_assertions is set, since
2968 * g_assertion_message_expr() is used for always-fatal assertions.
2970 if (test_in_subprocess)
2977 g_assertion_message_cmpnum (const char *domain,
2991 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;
2992 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;
2993 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr, (double) arg1, cmp, (double) arg2); break;
2994 /* ideally use: floats=%.7g double=%.17g */
2996 g_assertion_message (domain, file, line, func, s);
3001 g_assertion_message_cmpstr (const char *domain,
3010 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
3011 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
3012 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
3015 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
3018 g_assertion_message (domain, file, line, func, s);
3023 g_assertion_message_error (const char *domain,
3028 const GError *error,
3029 GQuark error_domain,
3034 /* This is used by both g_assert_error() and g_assert_no_error(), so there
3035 * are three cases: expected an error but got the wrong error, expected
3036 * an error but got no error, and expected no error but got an error.
3039 gstring = g_string_new ("assertion failed ");
3041 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
3042 g_quark_to_string (error_domain), error_code);
3044 g_string_append_printf (gstring, "(%s == NULL): ", expr);
3047 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
3048 g_quark_to_string (error->domain), error->code);
3050 g_string_append_printf (gstring, "%s is NULL", expr);
3052 g_assertion_message (domain, file, line, func, gstring->str);
3053 g_string_free (gstring, TRUE);
3058 * @str1: (nullable): a C string or %NULL
3059 * @str2: (nullable): another C string or %NULL
3061 * Compares @str1 and @str2 like strcmp(). Handles %NULL
3062 * gracefully by sorting it before non-%NULL strings.
3063 * Comparing two %NULL pointers returns 0.
3065 * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
3070 g_strcmp0 (const char *str1,
3074 return -(str1 != str2);
3076 return str1 != str2;
3077 return strcmp (str1, str2);
3081 test_trap_clear (void)
3083 test_trap_last_status = 0;
3084 test_trap_last_pid = 0;
3085 g_clear_pointer (&test_trap_last_subprocess, g_free);
3086 g_clear_pointer (&test_trap_last_stdout, g_free);
3087 g_clear_pointer (&test_trap_last_stderr, g_free);
3098 ret = dup2 (fd1, fd2);
3099 while (ret < 0 && errno == EINTR);
3108 int child_status; /* unmodified platform-specific status */
3110 GIOChannel *stdout_io;
3111 gboolean echo_stdout;
3112 GString *stdout_str;
3114 GIOChannel *stderr_io;
3115 gboolean echo_stderr;
3116 GString *stderr_str;
3120 check_complete (WaitForChildData *data)
3122 if (data->child_status != -1 && data->stdout_io == NULL && data->stderr_io == NULL)
3123 g_main_loop_quit (data->loop);
3127 child_exited (GPid pid,
3131 WaitForChildData *data = user_data;
3133 g_assert (status != -1);
3134 data->child_status = status;
3136 check_complete (data);
3140 child_timeout (gpointer user_data)
3142 WaitForChildData *data = user_data;
3145 TerminateProcess (data->pid, G_TEST_STATUS_TIMED_OUT);
3147 kill (data->pid, SIGALRM);
3154 child_read (GIOChannel *io, GIOCondition cond, gpointer user_data)
3156 WaitForChildData *data = user_data;
3158 gsize nread, nwrote, total;
3160 FILE *echo_file = NULL;
3162 status = g_io_channel_read_chars (io, buf, sizeof (buf), &nread, NULL);
3163 if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF)
3165 // FIXME data->error = (status == G_IO_STATUS_ERROR);
3166 if (io == data->stdout_io)
3167 g_clear_pointer (&data->stdout_io, g_io_channel_unref);
3169 g_clear_pointer (&data->stderr_io, g_io_channel_unref);
3171 check_complete (data);
3174 else if (status == G_IO_STATUS_AGAIN)
3177 if (io == data->stdout_io)
3179 g_string_append_len (data->stdout_str, buf, nread);
3180 if (data->echo_stdout)
3185 g_string_append_len (data->stderr_str, buf, nread);
3186 if (data->echo_stderr)
3192 for (total = 0; total < nread; total += nwrote)
3196 nwrote = fwrite (buf + total, 1, nread - total, echo_file);
3199 g_error ("write failed: %s", g_strerror (errsv));
3207 wait_for_child (GPid pid,
3208 int stdout_fd, gboolean echo_stdout,
3209 int stderr_fd, gboolean echo_stderr,
3212 WaitForChildData data;
3213 GMainContext *context;
3217 data.child_status = -1;
3219 context = g_main_context_new ();
3220 data.loop = g_main_loop_new (context, FALSE);
3222 source = g_child_watch_source_new (pid);
3223 g_source_set_callback (source, (GSourceFunc) child_exited, &data, NULL);
3224 g_source_attach (source, context);
3225 g_source_unref (source);
3227 data.echo_stdout = echo_stdout;
3228 data.stdout_str = g_string_new (NULL);
3229 data.stdout_io = g_io_channel_unix_new (stdout_fd);
3230 g_io_channel_set_close_on_unref (data.stdout_io, TRUE);
3231 g_io_channel_set_encoding (data.stdout_io, NULL, NULL);
3232 g_io_channel_set_buffered (data.stdout_io, FALSE);
3233 source = g_io_create_watch (data.stdout_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
3234 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
3235 g_source_attach (source, context);
3236 g_source_unref (source);
3238 data.echo_stderr = echo_stderr;
3239 data.stderr_str = g_string_new (NULL);
3240 data.stderr_io = g_io_channel_unix_new (stderr_fd);
3241 g_io_channel_set_close_on_unref (data.stderr_io, TRUE);
3242 g_io_channel_set_encoding (data.stderr_io, NULL, NULL);
3243 g_io_channel_set_buffered (data.stderr_io, FALSE);
3244 source = g_io_create_watch (data.stderr_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
3245 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
3246 g_source_attach (source, context);
3247 g_source_unref (source);
3251 source = g_timeout_source_new (0);
3252 g_source_set_ready_time (source, g_get_monotonic_time () + timeout);
3253 g_source_set_callback (source, (GSourceFunc) child_timeout, &data, NULL);
3254 g_source_attach (source, context);
3255 g_source_unref (source);
3258 g_main_loop_run (data.loop);
3259 g_main_loop_unref (data.loop);
3260 g_main_context_unref (context);
3262 test_trap_last_pid = pid;
3263 test_trap_last_status = data.child_status;
3264 test_trap_last_stdout = g_string_free (data.stdout_str, FALSE);
3265 test_trap_last_stderr = g_string_free (data.stderr_str, FALSE);
3267 g_clear_pointer (&data.stdout_io, g_io_channel_unref);
3268 g_clear_pointer (&data.stderr_io, g_io_channel_unref);
3273 * @usec_timeout: Timeout for the forked test in micro seconds.
3274 * @test_trap_flags: Flags to modify forking behaviour.
3276 * Fork the current test program to execute a test case that might
3277 * not return or that might abort.
3279 * If @usec_timeout is non-0, the forked test case is aborted and
3280 * considered failing if its run time exceeds it.
3282 * The forking behavior can be configured with the #GTestTrapFlags flags.
3284 * In the following example, the test code forks, the forked child
3285 * process produces some sample output and exits successfully.
3286 * The forking parent process then asserts successful child program
3287 * termination and validates child program outputs.
3289 * |[<!-- language="C" -->
3291 * test_fork_patterns (void)
3293 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
3295 * g_print ("some stdout text: somagic17\n");
3296 * g_printerr ("some stderr text: semagic43\n");
3297 * exit (0); // successful test run
3299 * g_test_trap_assert_passed ();
3300 * g_test_trap_assert_stdout ("*somagic17*");
3301 * g_test_trap_assert_stderr ("*semagic43*");
3305 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
3309 * Deprecated: This function is implemented only on Unix platforms,
3310 * and is not always reliable due to problems inherent in
3311 * fork-without-exec. Use g_test_trap_subprocess() instead.
3313 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
3315 g_test_trap_fork (guint64 usec_timeout,
3316 GTestTrapFlags test_trap_flags)
3319 int stdout_pipe[2] = { -1, -1 };
3320 int stderr_pipe[2] = { -1, -1 };
3324 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0)
3327 g_error ("failed to create pipes to fork test program: %s", g_strerror (errsv));
3329 test_trap_last_pid = fork ();
3331 if (test_trap_last_pid < 0)
3332 g_error ("failed to fork test program: %s", g_strerror (errsv));
3333 if (test_trap_last_pid == 0) /* child */
3336 test_in_forked_child = TRUE;
3337 close (stdout_pipe[0]);
3338 close (stderr_pipe[0]);
3339 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
3341 fd0 = g_open ("/dev/null", O_RDONLY, 0);
3343 g_error ("failed to open /dev/null for stdin redirection");
3345 if (safe_dup2 (stdout_pipe[1], 1) < 0 || safe_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && safe_dup2 (fd0, 0) < 0))
3348 g_error ("failed to dup2() in forked test program: %s", g_strerror (errsv));
3352 if (stdout_pipe[1] >= 3)
3353 close (stdout_pipe[1]);
3354 if (stderr_pipe[1] >= 3)
3355 close (stderr_pipe[1]);
3357 /* We typically expect these child processes to crash, and some
3358 * tests spawn a *lot* of them. Avoid spamming system crash
3359 * collection programs such as systemd-coredump and abrt.
3361 #ifdef HAVE_SYS_RESOURCE_H
3363 struct rlimit limit = { 0, 0 };
3364 (void) setrlimit (RLIMIT_CORE, &limit);
3373 close (stdout_pipe[1]);
3374 close (stderr_pipe[1]);
3376 wait_for_child (test_trap_last_pid,
3377 stdout_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT),
3378 stderr_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR),
3383 g_message ("Not implemented: g_test_trap_fork");
3388 G_GNUC_END_IGNORE_DEPRECATIONS
3391 * g_test_trap_subprocess:
3392 * @test_path: (nullable): Test to run in a subprocess
3393 * @usec_timeout: Timeout for the subprocess test in micro seconds.
3394 * @test_flags: Flags to modify subprocess behaviour.
3396 * Respawns the test program to run only @test_path in a subprocess.
3397 * This can be used for a test case that might not return, or that
3400 * If @test_path is %NULL then the same test is re-run in a subprocess.
3401 * You can use g_test_subprocess() to determine whether the test is in
3402 * a subprocess or not.
3404 * @test_path can also be the name of the parent test, followed by
3405 * "`/subprocess/`" and then a name for the specific subtest (or just
3406 * ending with "`/subprocess`" if the test only has one child test);
3407 * tests with names of this form will automatically be skipped in the
3410 * If @usec_timeout is non-0, the test subprocess is aborted and
3411 * considered failing if its run time exceeds it.
3413 * The subprocess behavior can be configured with the
3414 * #GTestSubprocessFlags flags.
3416 * You can use methods such as g_test_trap_assert_passed(),
3417 * g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to
3418 * check the results of the subprocess. (But note that
3419 * g_test_trap_assert_stdout() and g_test_trap_assert_stderr()
3420 * cannot be used if @test_flags specifies that the child should
3421 * inherit the parent stdout/stderr.)
3423 * If your `main ()` needs to behave differently in
3424 * the subprocess, you can call g_test_subprocess() (after calling
3425 * g_test_init()) to see whether you are in a subprocess.
3427 * The following example tests that calling
3428 * `my_object_new(1000000)` will abort with an error
3431 * |[<!-- language="C" -->
3433 * test_create_large_object (void)
3435 * if (g_test_subprocess ())
3437 * my_object_new (1000000);
3441 * // Reruns this same test in a subprocess
3442 * g_test_trap_subprocess (NULL, 0, 0);
3443 * g_test_trap_assert_failed ();
3444 * g_test_trap_assert_stderr ("*ERROR*too large*");
3448 * main (int argc, char **argv)
3450 * g_test_init (&argc, &argv, NULL);
3452 * g_test_add_func ("/myobject/create_large_object",
3453 * test_create_large_object);
3454 * return g_test_run ();
3461 g_test_trap_subprocess (const char *test_path,
3462 guint64 usec_timeout,
3463 GTestSubprocessFlags test_flags)
3465 GError *error = NULL;
3468 int stdout_fd, stderr_fd;
3471 /* Sanity check that they used GTestSubprocessFlags, not GTestTrapFlags */
3472 g_assert ((test_flags & (G_TEST_TRAP_INHERIT_STDIN | G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR)) == 0);
3476 if (!g_test_suite_case_exists (g_test_get_root (), test_path))
3477 g_error ("g_test_trap_subprocess: test does not exist: %s", test_path);
3481 test_path = test_run_name;
3484 if (g_test_verbose ())
3485 g_print ("GTest: subprocess: %s\n", test_path);
3488 test_trap_last_subprocess = g_strdup (test_path);
3490 argv = g_ptr_array_new ();
3491 g_ptr_array_add (argv, test_argv0);
3492 g_ptr_array_add (argv, "-q");
3493 g_ptr_array_add (argv, "-p");
3494 g_ptr_array_add (argv, (char *)test_path);
3495 g_ptr_array_add (argv, "--GTestSubprocess");
3496 if (test_log_fd != -1)
3498 char log_fd_buf[128];
3500 g_ptr_array_add (argv, "--GTestLogFD");
3501 g_snprintf (log_fd_buf, sizeof (log_fd_buf), "%d", test_log_fd);
3502 g_ptr_array_add (argv, log_fd_buf);
3504 g_ptr_array_add (argv, NULL);
3506 flags = G_SPAWN_DO_NOT_REAP_CHILD;
3507 if (test_log_fd != -1)
3508 flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
3509 if (test_flags & G_TEST_TRAP_INHERIT_STDIN)
3510 flags |= G_SPAWN_CHILD_INHERITS_STDIN;
3512 if (!g_spawn_async_with_pipes (test_initial_cwd,
3513 (char **)argv->pdata,
3516 &pid, NULL, &stdout_fd, &stderr_fd,
3519 g_error ("g_test_trap_subprocess() failed: %s",
3522 g_ptr_array_free (argv, TRUE);
3524 wait_for_child (pid,
3525 stdout_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDOUT),
3526 stderr_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDERR),
3531 * g_test_subprocess:
3533 * Returns %TRUE (after g_test_init() has been called) if the test
3534 * program is running under g_test_trap_subprocess().
3536 * Returns: %TRUE if the test program is running under
3537 * g_test_trap_subprocess().
3542 g_test_subprocess (void)
3544 return test_in_subprocess;
3548 * g_test_trap_has_passed:
3550 * Check the result of the last g_test_trap_subprocess() call.
3552 * Returns: %TRUE if the last test subprocess terminated successfully.
3557 g_test_trap_has_passed (void)
3560 return (WIFEXITED (test_trap_last_status) &&
3561 WEXITSTATUS (test_trap_last_status) == 0);
3563 return test_trap_last_status == 0;
3568 * g_test_trap_reached_timeout:
3570 * Check the result of the last g_test_trap_subprocess() call.
3572 * Returns: %TRUE if the last test subprocess got killed due to a timeout.
3577 g_test_trap_reached_timeout (void)
3580 return (WIFSIGNALED (test_trap_last_status) &&
3581 WTERMSIG (test_trap_last_status) == SIGALRM);
3583 return test_trap_last_status == G_TEST_STATUS_TIMED_OUT;
3588 log_child_output (const gchar *process_id)
3593 if (WIFEXITED (test_trap_last_status)) /* normal exit */
3595 if (WEXITSTATUS (test_trap_last_status) == 0)
3596 g_test_message ("child process (%s) exit status: 0 (success)",
3599 g_test_message ("child process (%s) exit status: %d (error)",
3600 process_id, WEXITSTATUS (test_trap_last_status));
3602 else if (WIFSIGNALED (test_trap_last_status) &&
3603 WTERMSIG (test_trap_last_status) == SIGALRM)
3605 g_test_message ("child process (%s) timed out", process_id);
3607 else if (WIFSIGNALED (test_trap_last_status))
3609 const gchar *maybe_dumped_core = "";
3612 if (WCOREDUMP (test_trap_last_status))
3613 maybe_dumped_core = ", core dumped";
3616 g_test_message ("child process (%s) killed by signal %d (%s)%s",
3617 process_id, WTERMSIG (test_trap_last_status),
3618 g_strsignal (WTERMSIG (test_trap_last_status)),
3623 g_test_message ("child process (%s) unknown wait status %d",
3624 process_id, test_trap_last_status);
3627 if (test_trap_last_status == 0)
3628 g_test_message ("child process (%s) exit status: 0 (success)",
3631 g_test_message ("child process (%s) exit status: %d (error)",
3632 process_id, test_trap_last_status);
3635 escaped = g_strescape (test_trap_last_stdout, NULL);
3636 g_test_message ("child process (%s) stdout: \"%s\"", process_id, escaped);
3639 escaped = g_strescape (test_trap_last_stderr, NULL);
3640 g_test_message ("child process (%s) stderr: \"%s\"", process_id, escaped);
3643 /* so we can use short-circuiting:
3644 * logged_child_output = logged_child_output || log_child_output (...) */
3649 g_test_trap_assertions (const char *domain,
3653 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
3654 const char *pattern)
3656 gboolean must_pass = assertion_flags == 0;
3657 gboolean must_fail = assertion_flags == 1;
3658 gboolean match_result = 0 == (assertion_flags & 1);
3659 gboolean logged_child_output = FALSE;
3660 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
3661 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
3662 const char *match_error = match_result ? "failed to match" : "contains invalid match";
3666 if (test_trap_last_subprocess != NULL)
3668 process_id = g_strdup_printf ("%s [%d]", test_trap_last_subprocess,
3669 test_trap_last_pid);
3671 else if (test_trap_last_pid != 0)
3672 process_id = g_strdup_printf ("%d", test_trap_last_pid);
3674 if (test_trap_last_subprocess != NULL)
3675 process_id = g_strdup (test_trap_last_subprocess);
3678 g_error ("g_test_trap_ assertion with no trapped test");
3680 if (must_pass && !g_test_trap_has_passed())
3684 logged_child_output = logged_child_output || log_child_output (process_id);
3686 msg = g_strdup_printf ("child process (%s) failed unexpectedly", process_id);
3687 g_assertion_message (domain, file, line, func, msg);
3690 if (must_fail && g_test_trap_has_passed())
3694 logged_child_output = logged_child_output || log_child_output (process_id);
3696 msg = g_strdup_printf ("child process (%s) did not fail as expected", process_id);
3697 g_assertion_message (domain, file, line, func, msg);
3700 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
3704 logged_child_output = logged_child_output || log_child_output (process_id);
3706 msg = g_strdup_printf ("stdout of child process (%s) %s: %s\nstdout was:\n%s",
3707 process_id, match_error, stdout_pattern, test_trap_last_stdout);
3708 g_assertion_message (domain, file, line, func, msg);
3711 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
3715 logged_child_output = logged_child_output || log_child_output (process_id);
3717 msg = g_strdup_printf ("stderr of child process (%s) %s: %s\nstderr was:\n%s",
3718 process_id, match_error, stderr_pattern, test_trap_last_stderr);
3719 g_assertion_message (domain, file, line, func, msg);
3723 (void) logged_child_output; /* shut up scan-build about the final unread assignment */
3725 g_free (process_id);
3729 gstring_overwrite_int (GString *gstring,
3733 vuint = g_htonl (vuint);
3734 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
3738 gstring_append_int (GString *gstring,
3741 vuint = g_htonl (vuint);
3742 g_string_append_len (gstring, (const gchar*) &vuint, 4);
3746 gstring_append_double (GString *gstring,
3749 union { double vdouble; guint64 vuint64; } u;
3750 u.vdouble = vdouble;
3751 u.vuint64 = GUINT64_TO_BE (u.vuint64);
3752 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
3756 g_test_log_dump (GTestLogMsg *msg,
3759 GString *gstring = g_string_sized_new (1024);
3761 gstring_append_int (gstring, 0); /* message length */
3762 gstring_append_int (gstring, msg->log_type);
3763 gstring_append_int (gstring, msg->n_strings);
3764 gstring_append_int (gstring, msg->n_nums);
3765 gstring_append_int (gstring, 0); /* reserved */
3766 for (ui = 0; ui < msg->n_strings; ui++)
3768 guint l = strlen (msg->strings[ui]);
3769 gstring_append_int (gstring, l);
3770 g_string_append_len (gstring, msg->strings[ui], l);
3772 for (ui = 0; ui < msg->n_nums; ui++)
3773 gstring_append_double (gstring, msg->nums[ui]);
3774 *len = gstring->len;
3775 gstring_overwrite_int (gstring, 0, *len); /* message length */
3776 return (guint8*) g_string_free (gstring, FALSE);
3779 static inline long double
3780 net_double (const gchar **ipointer)
3782 union { guint64 vuint64; double vdouble; } u;
3783 guint64 aligned_int64;
3784 memcpy (&aligned_int64, *ipointer, 8);
3786 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
3790 static inline guint32
3791 net_int (const gchar **ipointer)
3793 guint32 aligned_int;
3794 memcpy (&aligned_int, *ipointer, 4);
3796 return g_ntohl (aligned_int);
3800 g_test_log_extract (GTestLogBuffer *tbuffer)
3802 const gchar *p = tbuffer->data->str;
3805 if (tbuffer->data->len < 4 * 5)
3807 mlength = net_int (&p);
3808 if (tbuffer->data->len < mlength)
3810 msg.log_type = net_int (&p);
3811 msg.n_strings = net_int (&p);
3812 msg.n_nums = net_int (&p);
3813 if (net_int (&p) == 0)
3816 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
3817 msg.nums = g_new0 (long double, msg.n_nums);
3818 for (ui = 0; ui < msg.n_strings; ui++)
3820 guint sl = net_int (&p);
3821 msg.strings[ui] = g_strndup (p, sl);
3824 for (ui = 0; ui < msg.n_nums; ui++)
3825 msg.nums[ui] = net_double (&p);
3826 if (p <= tbuffer->data->str + mlength)
3828 g_string_erase (tbuffer->data, 0, mlength);
3829 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup2 (&msg, sizeof (msg)));
3834 g_strfreev (msg.strings);
3837 g_error ("corrupt log stream from test program");
3842 * g_test_log_buffer_new:
3844 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3847 g_test_log_buffer_new (void)
3849 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
3850 tb->data = g_string_sized_new (1024);
3855 * g_test_log_buffer_free:
3857 * Internal function for gtester to free test log messages, no ABI guarantees provided.
3860 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
3862 g_return_if_fail (tbuffer != NULL);
3863 while (tbuffer->msgs)
3864 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
3865 g_string_free (tbuffer->data, TRUE);
3870 * g_test_log_buffer_push:
3872 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3875 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
3877 const guint8 *bytes)
3879 g_return_if_fail (tbuffer != NULL);
3882 gboolean more_messages;
3883 g_return_if_fail (bytes != NULL);
3884 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
3886 more_messages = g_test_log_extract (tbuffer);
3887 while (more_messages);
3892 * g_test_log_buffer_pop:
3894 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
3897 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
3899 GTestLogMsg *msg = NULL;
3900 g_return_val_if_fail (tbuffer != NULL, NULL);
3903 GSList *slist = g_slist_last (tbuffer->msgs);
3905 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
3911 * g_test_log_msg_free:
3913 * Internal function for gtester to free test log messages, no ABI guarantees provided.
3916 g_test_log_msg_free (GTestLogMsg *tmsg)
3918 g_return_if_fail (tmsg != NULL);
3919 g_strfreev (tmsg->strings);
3920 g_free (tmsg->nums);
3925 g_test_build_filename_va (GTestFileType file_type,
3926 const gchar *first_path,
3929 const gchar *pathv[16];
3930 gsize num_path_segments;
3932 if (file_type == G_TEST_DIST)
3933 pathv[0] = test_disted_files_dir;
3934 else if (file_type == G_TEST_BUILT)
3935 pathv[0] = test_built_files_dir;
3937 g_assert_not_reached ();
3939 pathv[1] = first_path;
3941 for (num_path_segments = 2; num_path_segments < G_N_ELEMENTS (pathv); num_path_segments++)
3943 pathv[num_path_segments] = va_arg (ap, const char *);
3944 if (pathv[num_path_segments] == NULL)
3948 g_assert_cmpint (num_path_segments, <, G_N_ELEMENTS (pathv));
3950 return g_build_filenamev ((gchar **) pathv);
3954 * g_test_build_filename:
3955 * @file_type: the type of file (built vs. distributed)
3956 * @first_path: the first segment of the pathname
3957 * @...: %NULL-terminated additional path segments
3959 * Creates the pathname to a data file that is required for a test.
3961 * This function is conceptually similar to g_build_filename() except
3962 * that the first argument has been replaced with a #GTestFileType
3965 * The data file should either have been distributed with the module
3966 * containing the test (%G_TEST_DIST) or built as part of the build
3967 * system of that module (%G_TEST_BUILT).
3969 * In order for this function to work in srcdir != builddir situations,
3970 * the G_TEST_SRCDIR and G_TEST_BUILDDIR environment variables need to
3971 * have been defined. As of 2.38, this is done by the glib.mk
3972 * included in GLib. Please ensure that your copy is up to date before
3973 * using this function.
3975 * In case neither variable is set, this function will fall back to
3976 * using the dirname portion of argv[0], possibly removing ".libs".
3977 * This allows for casual running of tests directly from the commandline
3978 * in the srcdir == builddir case and should also support running of
3979 * installed tests, assuming the data files have been installed in the
3980 * same relative path as the test binary.
3982 * Returns: the path of the file, to be freed using g_free()
3988 * @G_TEST_DIST: a file that was included in the distribution tarball
3989 * @G_TEST_BUILT: a file that was built on the compiling machine
3991 * The type of file to return the filename for, when used with
3992 * g_test_build_filename().
3994 * These two options correspond rather directly to the 'dist' and
3995 * 'built' terminology that automake uses and are explicitly used to
3996 * distinguish between the 'srcdir' and 'builddir' being separate. All
3997 * files in your project should either be dist (in the
3998 * `EXTRA_DIST` or `dist_schema_DATA`
3999 * sense, in which case they will always be in the srcdir) or built (in
4000 * the `BUILT_SOURCES` sense, in which case they will
4001 * always be in the builddir).
4003 * Note: as a general rule of automake, files that are generated only as
4004 * part of the build-from-git process (but then are distributed with the
4005 * tarball) always go in srcdir (even if doing a srcdir != builddir
4006 * build from git) and are considered as distributed files.
4011 g_test_build_filename (GTestFileType file_type,
4012 const gchar *first_path,
4018 g_assert (g_test_initialized ());
4020 va_start (ap, first_path);
4021 result = g_test_build_filename_va (file_type, first_path, ap);
4029 * @file_type: the type of file (built vs. distributed)
4031 * Gets the pathname of the directory containing test files of the type
4032 * specified by @file_type.
4034 * This is approximately the same as calling g_test_build_filename("."),
4035 * but you don't need to free the return value.
4037 * Returns: (type filename): the path of the directory, owned by GLib
4042 g_test_get_dir (GTestFileType file_type)
4044 g_assert (g_test_initialized ());
4046 if (file_type == G_TEST_DIST)
4047 return test_disted_files_dir;
4048 else if (file_type == G_TEST_BUILT)
4049 return test_built_files_dir;
4051 g_assert_not_reached ();
4055 * g_test_get_filename:
4056 * @file_type: the type of file (built vs. distributed)
4057 * @first_path: the first segment of the pathname
4058 * @...: %NULL-terminated additional path segments
4060 * Gets the pathname to a data file that is required for a test.
4062 * This is the same as g_test_build_filename() with two differences.
4063 * The first difference is that must only use this function from within
4064 * a testcase function. The second difference is that you need not free
4065 * the return value -- it will be automatically freed when the testcase
4068 * It is safe to use this function from a thread inside of a testcase
4069 * but you must ensure that all such uses occur before the main testcase
4070 * function returns (ie: it is best to ensure that all threads have been
4073 * Returns: the path, automatically freed at the end of the testcase
4078 g_test_get_filename (GTestFileType file_type,
4079 const gchar *first_path,
4086 g_assert (g_test_initialized ());
4087 if (test_filename_free_list == NULL)
4088 g_error ("g_test_get_filename() can only be used within testcase functions");
4090 va_start (ap, first_path);
4091 result = g_test_build_filename_va (file_type, first_path, ap);
4094 node = g_slist_prepend (NULL, result);
4096 node->next = *test_filename_free_list;
4097 while (!g_atomic_pointer_compare_and_exchange (test_filename_free_list, node->next, node));