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>
30 #include <glib/gstdio.h>
35 #ifdef HAVE_SYS_RESOURCE_H
36 #include <sys/resource.h>
44 #ifdef HAVE_SYS_SELECT_H
45 #include <sys/select.h>
46 #endif /* HAVE_SYS_SELECT_H */
51 #include "gstrfuncs.h"
55 #include "glib-private.h"
61 * @short_description: a test framework
62 * @see_also: [gtester][gtester], [gtester-report][gtester-report]
64 * GLib provides a framework for writing and maintaining unit tests
65 * in parallel to the code they are testing. The API is designed according
66 * to established concepts found in the other test frameworks (JUnit, NUnit,
67 * RUnit), which in turn is based on smalltalk unit testing concepts.
69 * - Test case: Tests (test methods) are grouped together with their
70 * fixture into test cases.
72 * - Fixture: A test fixture consists of fixture data and setup and
73 * teardown methods to establish the environment for the test
74 * functions. We use fresh fixtures, i.e. fixtures are newly set
75 * up and torn down around each test invocation to avoid dependencies
78 * - Test suite: Test cases can be grouped into test suites, to allow
79 * subsets of the available tests to be run. Test suites can be
80 * grouped into other test suites as well.
82 * The API is designed to handle creation and registration of test suites
83 * and test cases implicitly. A simple call like
84 * |[<!-- language="C" -->
85 * g_test_add_func ("/misc/assertions", test_assertions);
87 * creates a test suite called "misc" with a single test case named
88 * "assertions", which consists of running the test_assertions function.
90 * In addition to the traditional g_assert(), the test framework provides
91 * an extended set of assertions for comparisons: g_assert_cmpfloat(),
92 * g_assert_cmpint(), g_assert_cmpuint(), g_assert_cmphex(),
93 * g_assert_cmpstr(), and g_assert_cmpmem(). The advantage of these
94 * variants over plain g_assert() is that the assertion messages can be
95 * more elaborate, and include the values of the compared entities.
97 * A full example of creating a test suite with two tests using fixtures:
98 * |[<!-- language="C" -->
100 * #include <locale.h>
104 * OtherObject *helper;
108 * my_object_fixture_set_up (MyObjectFixture *fixture,
109 * gconstpointer user_data)
111 * fixture->obj = my_object_new ();
112 * my_object_set_prop1 (fixture->obj, "some-value");
113 * my_object_do_some_complex_setup (fixture->obj, user_data);
115 * fixture->helper = other_object_new ();
119 * my_object_fixture_tear_down (MyObjectFixture *fixture,
120 * gconstpointer user_data)
122 * g_clear_object (&fixture->helper);
123 * g_clear_object (&fixture->obj);
127 * test_my_object_test1 (MyObjectFixture *fixture,
128 * gconstpointer user_data)
130 * g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "initial-value");
134 * test_my_object_test2 (MyObjectFixture *fixture,
135 * gconstpointer user_data)
137 * my_object_do_some_work_using_helper (fixture->obj, fixture->helper);
138 * g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "updated-value");
142 * main (int argc, char *argv[])
144 * setlocale (LC_ALL, "");
146 * g_test_init (&argc, &argv, NULL);
147 * g_test_bug_base ("http://bugzilla.gnome.org/show_bug.cgi?id=");
149 * // Define the tests.
150 * g_test_add ("/my-object/test1", MyObjectFixture, "some-user-data",
151 * my_object_fixture_set_up, test_my_object_test1,
152 * my_object_fixture_tear_down);
153 * g_test_add ("/my-object/test2", MyObjectFixture, "some-user-data",
154 * my_object_fixture_set_up, test_my_object_test2,
155 * my_object_fixture_tear_down);
157 * return g_test_run ();
161 * ### Integrating GTest in your project
163 * If you are using the [Meson](http://mesonbuild.com) build system, you will
164 * typically use the provided `test()` primitive to call the test binaries,
167 * |[<!-- language="plain" -->
170 * executable('foo', 'foo.c', dependencies: deps),
172 * 'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
173 * 'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
179 * executable('bar', 'bar.c', dependencies: deps),
181 * 'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
182 * 'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
187 * If you are using Autotools, you're strongly encouraged to use the Automake
188 * [TAP](https://testanything.org/) harness; GLib provides template files for
189 * easily integrating with it:
191 * - [glib-tap.mk](https://git.gnome.org/browse/glib/tree/glib-tap.mk)
192 * - [tap-test](https://git.gnome.org/browse/glib/tree/tap-test)
193 * - [tap-driver.sh](https://git.gnome.org/browse/glib/tree/tap-driver.sh)
195 * You can copy these files in your own project's root directory, and then
196 * set up your `Makefile.am` file to reference them, for instance:
198 * |[<!-- language="plain" -->
199 * include $(top_srcdir)/glib-tap.mk
206 * # data distributed in the tarball
211 * # data not distributed in the tarball
216 * Make sure to distribute the TAP files, using something like the following
217 * in your top-level `Makefile.am`:
219 * |[<!-- language="plain" -->
225 * `glib-tap.mk` will be distributed implicitly due to being included in a
226 * `Makefile.am`. All three files should be added to version control.
228 * If you don't have access to the Autotools TAP harness, you can use the
229 * [gtester][gtester] and [gtester-report][gtester-report] tools, and use
230 * the [glib.mk](https://git.gnome.org/browse/glib/tree/glib.mk) Automake
231 * template provided by GLib.
235 * g_test_initialized:
237 * Returns %TRUE if g_test_init() has been called.
239 * Returns: %TRUE if g_test_init() has been called.
247 * Returns %TRUE if tests are run in quick mode.
248 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
249 * there is no "medium speed".
251 * By default, tests are run in quick mode. In tests that use
252 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
253 * can be used to change this.
255 * Returns: %TRUE if in quick mode
261 * Returns %TRUE if tests are run in slow mode.
262 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
263 * there is no "medium speed".
265 * By default, tests are run in quick mode. In tests that use
266 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
267 * can be used to change this.
269 * Returns: the opposite of g_test_quick()
275 * Returns %TRUE if tests are run in thorough mode, equivalent to
278 * By default, tests are run in quick mode. In tests that use
279 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
280 * can be used to change this.
282 * Returns: the same thing as g_test_slow()
288 * Returns %TRUE if tests are run in performance mode.
290 * By default, tests are run in quick mode. In tests that use
291 * g_test_init(), the option `-m perf` enables performance tests, while
292 * `-m quick` disables them.
294 * Returns: %TRUE if in performance mode
300 * Returns %TRUE if tests may provoke assertions and other formally-undefined
301 * behaviour, to verify that appropriate warnings are given. It might, in some
302 * cases, be useful to turn this off with if running tests under valgrind;
303 * in tests that use g_test_init(), the option `-m no-undefined` disables
304 * those tests, while `-m undefined` explicitly enables them (the default
307 * Returns: %TRUE if tests may provoke programming errors
313 * Returns %TRUE if tests are run in verbose mode.
314 * In tests that use g_test_init(), the option `--verbose` enables this,
315 * while `-q` or `--quiet` disables it.
316 * The default is neither g_test_verbose() nor g_test_quiet().
318 * Returns: %TRUE if in verbose mode
324 * Returns %TRUE if tests are run in quiet mode.
325 * In tests that use g_test_init(), the option `-q` or `--quiet` enables
326 * this, while `--verbose` disables it.
327 * The default is neither g_test_verbose() nor g_test_quiet().
329 * Returns: %TRUE if in quiet mode
333 * g_test_queue_unref:
334 * @gobject: the object to unref
336 * Enqueue an object to be released with g_object_unref() during
337 * the next teardown phase. This is equivalent to calling
338 * g_test_queue_destroy() with a destroy callback of g_object_unref().
345 * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
346 * `/dev/null` so it cannot be observed on the console during test
347 * runs. The actual output is still captured though to allow later
348 * tests with g_test_trap_assert_stdout().
349 * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
350 * `/dev/null` so it cannot be observed on the console during test
351 * runs. The actual output is still captured though to allow later
352 * tests with g_test_trap_assert_stderr().
353 * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
354 * child process is shared with stdin of its parent process.
355 * It is redirected to `/dev/null` otherwise.
357 * Test traps are guards around forked tests.
358 * These flags determine what traps to set.
360 * Deprecated: #GTestTrapFlags is used only with g_test_trap_fork(),
361 * which is deprecated. g_test_trap_subprocess() uses
362 * #GTestSubprocessFlags.
366 * GTestSubprocessFlags:
367 * @G_TEST_SUBPROCESS_INHERIT_STDIN: If this flag is given, the child
368 * process will inherit the parent's stdin. Otherwise, the child's
369 * stdin is redirected to `/dev/null`.
370 * @G_TEST_SUBPROCESS_INHERIT_STDOUT: If this flag is given, the child
371 * process will inherit the parent's stdout. Otherwise, the child's
372 * stdout will not be visible, but it will be captured to allow
373 * later tests with g_test_trap_assert_stdout().
374 * @G_TEST_SUBPROCESS_INHERIT_STDERR: If this flag is given, the child
375 * process will inherit the parent's stderr. Otherwise, the child's
376 * stderr will not be visible, but it will be captured to allow
377 * later tests with g_test_trap_assert_stderr().
379 * Flags to pass to g_test_trap_subprocess() to control input and output.
381 * Note that in contrast with g_test_trap_fork(), the default is to
382 * not show stdout and stderr.
386 * g_test_trap_assert_passed:
388 * Assert that the last test subprocess passed.
389 * See g_test_trap_subprocess().
395 * g_test_trap_assert_failed:
397 * Assert that the last test subprocess failed.
398 * See g_test_trap_subprocess().
400 * This is sometimes used to test situations that are formally considered to
401 * be undefined behaviour, like inputs that fail a g_return_if_fail()
402 * check. In these situations you should skip the entire test, including the
403 * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
404 * to indicate that undefined behaviour may be tested.
410 * g_test_trap_assert_stdout:
411 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
413 * Assert that the stdout output of the last test subprocess matches
414 * @soutpattern. See g_test_trap_subprocess().
420 * g_test_trap_assert_stdout_unmatched:
421 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
423 * Assert that the stdout output of the last test subprocess
424 * does not match @soutpattern. See g_test_trap_subprocess().
430 * g_test_trap_assert_stderr:
431 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
433 * Assert that the stderr output of the last test subprocess
434 * matches @serrpattern. See g_test_trap_subprocess().
436 * This is sometimes used to test situations that are formally
437 * considered to be undefined behaviour, like code that hits a
438 * g_assert() or g_error(). In these situations you should skip the
439 * entire test, including the call to g_test_trap_subprocess(), unless
440 * g_test_undefined() returns %TRUE to indicate that undefined
441 * behaviour may be tested.
447 * g_test_trap_assert_stderr_unmatched:
448 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
450 * Assert that the stderr output of the last test subprocess
451 * does not match @serrpattern. See g_test_trap_subprocess().
459 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
460 * for details on test case random numbers.
467 * @expr: the expression to check
469 * Debugging macro to terminate the application if the assertion
470 * fails. If the assertion fails (i.e. the expression is not true),
471 * an error message is logged and the application is terminated.
473 * The macro can be turned off in final releases of code by defining
474 * `G_DISABLE_ASSERT` when compiling the application, so code must
475 * not depend on any side effects from @expr.
479 * g_assert_not_reached:
481 * Debugging macro to terminate the application if it is ever
482 * reached. If it is reached, an error message is logged and the
483 * application is terminated.
485 * The macro can be turned off in final releases of code by defining
486 * `G_DISABLE_ASSERT` when compiling the application.
491 * @expr: the expression to check
493 * Debugging macro to check that an expression is true.
495 * If the assertion fails (i.e. the expression is not true),
496 * an error message is logged and the application is either
497 * terminated or the testcase marked as failed.
499 * See g_test_set_nonfatal_assertions().
506 * @expr: the expression to check
508 * Debugging macro to check an expression is false.
510 * If the assertion fails (i.e. the expression is not false),
511 * an error message is logged and the application is either
512 * terminated or the testcase marked as failed.
514 * See g_test_set_nonfatal_assertions().
521 * @expr: the expression to check
523 * Debugging macro to check an expression is %NULL.
525 * If the assertion fails (i.e. the expression is not %NULL),
526 * an error message is logged and the application is either
527 * terminated or the testcase marked as failed.
529 * See g_test_set_nonfatal_assertions().
536 * @expr: the expression to check
538 * Debugging macro to check an expression is not %NULL.
540 * If the assertion fails (i.e. the expression is %NULL),
541 * an error message is logged and the application is either
542 * terminated or the testcase marked as failed.
544 * See g_test_set_nonfatal_assertions().
551 * @s1: a string (may be %NULL)
552 * @cmp: The comparison operator to use.
553 * One of ==, !=, <, >, <=, >=.
554 * @s2: another string (may be %NULL)
556 * Debugging macro to compare two strings. If the comparison fails,
557 * an error message is logged and the application is either terminated
558 * or the testcase marked as failed.
559 * The strings are compared using g_strcmp0().
561 * The effect of `g_assert_cmpstr (s1, op, s2)` is
562 * the same as `g_assert_true (g_strcmp0 (s1, s2) op 0)`.
563 * The advantage of this macro is that it can produce a message that
564 * includes the actual values of @s1 and @s2.
566 * |[<!-- language="C" -->
567 * g_assert_cmpstr (mystring, ==, "fubar");
576 * @cmp: The comparison operator to use.
577 * One of ==, !=, <, >, <=, >=.
578 * @n2: another integer
580 * Debugging macro to compare two integers.
582 * The effect of `g_assert_cmpint (n1, op, n2)` is
583 * the same as `g_assert_true (n1 op n2)`. The advantage
584 * of this macro is that it can produce a message that includes the
585 * actual values of @n1 and @n2.
592 * @n1: an unsigned integer
593 * @cmp: The comparison operator to use.
594 * One of ==, !=, <, >, <=, >=.
595 * @n2: another unsigned integer
597 * Debugging macro to compare two unsigned integers.
599 * The effect of `g_assert_cmpuint (n1, op, n2)` is
600 * the same as `g_assert_true (n1 op n2)`. The advantage
601 * of this macro is that it can produce a message that includes the
602 * actual values of @n1 and @n2.
609 * @n1: an unsigned integer
610 * @cmp: The comparison operator to use.
611 * One of ==, !=, <, >, <=, >=.
612 * @n2: another unsigned integer
614 * Debugging macro to compare to unsigned integers.
616 * This is a variant of g_assert_cmpuint() that displays the numbers
617 * in hexadecimal notation in the message.
624 * @n1: an floating point number
625 * @cmp: The comparison operator to use.
626 * One of ==, !=, <, >, <=, >=.
627 * @n2: another floating point number
629 * Debugging macro to compare two floating point numbers.
631 * The effect of `g_assert_cmpfloat (n1, op, n2)` is
632 * the same as `g_assert_true (n1 op n2)`. The advantage
633 * of this macro is that it can produce a message that includes the
634 * actual values of @n1 and @n2.
641 * @m1: pointer to a buffer
643 * @m2: pointer to another buffer
646 * Debugging macro to compare memory regions. If the comparison fails,
647 * an error message is logged and the application is either terminated
648 * or the testcase marked as failed.
650 * The effect of `g_assert_cmpmem (m1, l1, m2, l2)` is
651 * the same as `g_assert_true (l1 == l2 && memcmp (m1, m2, l1) == 0)`.
652 * The advantage of this macro is that it can produce a message that
653 * includes the actual values of @l1 and @l2.
655 * |[<!-- language="C" -->
656 * g_assert_cmpmem (buf->data, buf->len, expected, sizeof (expected));
664 * @err: a #GError, possibly %NULL
666 * Debugging macro to check that a #GError is not set.
668 * The effect of `g_assert_no_error (err)` is
669 * the same as `g_assert_true (err == NULL)`. The advantage
670 * of this macro is that it can produce a message that includes
671 * the error message and code.
678 * @err: a #GError, possibly %NULL
679 * @dom: the expected error domain (a #GQuark)
680 * @c: the expected error code
682 * Debugging macro to check that a method has returned
683 * the correct #GError.
685 * The effect of `g_assert_error (err, dom, c)` is
686 * the same as `g_assert_true (err != NULL && err->domain
687 * == dom && err->code == c)`. The advantage of this
688 * macro is that it can produce a message that includes the incorrect
689 * error message and code.
691 * This can only be used to test for a specific error. If you want to
692 * test that @err is set, but don't care what it's set to, just use
693 * `g_assert (err != NULL)`
701 * An opaque structure representing a test case.
707 * An opaque structure representing a test suite.
711 /* Global variable for storing assertion messages; this is the counterpart to
712 * glibc's (private) __abort_msg variable, and allows developers and crash
713 * analysis systems like Apport and ABRT to fish out assertion messages from
714 * core dumps, instead of having to catch them on screen output.
716 GLIB_VAR
char *__glib_assert_msg
;
717 char *__glib_assert_msg
= NULL
;
719 /* --- constants --- */
720 #define G_TEST_STATUS_TIMED_OUT 1024
722 /* --- structures --- */
727 void (*fixture_setup
) (void*, gconstpointer
);
728 void (*fixture_test
) (void*, gconstpointer
);
729 void (*fixture_teardown
) (void*, gconstpointer
);
738 typedef struct DestroyEntry DestroyEntry
;
742 GDestroyNotify destroy_func
;
743 gpointer destroy_data
;
746 /* --- prototypes --- */
747 static void test_run_seed (const gchar
*rseed
);
748 static void test_trap_clear (void);
749 static guint8
* g_test_log_dump (GTestLogMsg
*msg
,
751 static void gtest_default_log_handler (const gchar
*log_domain
,
752 GLogLevelFlags log_level
,
753 const gchar
*message
,
754 gpointer unused_data
);
757 static const char * const g_test_result_names
[] = {
764 /* --- variables --- */
765 static int test_log_fd
= -1;
766 static gboolean test_mode_fatal
= TRUE
;
767 static gboolean g_test_run_once
= TRUE
;
768 static gboolean test_run_list
= FALSE
;
769 static gchar
*test_run_seedstr
= NULL
;
770 static GRand
*test_run_rand
= NULL
;
771 static gchar
*test_run_name
= "";
772 static GSList
**test_filename_free_list
;
773 static guint test_run_forks
= 0;
774 static guint test_run_count
= 0;
775 static guint test_count
= 0;
776 static guint test_skipped_count
= 0;
777 static GTestResult test_run_success
= G_TEST_RUN_FAILURE
;
778 static gchar
*test_run_msg
= NULL
;
779 static guint test_startup_skip_count
= 0;
780 static GTimer
*test_user_timer
= NULL
;
781 static double test_user_stamp
= 0;
782 static GSList
*test_paths
= NULL
;
783 static GSList
*test_paths_skipped
= NULL
;
784 static GTestSuite
*test_suite_root
= NULL
;
785 static int test_trap_last_status
= 0; /* unmodified platform-specific status */
786 static GPid test_trap_last_pid
= 0;
787 static char *test_trap_last_subprocess
= NULL
;
788 static char *test_trap_last_stdout
= NULL
;
789 static char *test_trap_last_stderr
= NULL
;
790 static char *test_uri_base
= NULL
;
791 static gboolean test_debug_log
= FALSE
;
792 static gboolean test_tap_log
= FALSE
;
793 static gboolean test_nonfatal_assertions
= FALSE
;
794 static DestroyEntry
*test_destroy_queue
= NULL
;
795 static char *test_argv0
= NULL
;
796 static char *test_argv0_dirname
;
797 static const char *test_disted_files_dir
;
798 static const char *test_built_files_dir
;
799 static char *test_initial_cwd
= NULL
;
800 static gboolean test_in_forked_child
= FALSE
;
801 static gboolean test_in_subprocess
= FALSE
;
802 static GTestConfig mutable_test_config_vars
= {
803 FALSE
, /* test_initialized */
804 TRUE
, /* test_quick */
805 FALSE
, /* test_perf */
806 FALSE
, /* test_verbose */
807 FALSE
, /* test_quiet */
808 TRUE
, /* test_undefined */
810 const GTestConfig
* const g_test_config_vars
= &mutable_test_config_vars
;
811 static gboolean no_g_set_prgname
= FALSE
;
813 /* --- functions --- */
815 g_test_log_type_name (GTestLogType log_type
)
819 case G_TEST_LOG_NONE
: return "none";
820 case G_TEST_LOG_ERROR
: return "error";
821 case G_TEST_LOG_START_BINARY
: return "binary";
822 case G_TEST_LOG_LIST_CASE
: return "list";
823 case G_TEST_LOG_SKIP_CASE
: return "skip";
824 case G_TEST_LOG_START_CASE
: return "start";
825 case G_TEST_LOG_STOP_CASE
: return "stop";
826 case G_TEST_LOG_MIN_RESULT
: return "minperf";
827 case G_TEST_LOG_MAX_RESULT
: return "maxperf";
828 case G_TEST_LOG_MESSAGE
: return "message";
829 case G_TEST_LOG_START_SUITE
: return "start suite";
830 case G_TEST_LOG_STOP_SUITE
: return "stop suite";
836 g_test_log_send (guint n_bytes
,
837 const guint8
*buffer
)
839 if (test_log_fd
>= 0)
843 r
= write (test_log_fd
, buffer
, n_bytes
);
844 while (r
< 0 && errno
== EINTR
);
848 GTestLogBuffer
*lbuffer
= g_test_log_buffer_new ();
851 g_test_log_buffer_push (lbuffer
, n_bytes
, buffer
);
852 msg
= g_test_log_buffer_pop (lbuffer
);
853 g_warn_if_fail (msg
!= NULL
);
854 g_warn_if_fail (lbuffer
->data
->len
== 0);
855 g_test_log_buffer_free (lbuffer
);
857 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg
->log_type
));
858 for (ui
= 0; ui
< msg
->n_strings
; ui
++)
859 g_printerr (":{%s}", msg
->strings
[ui
]);
863 for (ui
= 0; ui
< msg
->n_nums
; ui
++)
865 if ((long double) (long) msg
->nums
[ui
] == msg
->nums
[ui
])
866 g_printerr ("%s%ld", ui
? ";" : "", (long) msg
->nums
[ui
]);
868 g_printerr ("%s%.16g", ui
? ";" : "", (double) msg
->nums
[ui
]);
872 g_printerr (":LOG*}\n");
873 g_test_log_msg_free (msg
);
878 g_test_log (GTestLogType lbit
,
879 const gchar
*string1
,
880 const gchar
*string2
,
887 gchar
*astrings
[3] = { NULL
, NULL
, NULL
};
893 case G_TEST_LOG_START_BINARY
:
895 g_print ("# random seed: %s\n", string2
);
896 else if (g_test_verbose ())
897 g_print ("GTest: random seed: %s\n", string2
);
899 case G_TEST_LOG_START_SUITE
:
903 g_print ("# Start of %s tests\n", string1
);
905 g_print ("1..%d\n", test_count
);
908 case G_TEST_LOG_STOP_SUITE
:
912 g_print ("# End of %s tests\n", string1
);
915 case G_TEST_LOG_STOP_CASE
:
917 fail
= result
== G_TEST_RUN_FAILURE
;
920 g_print ("%s %d %s", fail
? "not ok" : "ok", test_run_count
, string1
);
921 if (result
== G_TEST_RUN_INCOMPLETE
)
922 g_print (" # TODO %s\n", string2
? string2
: "");
923 else if (result
== G_TEST_RUN_SKIPPED
)
924 g_print (" # SKIP %s\n", string2
? string2
: "");
928 else if (g_test_verbose ())
929 g_print ("GTest: result: %s\n", g_test_result_names
[result
]);
930 else if (!g_test_quiet ())
931 g_print ("%s\n", g_test_result_names
[result
]);
932 if (fail
&& test_mode_fatal
)
935 g_print ("Bail out!\n");
938 if (result
== G_TEST_RUN_SKIPPED
)
939 test_skipped_count
++;
941 case G_TEST_LOG_MIN_RESULT
:
943 g_print ("# min perf: %s\n", string1
);
944 else if (g_test_verbose ())
945 g_print ("(MINPERF:%s)\n", string1
);
947 case G_TEST_LOG_MAX_RESULT
:
949 g_print ("# max perf: %s\n", string1
);
950 else if (g_test_verbose ())
951 g_print ("(MAXPERF:%s)\n", string1
);
953 case G_TEST_LOG_MESSAGE
:
955 g_print ("# %s\n", string1
);
956 else if (g_test_verbose ())
957 g_print ("(MSG: %s)\n", string1
);
959 case G_TEST_LOG_ERROR
:
961 g_print ("Bail out! %s\n", string1
);
962 else if (g_test_verbose ())
963 g_print ("(ERROR: %s)\n", string1
);
969 msg
.n_strings
= (string1
!= NULL
) + (string1
&& string2
);
970 msg
.strings
= astrings
;
971 astrings
[0] = (gchar
*) string1
;
972 astrings
[1] = astrings
[0] ? (gchar
*) string2
: NULL
;
975 dbuffer
= g_test_log_dump (&msg
, &dbufferlen
);
976 g_test_log_send (dbufferlen
, dbuffer
);
981 case G_TEST_LOG_START_CASE
:
984 else if (g_test_verbose ())
985 g_print ("GTest: run: %s\n", string1
);
986 else if (!g_test_quiet ())
987 g_print ("%s: ", string1
);
993 /* We intentionally parse the command line without GOptionContext
994 * because otherwise you would never be able to test it.
997 parse_args (gint
*argc_p
,
1000 guint argc
= *argc_p
;
1001 gchar
**argv
= *argv_p
;
1004 test_argv0
= argv
[0];
1005 test_initial_cwd
= g_get_current_dir ();
1007 /* parse known args */
1008 for (i
= 1; i
< argc
; i
++)
1010 if (strcmp (argv
[i
], "--g-fatal-warnings") == 0)
1012 GLogLevelFlags fatal_mask
= (GLogLevelFlags
) g_log_set_always_fatal ((GLogLevelFlags
) G_LOG_FATAL_MASK
);
1013 fatal_mask
= (GLogLevelFlags
) (fatal_mask
| G_LOG_LEVEL_WARNING
| G_LOG_LEVEL_CRITICAL
);
1014 g_log_set_always_fatal (fatal_mask
);
1017 else if (strcmp (argv
[i
], "--keep-going") == 0 ||
1018 strcmp (argv
[i
], "-k") == 0)
1020 test_mode_fatal
= FALSE
;
1023 else if (strcmp (argv
[i
], "--debug-log") == 0)
1025 test_debug_log
= TRUE
;
1028 else if (strcmp (argv
[i
], "--tap") == 0)
1030 test_tap_log
= TRUE
;
1033 else if (strcmp ("--GTestLogFD", argv
[i
]) == 0 || strncmp ("--GTestLogFD=", argv
[i
], 13) == 0)
1035 gchar
*equal
= argv
[i
] + 12;
1037 test_log_fd
= g_ascii_strtoull (equal
+ 1, NULL
, 0);
1038 else if (i
+ 1 < argc
)
1041 test_log_fd
= g_ascii_strtoull (argv
[i
], NULL
, 0);
1045 else if (strcmp ("--GTestSkipCount", argv
[i
]) == 0 || strncmp ("--GTestSkipCount=", argv
[i
], 17) == 0)
1047 gchar
*equal
= argv
[i
] + 16;
1049 test_startup_skip_count
= g_ascii_strtoull (equal
+ 1, NULL
, 0);
1050 else if (i
+ 1 < argc
)
1053 test_startup_skip_count
= g_ascii_strtoull (argv
[i
], NULL
, 0);
1057 else if (strcmp ("--GTestSubprocess", argv
[i
]) == 0)
1059 test_in_subprocess
= TRUE
;
1060 /* We typically expect these child processes to crash, and some
1061 * tests spawn a *lot* of them. Avoid spamming system crash
1062 * collection programs such as systemd-coredump and abrt.
1064 #ifdef HAVE_SYS_RESOURCE_H
1066 struct rlimit limit
= { 0, 0 };
1067 (void) setrlimit (RLIMIT_CORE
, &limit
);
1072 else if (strcmp ("-p", argv
[i
]) == 0 || strncmp ("-p=", argv
[i
], 3) == 0)
1074 gchar
*equal
= argv
[i
] + 2;
1076 test_paths
= g_slist_prepend (test_paths
, equal
+ 1);
1077 else if (i
+ 1 < argc
)
1080 test_paths
= g_slist_prepend (test_paths
, argv
[i
]);
1084 else if (strcmp ("-s", argv
[i
]) == 0 || strncmp ("-s=", argv
[i
], 3) == 0)
1086 gchar
*equal
= argv
[i
] + 2;
1088 test_paths_skipped
= g_slist_prepend (test_paths_skipped
, equal
+ 1);
1089 else if (i
+ 1 < argc
)
1092 test_paths_skipped
= g_slist_prepend (test_paths_skipped
, argv
[i
]);
1096 else if (strcmp ("-m", argv
[i
]) == 0 || strncmp ("-m=", argv
[i
], 3) == 0)
1098 gchar
*equal
= argv
[i
] + 2;
1099 const gchar
*mode
= "";
1102 else if (i
+ 1 < argc
)
1107 if (strcmp (mode
, "perf") == 0)
1108 mutable_test_config_vars
.test_perf
= TRUE
;
1109 else if (strcmp (mode
, "slow") == 0)
1110 mutable_test_config_vars
.test_quick
= FALSE
;
1111 else if (strcmp (mode
, "thorough") == 0)
1112 mutable_test_config_vars
.test_quick
= FALSE
;
1113 else if (strcmp (mode
, "quick") == 0)
1115 mutable_test_config_vars
.test_quick
= TRUE
;
1116 mutable_test_config_vars
.test_perf
= FALSE
;
1118 else if (strcmp (mode
, "undefined") == 0)
1119 mutable_test_config_vars
.test_undefined
= TRUE
;
1120 else if (strcmp (mode
, "no-undefined") == 0)
1121 mutable_test_config_vars
.test_undefined
= FALSE
;
1123 g_error ("unknown test mode: -m %s", mode
);
1126 else if (strcmp ("-q", argv
[i
]) == 0 || strcmp ("--quiet", argv
[i
]) == 0)
1128 mutable_test_config_vars
.test_quiet
= TRUE
;
1129 mutable_test_config_vars
.test_verbose
= FALSE
;
1132 else if (strcmp ("--verbose", argv
[i
]) == 0)
1134 mutable_test_config_vars
.test_quiet
= FALSE
;
1135 mutable_test_config_vars
.test_verbose
= TRUE
;
1138 else if (strcmp ("-l", argv
[i
]) == 0)
1140 test_run_list
= TRUE
;
1143 else if (strcmp ("--seed", argv
[i
]) == 0 || strncmp ("--seed=", argv
[i
], 7) == 0)
1145 gchar
*equal
= argv
[i
] + 6;
1147 test_run_seedstr
= equal
+ 1;
1148 else if (i
+ 1 < argc
)
1151 test_run_seedstr
= argv
[i
];
1155 else if (strcmp ("-?", argv
[i
]) == 0 ||
1156 strcmp ("-h", argv
[i
]) == 0 ||
1157 strcmp ("--help", argv
[i
]) == 0)
1160 " %s [OPTION...]\n\n"
1162 " -h, --help Show help options\n\n"
1164 " --g-fatal-warnings Make all warnings fatal\n"
1165 " -l List test cases available in a test executable\n"
1166 " -m {perf|slow|thorough|quick} Execute tests according to mode\n"
1167 " -m {undefined|no-undefined} Execute tests according to mode\n"
1168 " -p TESTPATH Only start test cases matching TESTPATH\n"
1169 " -s TESTPATH Skip all tests matching TESTPATH\n"
1170 " --seed=SEEDSTRING Start tests with random seed SEEDSTRING\n"
1171 " --debug-log debug test logging output\n"
1172 " -q, --quiet Run tests quietly\n"
1173 " --verbose Run tests verbosely\n",
1180 for (i
= 1; i
< argc
; i
++)
1183 argv
[e
++] = argv
[i
];
1192 * @argc: Address of the @argc parameter of the main() function.
1193 * Changed if any arguments were handled.
1194 * @argv: Address of the @argv parameter of main().
1195 * Any parameters understood by g_test_init() stripped before return.
1196 * @...: %NULL-terminated list of special options. Currently the only
1197 * defined option is `"no_g_set_prgname"`, which
1198 * will cause g_test_init() to not call g_set_prgname().
1200 * Initialize the GLib testing framework, e.g. by seeding the
1201 * test random number generator, the name for g_get_prgname()
1202 * and parsing test related command line args.
1204 * So far, the following arguments are understood:
1206 * - `-l`: List test cases available in a test executable.
1207 * - `--seed=SEED`: Provide a random seed to reproduce test
1208 * runs using random numbers.
1209 * - `--verbose`: Run tests verbosely.
1210 * - `-q`, `--quiet`: Run tests quietly.
1211 * - `-p PATH`: Execute all tests matching the given path.
1212 * - `-s PATH`: Skip all tests matching the given path.
1213 * This can also be used to force a test to run that would otherwise
1214 * be skipped (ie, a test whose name contains "/subprocess").
1215 * - `-m {perf|slow|thorough|quick|undefined|no-undefined}`: Execute tests according to these test modes:
1217 * `perf`: Performance tests, may take long and report results (off by default).
1219 * `slow`, `thorough`: Slow and thorough tests, may take quite long and maximize coverage
1222 * `quick`: Quick tests, should run really quickly and give good coverage (the default).
1224 * `undefined`: Tests for undefined behaviour, may provoke programming errors
1225 * under g_test_trap_subprocess() or g_test_expect_message() to check
1226 * that appropriate assertions or warnings are given (the default).
1228 * `no-undefined`: Avoid tests for undefined behaviour
1230 * - `--debug-log`: Debug test logging output.
1235 g_test_init (int *argc
,
1239 static char seedstr
[4 + 4 * 8 + 1];
1242 /* make warnings and criticals fatal for all test programs */
1243 GLogLevelFlags fatal_mask
= (GLogLevelFlags
) g_log_set_always_fatal ((GLogLevelFlags
) G_LOG_FATAL_MASK
);
1245 fatal_mask
= (GLogLevelFlags
) (fatal_mask
| G_LOG_LEVEL_WARNING
| G_LOG_LEVEL_CRITICAL
);
1246 g_log_set_always_fatal (fatal_mask
);
1247 /* check caller args */
1248 g_return_if_fail (argc
!= NULL
);
1249 g_return_if_fail (argv
!= NULL
);
1250 g_return_if_fail (g_test_config_vars
->test_initialized
== FALSE
);
1251 mutable_test_config_vars
.test_initialized
= TRUE
;
1253 va_start (args
, argv
);
1254 while ((option
= va_arg (args
, char *)))
1256 if (g_strcmp0 (option
, "no_g_set_prgname") == 0)
1257 no_g_set_prgname
= TRUE
;
1261 /* setup random seed string */
1262 g_snprintf (seedstr
, sizeof (seedstr
), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
1263 test_run_seedstr
= seedstr
;
1265 /* parse args, sets up mode, changes seed, etc. */
1266 parse_args (argc
, argv
);
1268 if (!g_get_prgname() && !no_g_set_prgname
)
1269 g_set_prgname ((*argv
)[0]);
1274 if (test_paths
|| test_startup_skip_count
)
1276 /* Not invoking every test (even if SKIPped) breaks the "1..XX" plan */
1277 g_printerr ("%s: -p and --GTestSkipCount options are incompatible with --tap\n",
1283 /* verify GRand reliability, needed for reliable seeds */
1286 GRand
*rg
= g_rand_new_with_seed (0xc8c49fb6);
1287 guint32 t1
= g_rand_int (rg
), t2
= g_rand_int (rg
), t3
= g_rand_int (rg
), t4
= g_rand_int (rg
);
1288 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
1289 if (t1
!= 0xfab39f9b || t2
!= 0xb948fb0e || t3
!= 0x3d31be26 || t4
!= 0x43a19d66)
1290 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
1294 /* check rand seed */
1295 test_run_seed (test_run_seedstr
);
1297 /* report program start */
1298 g_log_set_default_handler (gtest_default_log_handler
, NULL
);
1299 g_test_log (G_TEST_LOG_START_BINARY
, g_get_prgname(), test_run_seedstr
, 0, NULL
);
1301 test_argv0_dirname
= g_path_get_dirname (test_argv0
);
1303 /* Make sure we get the real dirname that the test was run from */
1304 if (g_str_has_suffix (test_argv0_dirname
, "/.libs"))
1307 tmp
= g_path_get_dirname (test_argv0_dirname
);
1308 g_free (test_argv0_dirname
);
1309 test_argv0_dirname
= tmp
;
1312 test_disted_files_dir
= g_getenv ("G_TEST_SRCDIR");
1313 if (!test_disted_files_dir
)
1314 test_disted_files_dir
= test_argv0_dirname
;
1316 test_built_files_dir
= g_getenv ("G_TEST_BUILDDIR");
1317 if (!test_built_files_dir
)
1318 test_built_files_dir
= test_argv0_dirname
;
1322 test_run_seed (const gchar
*rseed
)
1324 guint seed_failed
= 0;
1326 g_rand_free (test_run_rand
);
1327 test_run_rand
= NULL
;
1328 while (strchr (" \t\v\r\n\f", *rseed
))
1330 if (strncmp (rseed
, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
1332 const char *s
= rseed
+ 4;
1333 if (strlen (s
) >= 32) /* require 4 * 8 chars */
1335 guint32 seedarray
[4];
1336 gchar
*p
, hexbuf
[9] = { 0, };
1337 memcpy (hexbuf
, s
+ 0, 8);
1338 seedarray
[0] = g_ascii_strtoull (hexbuf
, &p
, 16);
1339 seed_failed
+= p
!= NULL
&& *p
!= 0;
1340 memcpy (hexbuf
, s
+ 8, 8);
1341 seedarray
[1] = g_ascii_strtoull (hexbuf
, &p
, 16);
1342 seed_failed
+= p
!= NULL
&& *p
!= 0;
1343 memcpy (hexbuf
, s
+ 16, 8);
1344 seedarray
[2] = g_ascii_strtoull (hexbuf
, &p
, 16);
1345 seed_failed
+= p
!= NULL
&& *p
!= 0;
1346 memcpy (hexbuf
, s
+ 24, 8);
1347 seedarray
[3] = g_ascii_strtoull (hexbuf
, &p
, 16);
1348 seed_failed
+= p
!= NULL
&& *p
!= 0;
1351 test_run_rand
= g_rand_new_with_seed_array (seedarray
, 4);
1356 g_error ("Unknown or invalid random seed: %s", rseed
);
1362 * Get a reproducible random integer number.
1364 * The random numbers generated by the g_test_rand_*() family of functions
1365 * change with every new test program start, unless the --seed option is
1366 * given when starting test programs.
1368 * For individual test cases however, the random number generator is
1369 * reseeded, to avoid dependencies between tests and to make --seed
1370 * effective for all test cases.
1372 * Returns: a random number from the seeded random number generator.
1377 g_test_rand_int (void)
1379 return g_rand_int (test_run_rand
);
1383 * g_test_rand_int_range:
1384 * @begin: the minimum value returned by this function
1385 * @end: the smallest value not to be returned by this function
1387 * Get a reproducible random integer number out of a specified range,
1388 * see g_test_rand_int() for details on test case random numbers.
1390 * Returns: a number with @begin <= number < @end.
1395 g_test_rand_int_range (gint32 begin
,
1398 return g_rand_int_range (test_run_rand
, begin
, end
);
1402 * g_test_rand_double:
1404 * Get a reproducible random floating point number,
1405 * see g_test_rand_int() for details on test case random numbers.
1407 * Returns: a random number from the seeded random number generator.
1412 g_test_rand_double (void)
1414 return g_rand_double (test_run_rand
);
1418 * g_test_rand_double_range:
1419 * @range_start: the minimum value returned by this function
1420 * @range_end: the minimum value not returned by this function
1422 * Get a reproducible random floating pointer number out of a specified range,
1423 * see g_test_rand_int() for details on test case random numbers.
1425 * Returns: a number with @range_start <= number < @range_end.
1430 g_test_rand_double_range (double range_start
,
1433 return g_rand_double_range (test_run_rand
, range_start
, range_end
);
1437 * g_test_timer_start:
1439 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1440 * to be done. Call this function again to restart the timer.
1445 g_test_timer_start (void)
1447 if (!test_user_timer
)
1448 test_user_timer
= g_timer_new();
1449 test_user_stamp
= 0;
1450 g_timer_start (test_user_timer
);
1454 * g_test_timer_elapsed:
1456 * Get the time since the last start of the timer with g_test_timer_start().
1458 * Returns: the time since the last start of the timer, as a double
1463 g_test_timer_elapsed (void)
1465 test_user_stamp
= test_user_timer
? g_timer_elapsed (test_user_timer
, NULL
) : 0;
1466 return test_user_stamp
;
1470 * g_test_timer_last:
1472 * Report the last result of g_test_timer_elapsed().
1474 * Returns: the last result of g_test_timer_elapsed(), as a double
1479 g_test_timer_last (void)
1481 return test_user_stamp
;
1485 * g_test_minimized_result:
1486 * @minimized_quantity: the reported value
1487 * @format: the format string of the report message
1488 * @...: arguments to pass to the printf() function
1490 * Report the result of a performance or measurement test.
1491 * The test should generally strive to minimize the reported
1492 * quantities (smaller values are better than larger ones),
1493 * this and @minimized_quantity can determine sorting
1494 * order for test result reports.
1499 g_test_minimized_result (double minimized_quantity
,
1503 long double largs
= minimized_quantity
;
1507 va_start (args
, format
);
1508 buffer
= g_strdup_vprintf (format
, args
);
1511 g_test_log (G_TEST_LOG_MIN_RESULT
, buffer
, NULL
, 1, &largs
);
1516 * g_test_maximized_result:
1517 * @maximized_quantity: the reported value
1518 * @format: the format string of the report message
1519 * @...: arguments to pass to the printf() function
1521 * Report the result of a performance or measurement test.
1522 * The test should generally strive to maximize the reported
1523 * quantities (larger values are better than smaller ones),
1524 * this and @maximized_quantity can determine sorting
1525 * order for test result reports.
1530 g_test_maximized_result (double maximized_quantity
,
1534 long double largs
= maximized_quantity
;
1538 va_start (args
, format
);
1539 buffer
= g_strdup_vprintf (format
, args
);
1542 g_test_log (G_TEST_LOG_MAX_RESULT
, buffer
, NULL
, 1, &largs
);
1548 * @format: the format string
1549 * @...: printf-like arguments to @format
1551 * Add a message to the test report.
1556 g_test_message (const char *format
,
1562 va_start (args
, format
);
1563 buffer
= g_strdup_vprintf (format
, args
);
1566 g_test_log (G_TEST_LOG_MESSAGE
, buffer
, NULL
, 0, NULL
);
1572 * @uri_pattern: the base pattern for bug URIs
1574 * Specify the base URI for bug reports.
1576 * The base URI is used to construct bug report messages for
1577 * g_test_message() when g_test_bug() is called.
1578 * Calling this function outside of a test case sets the
1579 * default base URI for all test cases. Calling it from within
1580 * a test case changes the base URI for the scope of the test
1582 * Bug URIs are constructed by appending a bug specific URI
1583 * portion to @uri_pattern, or by replacing the special string
1584 * '\%s' within @uri_pattern if that is present.
1589 g_test_bug_base (const char *uri_pattern
)
1591 g_free (test_uri_base
);
1592 test_uri_base
= g_strdup (uri_pattern
);
1597 * @bug_uri_snippet: Bug specific bug tracker URI portion.
1599 * This function adds a message to test reports that
1600 * associates a bug URI with a test case.
1601 * Bug URIs are constructed from a base URI set with g_test_bug_base()
1602 * and @bug_uri_snippet.
1607 g_test_bug (const char *bug_uri_snippet
)
1611 g_return_if_fail (test_uri_base
!= NULL
);
1612 g_return_if_fail (bug_uri_snippet
!= NULL
);
1614 c
= strstr (test_uri_base
, "%s");
1617 char *b
= g_strndup (test_uri_base
, c
- test_uri_base
);
1618 char *s
= g_strconcat (b
, bug_uri_snippet
, c
+ 2, NULL
);
1620 g_test_message ("Bug Reference: %s", s
);
1624 g_test_message ("Bug Reference: %s%s", test_uri_base
, bug_uri_snippet
);
1630 * Get the toplevel test suite for the test path API.
1632 * Returns: the toplevel #GTestSuite
1637 g_test_get_root (void)
1639 if (!test_suite_root
)
1641 test_suite_root
= g_test_create_suite ("root");
1642 g_free (test_suite_root
->name
);
1643 test_suite_root
->name
= g_strdup ("");
1646 return test_suite_root
;
1652 * Runs all tests under the toplevel suite which can be retrieved
1653 * with g_test_get_root(). Similar to g_test_run_suite(), the test
1654 * cases to be run are filtered according to test path arguments
1655 * (`-p testpath` and `-s testpath`) as parsed by g_test_init().
1656 * g_test_run_suite() or g_test_run() may only be called once in a
1659 * In general, the tests and sub-suites within each suite are run in
1660 * the order in which they are defined. However, note that prior to
1661 * GLib 2.36, there was a bug in the `g_test_add_*`
1662 * functions which caused them to create multiple suites with the same
1663 * name, meaning that if you created tests "/foo/simple",
1664 * "/bar/simple", and "/foo/using-bar" in that order, they would get
1665 * run in that order (since g_test_run() would run the first "/foo"
1666 * suite, then the "/bar" suite, then the second "/foo" suite). As of
1667 * 2.36, this bug is fixed, and adding the tests in that order would
1668 * result in a running order of "/foo/simple", "/foo/using-bar",
1669 * "/bar/simple". If this new ordering is sub-optimal (because it puts
1670 * more-complicated tests before simpler ones, making it harder to
1671 * figure out exactly what has failed), you can fix it by changing the
1672 * test paths to group tests by suite in a way that will result in the
1673 * desired running order. Eg, "/simple/foo", "/simple/bar",
1674 * "/complex/foo-using-bar".
1676 * However, you should never make the actual result of a test depend
1677 * on the order that tests are run in. If you need to ensure that some
1678 * particular code runs before or after a given test case, use
1679 * g_test_add(), which lets you specify setup and teardown functions.
1681 * If all tests are skipped, this function will return 0 if
1682 * producing TAP output, or 77 (treated as "skip test" by Automake) otherwise.
1684 * Returns: 0 on success, 1 on failure (assuming it returns at all),
1685 * 0 or 77 if all tests were skipped with g_test_skip()
1692 if (g_test_run_suite (g_test_get_root()) != 0)
1695 /* 77 is special to Automake's default driver, but not Automake's TAP driver
1696 * or Perl's prove(1) TAP driver. */
1700 if (test_run_count
> 0 && test_run_count
== test_skipped_count
)
1707 * g_test_create_case:
1708 * @test_name: the name for the test case
1709 * @data_size: the size of the fixture data structure
1710 * @test_data: test data argument for the test functions
1711 * @data_setup: (scope async): the function to set up the fixture data
1712 * @data_test: (scope async): the actual test function
1713 * @data_teardown: (scope async): the function to teardown the fixture data
1715 * Create a new #GTestCase, named @test_name, this API is fairly
1716 * low level, calling g_test_add() or g_test_add_func() is preferable.
1717 * When this test is executed, a fixture structure of size @data_size
1718 * will be automatically allocated and filled with zeros. Then @data_setup is
1719 * called to initialize the fixture. After fixture setup, the actual test
1720 * function @data_test is called. Once the test run completes, the
1721 * fixture structure is torn down by calling @data_teardown and
1722 * after that the memory is automatically released by the test framework.
1724 * Splitting up a test run into fixture setup, test function and
1725 * fixture teardown is most useful if the same fixture is used for
1726 * multiple tests. In this cases, g_test_create_case() will be
1727 * called with the same fixture, but varying @test_name and
1728 * @data_test arguments.
1730 * Returns: a newly allocated #GTestCase.
1735 g_test_create_case (const char *test_name
,
1737 gconstpointer test_data
,
1738 GTestFixtureFunc data_setup
,
1739 GTestFixtureFunc data_test
,
1740 GTestFixtureFunc data_teardown
)
1744 g_return_val_if_fail (test_name
!= NULL
, NULL
);
1745 g_return_val_if_fail (strchr (test_name
, '/') == NULL
, NULL
);
1746 g_return_val_if_fail (test_name
[0] != 0, NULL
);
1747 g_return_val_if_fail (data_test
!= NULL
, NULL
);
1749 tc
= g_slice_new0 (GTestCase
);
1750 tc
->name
= g_strdup (test_name
);
1751 tc
->test_data
= (gpointer
) test_data
;
1752 tc
->fixture_size
= data_size
;
1753 tc
->fixture_setup
= (void*) data_setup
;
1754 tc
->fixture_test
= (void*) data_test
;
1755 tc
->fixture_teardown
= (void*) data_teardown
;
1761 find_suite (gconstpointer l
, gconstpointer s
)
1763 const GTestSuite
*suite
= l
;
1764 const gchar
*str
= s
;
1766 return strcmp (suite
->name
, str
);
1770 find_case (gconstpointer l
, gconstpointer s
)
1772 const GTestCase
*tc
= l
;
1773 const gchar
*str
= s
;
1775 return strcmp (tc
->name
, str
);
1780 * @fixture: (not nullable): the test fixture
1781 * @user_data: the data provided when registering the test
1783 * The type used for functions that operate on test fixtures. This is
1784 * used for the fixture setup and teardown functions as well as for the
1785 * testcases themselves.
1787 * @user_data is a pointer to the data that was given when registering
1790 * @fixture will be a pointer to the area of memory allocated by the
1791 * test framework, of the size requested. If the requested size was
1792 * zero then @fixture will be equal to @user_data.
1797 g_test_add_vtable (const char *testpath
,
1799 gconstpointer test_data
,
1800 GTestFixtureFunc data_setup
,
1801 GTestFixtureFunc fixture_test_func
,
1802 GTestFixtureFunc data_teardown
)
1808 g_return_if_fail (testpath
!= NULL
);
1809 g_return_if_fail (g_path_is_absolute (testpath
));
1810 g_return_if_fail (fixture_test_func
!= NULL
);
1812 suite
= g_test_get_root();
1813 segments
= g_strsplit (testpath
, "/", -1);
1814 for (ui
= 0; segments
[ui
] != NULL
; ui
++)
1816 const char *seg
= segments
[ui
];
1817 gboolean islast
= segments
[ui
+ 1] == NULL
;
1818 if (islast
&& !seg
[0])
1819 g_error ("invalid test case path: %s", testpath
);
1821 continue; /* initial or duplicate slash */
1826 l
= g_slist_find_custom (suite
->suites
, seg
, find_suite
);
1833 csuite
= g_test_create_suite (seg
);
1834 g_test_suite_add_suite (suite
, csuite
);
1842 if (g_slist_find_custom (suite
->cases
, seg
, find_case
))
1843 g_error ("duplicate test case path: %s", testpath
);
1845 tc
= g_test_create_case (seg
, data_size
, test_data
, data_setup
, fixture_test_func
, data_teardown
);
1846 g_test_suite_add (suite
, tc
);
1849 g_strfreev (segments
);
1855 * Indicates that a test failed. This function can be called
1856 * multiple times from the same test. You can use this function
1857 * if your test failed in a recoverable way.
1859 * Do not use this function if the failure of a test could cause
1860 * other tests to malfunction.
1862 * Calling this function will not stop the test from running, you
1863 * need to return from the test function yourself. So you can
1864 * produce additional diagnostic messages or even continue running
1867 * If not called from inside a test, this function does nothing.
1874 test_run_success
= G_TEST_RUN_FAILURE
;
1878 * g_test_incomplete:
1879 * @msg: (nullable): explanation
1881 * Indicates that a test failed because of some incomplete
1882 * functionality. This function can be called multiple times
1883 * from the same test.
1885 * Calling this function will not stop the test from running, you
1886 * need to return from the test function yourself. So you can
1887 * produce additional diagnostic messages or even continue running
1890 * If not called from inside a test, this function does nothing.
1895 g_test_incomplete (const gchar
*msg
)
1897 test_run_success
= G_TEST_RUN_INCOMPLETE
;
1898 g_free (test_run_msg
);
1899 test_run_msg
= g_strdup (msg
);
1904 * @msg: (nullable): explanation
1906 * Indicates that a test was skipped.
1908 * Calling this function will not stop the test from running, you
1909 * need to return from the test function yourself. So you can
1910 * produce additional diagnostic messages or even continue running
1913 * If not called from inside a test, this function does nothing.
1918 g_test_skip (const gchar
*msg
)
1920 test_run_success
= G_TEST_RUN_SKIPPED
;
1921 g_free (test_run_msg
);
1922 test_run_msg
= g_strdup (msg
);
1928 * Returns whether a test has already failed. This will
1929 * be the case when g_test_fail(), g_test_incomplete()
1930 * or g_test_skip() have been called, but also if an
1931 * assertion has failed.
1933 * This can be useful to return early from a test if
1934 * continuing after a failed assertion might be harmful.
1936 * The return value of this function is only meaningful
1937 * if it is called from inside a test function.
1939 * Returns: %TRUE if the test has failed
1944 g_test_failed (void)
1946 return test_run_success
!= G_TEST_RUN_SUCCESS
;
1950 * g_test_set_nonfatal_assertions:
1952 * Changes the behaviour of g_assert_cmpstr(), g_assert_cmpint(),
1953 * g_assert_cmpuint(), g_assert_cmphex(), g_assert_cmpfloat(),
1954 * g_assert_true(), g_assert_false(), g_assert_null(), g_assert_no_error(),
1955 * g_assert_error(), g_test_assert_expected_messages() and the various
1956 * g_test_trap_assert_*() macros to not abort to program, but instead
1957 * call g_test_fail() and continue. (This also changes the behavior of
1958 * g_test_fail() so that it will not cause the test program to abort
1959 * after completing the failed test.)
1961 * Note that the g_assert_not_reached() and g_assert() are not
1964 * This function can only be called after g_test_init().
1969 g_test_set_nonfatal_assertions (void)
1971 if (!g_test_config_vars
->test_initialized
)
1972 g_error ("g_test_set_nonfatal_assertions called without g_test_init");
1973 test_nonfatal_assertions
= TRUE
;
1974 test_mode_fatal
= FALSE
;
1980 * The type used for test case functions.
1987 * @testpath: /-separated test case path name for the test.
1988 * @test_func: (scope async): The test function to invoke for this test.
1990 * Create a new test case, similar to g_test_create_case(). However
1991 * the test is assumed to use no fixture, and test suites are automatically
1992 * created on the fly and added to the root fixture, based on the
1993 * slash-separated portions of @testpath.
1995 * If @testpath includes the component "subprocess" anywhere in it,
1996 * the test will be skipped by default, and only run if explicitly
1997 * required via the `-p` command-line option or g_test_trap_subprocess().
2002 g_test_add_func (const char *testpath
,
2003 GTestFunc test_func
)
2005 g_return_if_fail (testpath
!= NULL
);
2006 g_return_if_fail (testpath
[0] == '/');
2007 g_return_if_fail (test_func
!= NULL
);
2008 g_test_add_vtable (testpath
, 0, NULL
, NULL
, (GTestFixtureFunc
) test_func
, NULL
);
2013 * @user_data: the data provided when registering the test
2015 * The type used for test case functions that take an extra pointer
2022 * g_test_add_data_func:
2023 * @testpath: /-separated test case path name for the test.
2024 * @test_data: Test data argument for the test function.
2025 * @test_func: (scope async): The test function to invoke for this test.
2027 * Create a new test case, similar to g_test_create_case(). However
2028 * the test is assumed to use no fixture, and test suites are automatically
2029 * created on the fly and added to the root fixture, based on the
2030 * slash-separated portions of @testpath. The @test_data argument
2031 * will be passed as first argument to @test_func.
2033 * If @testpath includes the component "subprocess" anywhere in it,
2034 * the test will be skipped by default, and only run if explicitly
2035 * required via the `-p` command-line option or g_test_trap_subprocess().
2040 g_test_add_data_func (const char *testpath
,
2041 gconstpointer test_data
,
2042 GTestDataFunc test_func
)
2044 g_return_if_fail (testpath
!= NULL
);
2045 g_return_if_fail (testpath
[0] == '/');
2046 g_return_if_fail (test_func
!= NULL
);
2048 g_test_add_vtable (testpath
, 0, test_data
, NULL
, (GTestFixtureFunc
) test_func
, NULL
);
2052 * g_test_add_data_func_full:
2053 * @testpath: /-separated test case path name for the test.
2054 * @test_data: Test data argument for the test function.
2055 * @test_func: The test function to invoke for this test.
2056 * @data_free_func: #GDestroyNotify for @test_data.
2058 * Create a new test case, as with g_test_add_data_func(), but freeing
2059 * @test_data after the test run is complete.
2064 g_test_add_data_func_full (const char *testpath
,
2066 GTestDataFunc test_func
,
2067 GDestroyNotify data_free_func
)
2069 g_return_if_fail (testpath
!= NULL
);
2070 g_return_if_fail (testpath
[0] == '/');
2071 g_return_if_fail (test_func
!= NULL
);
2073 g_test_add_vtable (testpath
, 0, test_data
, NULL
,
2074 (GTestFixtureFunc
) test_func
,
2075 (GTestFixtureFunc
) data_free_func
);
2079 g_test_suite_case_exists (GTestSuite
*suite
,
2080 const char *test_path
)
2087 slash
= strchr (test_path
, '/');
2091 for (iter
= suite
->suites
; iter
; iter
= iter
->next
)
2093 GTestSuite
*child_suite
= iter
->data
;
2095 if (!strncmp (child_suite
->name
, test_path
, slash
- test_path
))
2096 if (g_test_suite_case_exists (child_suite
, slash
))
2102 for (iter
= suite
->cases
; iter
; iter
= iter
->next
)
2105 if (!strcmp (tc
->name
, test_path
))
2114 * g_test_create_suite:
2115 * @suite_name: a name for the suite
2117 * Create a new test suite with the name @suite_name.
2119 * Returns: A newly allocated #GTestSuite instance.
2124 g_test_create_suite (const char *suite_name
)
2127 g_return_val_if_fail (suite_name
!= NULL
, NULL
);
2128 g_return_val_if_fail (strchr (suite_name
, '/') == NULL
, NULL
);
2129 g_return_val_if_fail (suite_name
[0] != 0, NULL
);
2130 ts
= g_slice_new0 (GTestSuite
);
2131 ts
->name
= g_strdup (suite_name
);
2137 * @suite: a #GTestSuite
2138 * @test_case: a #GTestCase
2140 * Adds @test_case to @suite.
2145 g_test_suite_add (GTestSuite
*suite
,
2146 GTestCase
*test_case
)
2148 g_return_if_fail (suite
!= NULL
);
2149 g_return_if_fail (test_case
!= NULL
);
2151 suite
->cases
= g_slist_append (suite
->cases
, test_case
);
2155 * g_test_suite_add_suite:
2156 * @suite: a #GTestSuite
2157 * @nestedsuite: another #GTestSuite
2159 * Adds @nestedsuite to @suite.
2164 g_test_suite_add_suite (GTestSuite
*suite
,
2165 GTestSuite
*nestedsuite
)
2167 g_return_if_fail (suite
!= NULL
);
2168 g_return_if_fail (nestedsuite
!= NULL
);
2170 suite
->suites
= g_slist_append (suite
->suites
, nestedsuite
);
2174 * g_test_queue_free:
2175 * @gfree_pointer: the pointer to be stored.
2177 * Enqueue a pointer to be released with g_free() during the next
2178 * teardown phase. This is equivalent to calling g_test_queue_destroy()
2179 * with a destroy callback of g_free().
2184 g_test_queue_free (gpointer gfree_pointer
)
2187 g_test_queue_destroy (g_free
, gfree_pointer
);
2191 * g_test_queue_destroy:
2192 * @destroy_func: Destroy callback for teardown phase.
2193 * @destroy_data: Destroy callback data.
2195 * This function enqueus a callback @destroy_func to be executed
2196 * during the next test case teardown phase. This is most useful
2197 * to auto destruct allocated test resources at the end of a test run.
2198 * Resources are released in reverse queue order, that means enqueueing
2199 * callback A before callback B will cause B() to be called before
2200 * A() during teardown.
2205 g_test_queue_destroy (GDestroyNotify destroy_func
,
2206 gpointer destroy_data
)
2208 DestroyEntry
*dentry
;
2210 g_return_if_fail (destroy_func
!= NULL
);
2212 dentry
= g_slice_new0 (DestroyEntry
);
2213 dentry
->destroy_func
= destroy_func
;
2214 dentry
->destroy_data
= destroy_data
;
2215 dentry
->next
= test_destroy_queue
;
2216 test_destroy_queue
= dentry
;
2220 test_case_run (GTestCase
*tc
)
2222 gchar
*old_base
= g_strdup (test_uri_base
);
2223 GSList
**old_free_list
, *filename_free_list
= NULL
;
2224 gboolean success
= G_TEST_RUN_SUCCESS
;
2226 old_free_list
= test_filename_free_list
;
2227 test_filename_free_list
= &filename_free_list
;
2229 if (++test_run_count
<= test_startup_skip_count
)
2230 g_test_log (G_TEST_LOG_SKIP_CASE
, test_run_name
, NULL
, 0, NULL
);
2231 else if (test_run_list
)
2233 g_print ("%s\n", test_run_name
);
2234 g_test_log (G_TEST_LOG_LIST_CASE
, test_run_name
, NULL
, 0, NULL
);
2238 GTimer
*test_run_timer
= g_timer_new();
2239 long double largs
[3];
2241 g_test_log (G_TEST_LOG_START_CASE
, test_run_name
, NULL
, 0, NULL
);
2243 test_run_success
= G_TEST_RUN_SUCCESS
;
2244 g_clear_pointer (&test_run_msg
, g_free
);
2245 g_test_log_set_fatal_handler (NULL
, NULL
);
2246 if (test_paths_skipped
&& g_slist_find_custom (test_paths_skipped
, test_run_name
, (GCompareFunc
)g_strcmp0
))
2247 g_test_skip ("by request (-s option)");
2250 g_timer_start (test_run_timer
);
2251 fixture
= tc
->fixture_size
? g_malloc0 (tc
->fixture_size
) : tc
->test_data
;
2252 test_run_seed (test_run_seedstr
);
2253 if (tc
->fixture_setup
)
2254 tc
->fixture_setup (fixture
, tc
->test_data
);
2255 tc
->fixture_test (fixture
, tc
->test_data
);
2257 while (test_destroy_queue
)
2259 DestroyEntry
*dentry
= test_destroy_queue
;
2260 test_destroy_queue
= dentry
->next
;
2261 dentry
->destroy_func (dentry
->destroy_data
);
2262 g_slice_free (DestroyEntry
, dentry
);
2264 if (tc
->fixture_teardown
)
2265 tc
->fixture_teardown (fixture
, tc
->test_data
);
2266 if (tc
->fixture_size
)
2268 g_timer_stop (test_run_timer
);
2270 success
= test_run_success
;
2271 test_run_success
= G_TEST_RUN_FAILURE
;
2272 largs
[0] = success
; /* OK */
2273 largs
[1] = test_run_forks
;
2274 largs
[2] = g_timer_elapsed (test_run_timer
, NULL
);
2275 g_test_log (G_TEST_LOG_STOP_CASE
, test_run_name
, test_run_msg
, G_N_ELEMENTS (largs
), largs
);
2276 g_clear_pointer (&test_run_msg
, g_free
);
2277 g_timer_destroy (test_run_timer
);
2280 g_slist_free_full (filename_free_list
, g_free
);
2281 test_filename_free_list
= old_free_list
;
2282 g_free (test_uri_base
);
2283 test_uri_base
= old_base
;
2285 return (success
== G_TEST_RUN_SUCCESS
||
2286 success
== G_TEST_RUN_SKIPPED
);
2290 path_has_prefix (const char *path
,
2293 int prefix_len
= strlen (prefix
);
2295 return (strncmp (path
, prefix
, prefix_len
) == 0 &&
2296 (path
[prefix_len
] == '\0' ||
2297 path
[prefix_len
] == '/'));
2301 test_should_run (const char *test_path
,
2302 const char *cmp_path
)
2304 if (strstr (test_run_name
, "/subprocess"))
2306 if (g_strcmp0 (test_path
, cmp_path
) == 0)
2309 if (g_test_verbose ())
2310 g_print ("GTest: skipping: %s\n", test_run_name
);
2314 return !cmp_path
|| path_has_prefix (test_path
, cmp_path
);
2317 /* Recurse through @suite, running tests matching @path (or all tests
2318 * if @path is %NULL).
2321 g_test_run_suite_internal (GTestSuite
*suite
,
2325 gchar
*old_name
= test_run_name
;
2328 g_return_val_if_fail (suite
!= NULL
, -1);
2330 g_test_log (G_TEST_LOG_START_SUITE
, suite
->name
, NULL
, 0, NULL
);
2332 for (iter
= suite
->cases
; iter
; iter
= iter
->next
)
2334 GTestCase
*tc
= iter
->data
;
2336 test_run_name
= g_build_path ("/", old_name
, tc
->name
, NULL
);
2337 if (test_should_run (test_run_name
, path
))
2339 if (!test_case_run (tc
))
2342 g_free (test_run_name
);
2345 for (iter
= suite
->suites
; iter
; iter
= iter
->next
)
2347 GTestSuite
*ts
= iter
->data
;
2349 test_run_name
= g_build_path ("/", old_name
, ts
->name
, NULL
);
2350 if (!path
|| path_has_prefix (path
, test_run_name
))
2351 n_bad
+= g_test_run_suite_internal (ts
, path
);
2352 g_free (test_run_name
);
2355 test_run_name
= old_name
;
2357 g_test_log (G_TEST_LOG_STOP_SUITE
, suite
->name
, NULL
, 0, NULL
);
2363 g_test_suite_count (GTestSuite
*suite
)
2368 g_return_val_if_fail (suite
!= NULL
, -1);
2370 for (iter
= suite
->cases
; iter
; iter
= iter
->next
)
2372 GTestCase
*tc
= iter
->data
;
2374 if (strcmp (tc
->name
, "subprocess") != 0)
2378 for (iter
= suite
->suites
; iter
; iter
= iter
->next
)
2380 GTestSuite
*ts
= iter
->data
;
2382 if (strcmp (ts
->name
, "subprocess") != 0)
2383 n
+= g_test_suite_count (ts
);
2391 * @suite: a #GTestSuite
2393 * Execute the tests within @suite and all nested #GTestSuites.
2394 * The test suites to be executed are filtered according to
2395 * test path arguments (`-p testpath` and `-s testpath`) as parsed by
2396 * g_test_init(). See the g_test_run() documentation for more
2397 * information on the order that tests are run in.
2399 * g_test_run_suite() or g_test_run() may only be called once
2402 * Returns: 0 on success
2407 g_test_run_suite (GTestSuite
*suite
)
2411 g_return_val_if_fail (g_test_run_once
== TRUE
, -1);
2413 g_test_run_once
= FALSE
;
2414 test_count
= g_test_suite_count (suite
);
2416 test_run_name
= g_strdup_printf ("/%s", suite
->name
);
2422 for (iter
= test_paths
; iter
; iter
= iter
->next
)
2423 n_bad
+= g_test_run_suite_internal (suite
, iter
->data
);
2426 n_bad
= g_test_run_suite_internal (suite
, NULL
);
2428 g_free (test_run_name
);
2429 test_run_name
= NULL
;
2435 gtest_default_log_handler (const gchar
*log_domain
,
2436 GLogLevelFlags log_level
,
2437 const gchar
*message
,
2438 gpointer unused_data
)
2440 const gchar
*strv
[16];
2441 gboolean fatal
= FALSE
;
2447 strv
[i
++] = log_domain
;
2450 if (log_level
& G_LOG_FLAG_FATAL
)
2452 strv
[i
++] = "FATAL-";
2455 if (log_level
& G_LOG_FLAG_RECURSION
)
2456 strv
[i
++] = "RECURSIVE-";
2457 if (log_level
& G_LOG_LEVEL_ERROR
)
2458 strv
[i
++] = "ERROR";
2459 if (log_level
& G_LOG_LEVEL_CRITICAL
)
2460 strv
[i
++] = "CRITICAL";
2461 if (log_level
& G_LOG_LEVEL_WARNING
)
2462 strv
[i
++] = "WARNING";
2463 if (log_level
& G_LOG_LEVEL_MESSAGE
)
2464 strv
[i
++] = "MESSAGE";
2465 if (log_level
& G_LOG_LEVEL_INFO
)
2467 if (log_level
& G_LOG_LEVEL_DEBUG
)
2468 strv
[i
++] = "DEBUG";
2470 strv
[i
++] = message
;
2473 msg
= g_strjoinv ("", (gchar
**) strv
);
2474 g_test_log (fatal
? G_TEST_LOG_ERROR
: G_TEST_LOG_MESSAGE
, msg
, NULL
, 0, NULL
);
2475 g_log_default_handler (log_domain
, log_level
, message
, unused_data
);
2481 g_assertion_message (const char *domain
,
2485 const char *message
)
2491 message
= "code should not be reached";
2492 g_snprintf (lstr
, 32, "%d", line
);
2493 s
= g_strconcat (domain
? domain
: "", domain
&& domain
[0] ? ":" : "",
2494 "ERROR:", file
, ":", lstr
, ":",
2495 func
, func
[0] ? ":" : "",
2496 " ", message
, NULL
);
2497 g_printerr ("**\n%s\n", s
);
2499 /* Don't print a fatal error indication if assertions are non-fatal, or
2500 * if we are a child process that might be sharing the parent's stdout. */
2501 if (test_nonfatal_assertions
|| test_in_subprocess
|| test_in_forked_child
)
2502 g_test_log (G_TEST_LOG_MESSAGE
, s
, NULL
, 0, NULL
);
2504 g_test_log (G_TEST_LOG_ERROR
, s
, NULL
, 0, NULL
);
2506 if (test_nonfatal_assertions
)
2513 /* store assertion message in global variable, so that it can be found in a
2515 if (__glib_assert_msg
!= NULL
)
2516 /* free the old one */
2517 free (__glib_assert_msg
);
2518 __glib_assert_msg
= (char*) malloc (strlen (s
) + 1);
2519 strcpy (__glib_assert_msg
, s
);
2523 if (test_in_subprocess
)
2525 /* If this is a test case subprocess then it probably hit this
2526 * assertion on purpose, so just exit() rather than abort()ing,
2527 * to avoid triggering any system crash-reporting daemon.
2536 * g_assertion_message_expr: (skip)
2537 * @domain: (nullable):
2541 * @expr: (nullable):
2544 g_assertion_message_expr (const char *domain
,
2552 s
= g_strdup ("code should not be reached");
2554 s
= g_strconcat ("assertion failed: (", expr
, ")", NULL
);
2555 g_assertion_message (domain
, file
, line
, func
, s
);
2558 /* Normally g_assertion_message() won't return, but we need this for
2559 * when test_nonfatal_assertions is set, since
2560 * g_assertion_message_expr() is used for always-fatal assertions.
2562 if (test_in_subprocess
)
2569 g_assertion_message_cmpnum (const char *domain
,
2583 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;
2584 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;
2585 case 'f': s
= g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr
, (double) arg1
, cmp
, (double) arg2
); break;
2586 /* ideally use: floats=%.7g double=%.17g */
2588 g_assertion_message (domain
, file
, line
, func
, s
);
2593 g_assertion_message_cmpstr (const char *domain
,
2602 char *a1
, *a2
, *s
, *t1
= NULL
, *t2
= NULL
;
2603 a1
= arg1
? g_strconcat ("\"", t1
= g_strescape (arg1
, NULL
), "\"", NULL
) : g_strdup ("NULL");
2604 a2
= arg2
? g_strconcat ("\"", t2
= g_strescape (arg2
, NULL
), "\"", NULL
) : g_strdup ("NULL");
2607 s
= g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr
, a1
, cmp
, a2
);
2610 g_assertion_message (domain
, file
, line
, func
, s
);
2615 g_assertion_message_error (const char *domain
,
2620 const GError
*error
,
2621 GQuark error_domain
,
2626 /* This is used by both g_assert_error() and g_assert_no_error(), so there
2627 * are three cases: expected an error but got the wrong error, expected
2628 * an error but got no error, and expected no error but got an error.
2631 gstring
= g_string_new ("assertion failed ");
2633 g_string_append_printf (gstring
, "(%s == (%s, %d)): ", expr
,
2634 g_quark_to_string (error_domain
), error_code
);
2636 g_string_append_printf (gstring
, "(%s == NULL): ", expr
);
2639 g_string_append_printf (gstring
, "%s (%s, %d)", error
->message
,
2640 g_quark_to_string (error
->domain
), error
->code
);
2642 g_string_append_printf (gstring
, "%s is NULL", expr
);
2644 g_assertion_message (domain
, file
, line
, func
, gstring
->str
);
2645 g_string_free (gstring
, TRUE
);
2650 * @str1: (nullable): a C string or %NULL
2651 * @str2: (nullable): another C string or %NULL
2653 * Compares @str1 and @str2 like strcmp(). Handles %NULL
2654 * gracefully by sorting it before non-%NULL strings.
2655 * Comparing two %NULL pointers returns 0.
2657 * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
2662 g_strcmp0 (const char *str1
,
2666 return -(str1
!= str2
);
2668 return str1
!= str2
;
2669 return strcmp (str1
, str2
);
2673 test_trap_clear (void)
2675 test_trap_last_status
= 0;
2676 test_trap_last_pid
= 0;
2677 g_clear_pointer (&test_trap_last_subprocess
, g_free
);
2678 g_clear_pointer (&test_trap_last_stdout
, g_free
);
2679 g_clear_pointer (&test_trap_last_stderr
, g_free
);
2690 ret
= dup2 (fd1
, fd2
);
2691 while (ret
< 0 && errno
== EINTR
);
2700 int child_status
; /* unmodified platform-specific status */
2702 GIOChannel
*stdout_io
;
2703 gboolean echo_stdout
;
2704 GString
*stdout_str
;
2706 GIOChannel
*stderr_io
;
2707 gboolean echo_stderr
;
2708 GString
*stderr_str
;
2712 check_complete (WaitForChildData
*data
)
2714 if (data
->child_status
!= -1 && data
->stdout_io
== NULL
&& data
->stderr_io
== NULL
)
2715 g_main_loop_quit (data
->loop
);
2719 child_exited (GPid pid
,
2723 WaitForChildData
*data
= user_data
;
2725 g_assert (status
!= -1);
2726 data
->child_status
= status
;
2728 check_complete (data
);
2732 child_timeout (gpointer user_data
)
2734 WaitForChildData
*data
= user_data
;
2737 TerminateProcess (data
->pid
, G_TEST_STATUS_TIMED_OUT
);
2739 kill (data
->pid
, SIGALRM
);
2746 child_read (GIOChannel
*io
, GIOCondition cond
, gpointer user_data
)
2748 WaitForChildData
*data
= user_data
;
2750 gsize nread
, nwrote
, total
;
2752 FILE *echo_file
= NULL
;
2754 status
= g_io_channel_read_chars (io
, buf
, sizeof (buf
), &nread
, NULL
);
2755 if (status
== G_IO_STATUS_ERROR
|| status
== G_IO_STATUS_EOF
)
2757 // FIXME data->error = (status == G_IO_STATUS_ERROR);
2758 if (io
== data
->stdout_io
)
2759 g_clear_pointer (&data
->stdout_io
, g_io_channel_unref
);
2761 g_clear_pointer (&data
->stderr_io
, g_io_channel_unref
);
2763 check_complete (data
);
2766 else if (status
== G_IO_STATUS_AGAIN
)
2769 if (io
== data
->stdout_io
)
2771 g_string_append_len (data
->stdout_str
, buf
, nread
);
2772 if (data
->echo_stdout
)
2777 g_string_append_len (data
->stderr_str
, buf
, nread
);
2778 if (data
->echo_stderr
)
2784 for (total
= 0; total
< nread
; total
+= nwrote
)
2788 nwrote
= fwrite (buf
+ total
, 1, nread
- total
, echo_file
);
2791 g_error ("write failed: %s", g_strerror (errsv
));
2799 wait_for_child (GPid pid
,
2800 int stdout_fd
, gboolean echo_stdout
,
2801 int stderr_fd
, gboolean echo_stderr
,
2804 WaitForChildData data
;
2805 GMainContext
*context
;
2809 data
.child_status
= -1;
2811 context
= g_main_context_new ();
2812 data
.loop
= g_main_loop_new (context
, FALSE
);
2814 source
= g_child_watch_source_new (pid
);
2815 g_source_set_callback (source
, (GSourceFunc
) child_exited
, &data
, NULL
);
2816 g_source_attach (source
, context
);
2817 g_source_unref (source
);
2819 data
.echo_stdout
= echo_stdout
;
2820 data
.stdout_str
= g_string_new (NULL
);
2821 data
.stdout_io
= g_io_channel_unix_new (stdout_fd
);
2822 g_io_channel_set_close_on_unref (data
.stdout_io
, TRUE
);
2823 g_io_channel_set_encoding (data
.stdout_io
, NULL
, NULL
);
2824 g_io_channel_set_buffered (data
.stdout_io
, FALSE
);
2825 source
= g_io_create_watch (data
.stdout_io
, G_IO_IN
| G_IO_ERR
| G_IO_HUP
);
2826 g_source_set_callback (source
, (GSourceFunc
) child_read
, &data
, NULL
);
2827 g_source_attach (source
, context
);
2828 g_source_unref (source
);
2830 data
.echo_stderr
= echo_stderr
;
2831 data
.stderr_str
= g_string_new (NULL
);
2832 data
.stderr_io
= g_io_channel_unix_new (stderr_fd
);
2833 g_io_channel_set_close_on_unref (data
.stderr_io
, TRUE
);
2834 g_io_channel_set_encoding (data
.stderr_io
, NULL
, NULL
);
2835 g_io_channel_set_buffered (data
.stderr_io
, FALSE
);
2836 source
= g_io_create_watch (data
.stderr_io
, G_IO_IN
| G_IO_ERR
| G_IO_HUP
);
2837 g_source_set_callback (source
, (GSourceFunc
) child_read
, &data
, NULL
);
2838 g_source_attach (source
, context
);
2839 g_source_unref (source
);
2843 source
= g_timeout_source_new (0);
2844 g_source_set_ready_time (source
, g_get_monotonic_time () + timeout
);
2845 g_source_set_callback (source
, (GSourceFunc
) child_timeout
, &data
, NULL
);
2846 g_source_attach (source
, context
);
2847 g_source_unref (source
);
2850 g_main_loop_run (data
.loop
);
2851 g_main_loop_unref (data
.loop
);
2852 g_main_context_unref (context
);
2854 test_trap_last_pid
= pid
;
2855 test_trap_last_status
= data
.child_status
;
2856 test_trap_last_stdout
= g_string_free (data
.stdout_str
, FALSE
);
2857 test_trap_last_stderr
= g_string_free (data
.stderr_str
, FALSE
);
2859 g_clear_pointer (&data
.stdout_io
, g_io_channel_unref
);
2860 g_clear_pointer (&data
.stderr_io
, g_io_channel_unref
);
2865 * @usec_timeout: Timeout for the forked test in micro seconds.
2866 * @test_trap_flags: Flags to modify forking behaviour.
2868 * Fork the current test program to execute a test case that might
2869 * not return or that might abort.
2871 * If @usec_timeout is non-0, the forked test case is aborted and
2872 * considered failing if its run time exceeds it.
2874 * The forking behavior can be configured with the #GTestTrapFlags flags.
2876 * In the following example, the test code forks, the forked child
2877 * process produces some sample output and exits successfully.
2878 * The forking parent process then asserts successful child program
2879 * termination and validates child program outputs.
2881 * |[<!-- language="C" -->
2883 * test_fork_patterns (void)
2885 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2887 * g_print ("some stdout text: somagic17\n");
2888 * g_printerr ("some stderr text: semagic43\n");
2889 * exit (0); // successful test run
2891 * g_test_trap_assert_passed ();
2892 * g_test_trap_assert_stdout ("*somagic17*");
2893 * g_test_trap_assert_stderr ("*semagic43*");
2897 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2901 * Deprecated: This function is implemented only on Unix platforms,
2902 * and is not always reliable due to problems inherent in
2903 * fork-without-exec. Use g_test_trap_subprocess() instead.
2906 g_test_trap_fork (guint64 usec_timeout
,
2907 GTestTrapFlags test_trap_flags
)
2910 int stdout_pipe
[2] = { -1, -1 };
2911 int stderr_pipe
[2] = { -1, -1 };
2915 if (pipe (stdout_pipe
) < 0 || pipe (stderr_pipe
) < 0)
2918 g_error ("failed to create pipes to fork test program: %s", g_strerror (errsv
));
2920 test_trap_last_pid
= fork ();
2922 if (test_trap_last_pid
< 0)
2923 g_error ("failed to fork test program: %s", g_strerror (errsv
));
2924 if (test_trap_last_pid
== 0) /* child */
2927 test_in_forked_child
= TRUE
;
2928 close (stdout_pipe
[0]);
2929 close (stderr_pipe
[0]);
2930 if (!(test_trap_flags
& G_TEST_TRAP_INHERIT_STDIN
))
2932 fd0
= g_open ("/dev/null", O_RDONLY
, 0);
2934 g_error ("failed to open /dev/null for stdin redirection");
2936 if (sane_dup2 (stdout_pipe
[1], 1) < 0 || sane_dup2 (stderr_pipe
[1], 2) < 0 || (fd0
>= 0 && sane_dup2 (fd0
, 0) < 0))
2939 g_error ("failed to dup2() in forked test program: %s", g_strerror (errsv
));
2943 if (stdout_pipe
[1] >= 3)
2944 close (stdout_pipe
[1]);
2945 if (stderr_pipe
[1] >= 3)
2946 close (stderr_pipe
[1]);
2952 close (stdout_pipe
[1]);
2953 close (stderr_pipe
[1]);
2955 wait_for_child (test_trap_last_pid
,
2956 stdout_pipe
[0], !(test_trap_flags
& G_TEST_TRAP_SILENCE_STDOUT
),
2957 stderr_pipe
[0], !(test_trap_flags
& G_TEST_TRAP_SILENCE_STDERR
),
2962 g_message ("Not implemented: g_test_trap_fork");
2969 * g_test_trap_subprocess:
2970 * @test_path: (nullable): Test to run in a subprocess
2971 * @usec_timeout: Timeout for the subprocess test in micro seconds.
2972 * @test_flags: Flags to modify subprocess behaviour.
2974 * Respawns the test program to run only @test_path in a subprocess.
2975 * This can be used for a test case that might not return, or that
2978 * If @test_path is %NULL then the same test is re-run in a subprocess.
2979 * You can use g_test_subprocess() to determine whether the test is in
2980 * a subprocess or not.
2982 * @test_path can also be the name of the parent test, followed by
2983 * "`/subprocess/`" and then a name for the specific subtest (or just
2984 * ending with "`/subprocess`" if the test only has one child test);
2985 * tests with names of this form will automatically be skipped in the
2988 * If @usec_timeout is non-0, the test subprocess is aborted and
2989 * considered failing if its run time exceeds it.
2991 * The subprocess behavior can be configured with the
2992 * #GTestSubprocessFlags flags.
2994 * You can use methods such as g_test_trap_assert_passed(),
2995 * g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to
2996 * check the results of the subprocess. (But note that
2997 * g_test_trap_assert_stdout() and g_test_trap_assert_stderr()
2998 * cannot be used if @test_flags specifies that the child should
2999 * inherit the parent stdout/stderr.)
3001 * If your `main ()` needs to behave differently in
3002 * the subprocess, you can call g_test_subprocess() (after calling
3003 * g_test_init()) to see whether you are in a subprocess.
3005 * The following example tests that calling
3006 * `my_object_new(1000000)` will abort with an error
3009 * |[<!-- language="C" -->
3011 * test_create_large_object (void)
3013 * if (g_test_subprocess ())
3015 * my_object_new (1000000);
3019 * // Reruns this same test in a subprocess
3020 * g_test_trap_subprocess (NULL, 0, 0);
3021 * g_test_trap_assert_failed ();
3022 * g_test_trap_assert_stderr ("*ERROR*too large*");
3026 * main (int argc, char **argv)
3028 * g_test_init (&argc, &argv, NULL);
3030 * g_test_add_func ("/myobject/create_large_object",
3031 * test_create_large_object);
3032 * return g_test_run ();
3039 g_test_trap_subprocess (const char *test_path
,
3040 guint64 usec_timeout
,
3041 GTestSubprocessFlags test_flags
)
3043 GError
*error
= NULL
;
3046 int stdout_fd
, stderr_fd
;
3049 /* Sanity check that they used GTestSubprocessFlags, not GTestTrapFlags */
3050 g_assert ((test_flags
& (G_TEST_TRAP_INHERIT_STDIN
| G_TEST_TRAP_SILENCE_STDOUT
| G_TEST_TRAP_SILENCE_STDERR
)) == 0);
3054 if (!g_test_suite_case_exists (g_test_get_root (), test_path
))
3055 g_error ("g_test_trap_subprocess: test does not exist: %s", test_path
);
3059 test_path
= test_run_name
;
3062 if (g_test_verbose ())
3063 g_print ("GTest: subprocess: %s\n", test_path
);
3066 test_trap_last_subprocess
= g_strdup (test_path
);
3068 argv
= g_ptr_array_new ();
3069 g_ptr_array_add (argv
, test_argv0
);
3070 g_ptr_array_add (argv
, "-q");
3071 g_ptr_array_add (argv
, "-p");
3072 g_ptr_array_add (argv
, (char *)test_path
);
3073 g_ptr_array_add (argv
, "--GTestSubprocess");
3074 if (test_log_fd
!= -1)
3076 char log_fd_buf
[128];
3078 g_ptr_array_add (argv
, "--GTestLogFD");
3079 g_snprintf (log_fd_buf
, sizeof (log_fd_buf
), "%d", test_log_fd
);
3080 g_ptr_array_add (argv
, log_fd_buf
);
3082 g_ptr_array_add (argv
, NULL
);
3084 flags
= G_SPAWN_DO_NOT_REAP_CHILD
;
3085 if (test_flags
& G_TEST_TRAP_INHERIT_STDIN
)
3086 flags
|= G_SPAWN_CHILD_INHERITS_STDIN
;
3088 if (!g_spawn_async_with_pipes (test_initial_cwd
,
3089 (char **)argv
->pdata
,
3092 &pid
, NULL
, &stdout_fd
, &stderr_fd
,
3095 g_error ("g_test_trap_subprocess() failed: %s\n",
3098 g_ptr_array_free (argv
, TRUE
);
3100 wait_for_child (pid
,
3101 stdout_fd
, !!(test_flags
& G_TEST_SUBPROCESS_INHERIT_STDOUT
),
3102 stderr_fd
, !!(test_flags
& G_TEST_SUBPROCESS_INHERIT_STDERR
),
3107 * g_test_subprocess:
3109 * Returns %TRUE (after g_test_init() has been called) if the test
3110 * program is running under g_test_trap_subprocess().
3112 * Returns: %TRUE if the test program is running under
3113 * g_test_trap_subprocess().
3118 g_test_subprocess (void)
3120 return test_in_subprocess
;
3124 * g_test_trap_has_passed:
3126 * Check the result of the last g_test_trap_subprocess() call.
3128 * Returns: %TRUE if the last test subprocess terminated successfully.
3133 g_test_trap_has_passed (void)
3136 return (WIFEXITED (test_trap_last_status
) &&
3137 WEXITSTATUS (test_trap_last_status
) == 0);
3139 return test_trap_last_status
== 0;
3144 * g_test_trap_reached_timeout:
3146 * Check the result of the last g_test_trap_subprocess() call.
3148 * Returns: %TRUE if the last test subprocess got killed due to a timeout.
3153 g_test_trap_reached_timeout (void)
3156 return (WIFSIGNALED (test_trap_last_status
) &&
3157 WTERMSIG (test_trap_last_status
) == SIGALRM
);
3159 return test_trap_last_status
== G_TEST_STATUS_TIMED_OUT
;
3164 log_child_output (const gchar
*process_id
)
3169 if (WIFEXITED (test_trap_last_status
)) /* normal exit */
3171 if (WEXITSTATUS (test_trap_last_status
) == 0)
3172 g_test_message ("child process (%s) exit status: 0 (success)",
3175 g_test_message ("child process (%s) exit status: %d (error)",
3176 process_id
, WEXITSTATUS (test_trap_last_status
));
3178 else if (WIFSIGNALED (test_trap_last_status
) &&
3179 WTERMSIG (test_trap_last_status
) == SIGALRM
)
3181 g_test_message ("child process (%s) timed out", process_id
);
3183 else if (WIFSIGNALED (test_trap_last_status
))
3185 const gchar
*maybe_dumped_core
= "";
3188 if (WCOREDUMP (test_trap_last_status
))
3189 maybe_dumped_core
= ", core dumped";
3192 g_test_message ("child process (%s) killed by signal %d (%s)%s",
3193 process_id
, WTERMSIG (test_trap_last_status
),
3194 g_strsignal (WTERMSIG (test_trap_last_status
)),
3199 g_test_message ("child process (%s) unknown wait status %d",
3200 process_id
, test_trap_last_status
);
3203 if (test_trap_last_status
== 0)
3204 g_test_message ("child process (%s) exit status: 0 (success)",
3207 g_test_message ("child process (%s) exit status: %d (error)",
3208 process_id
, test_trap_last_status
);
3211 escaped
= g_strescape (test_trap_last_stdout
, NULL
);
3212 g_test_message ("child process (%s) stdout: \"%s\"", process_id
, escaped
);
3215 escaped
= g_strescape (test_trap_last_stderr
, NULL
);
3216 g_test_message ("child process (%s) stderr: \"%s\"", process_id
, escaped
);
3219 /* so we can use short-circuiting:
3220 * logged_child_output = logged_child_output || log_child_output (...) */
3225 g_test_trap_assertions (const char *domain
,
3229 guint64 assertion_flags
, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
3230 const char *pattern
)
3232 gboolean must_pass
= assertion_flags
== 0;
3233 gboolean must_fail
= assertion_flags
== 1;
3234 gboolean match_result
= 0 == (assertion_flags
& 1);
3235 gboolean logged_child_output
= FALSE
;
3236 const char *stdout_pattern
= (assertion_flags
& 2) ? pattern
: NULL
;
3237 const char *stderr_pattern
= (assertion_flags
& 4) ? pattern
: NULL
;
3238 const char *match_error
= match_result
? "failed to match" : "contains invalid match";
3242 if (test_trap_last_subprocess
!= NULL
)
3244 process_id
= g_strdup_printf ("%s [%d]", test_trap_last_subprocess
,
3245 test_trap_last_pid
);
3247 else if (test_trap_last_pid
!= 0)
3248 process_id
= g_strdup_printf ("%d", test_trap_last_pid
);
3250 if (test_trap_last_subprocess
!= NULL
)
3251 process_id
= g_strdup (test_trap_last_subprocess
);
3254 g_error ("g_test_trap_ assertion with no trapped test");
3256 if (must_pass
&& !g_test_trap_has_passed())
3260 logged_child_output
= logged_child_output
|| log_child_output (process_id
);
3262 msg
= g_strdup_printf ("child process (%s) failed unexpectedly", process_id
);
3263 g_assertion_message (domain
, file
, line
, func
, msg
);
3266 if (must_fail
&& g_test_trap_has_passed())
3270 logged_child_output
= logged_child_output
|| log_child_output (process_id
);
3272 msg
= g_strdup_printf ("child process (%s) did not fail as expected", process_id
);
3273 g_assertion_message (domain
, file
, line
, func
, msg
);
3276 if (stdout_pattern
&& match_result
== !g_pattern_match_simple (stdout_pattern
, test_trap_last_stdout
))
3280 logged_child_output
= logged_child_output
|| log_child_output (process_id
);
3282 msg
= g_strdup_printf ("stdout of child process (%s) %s: %s", process_id
, match_error
, stdout_pattern
);
3283 g_assertion_message (domain
, file
, line
, func
, msg
);
3286 if (stderr_pattern
&& match_result
== !g_pattern_match_simple (stderr_pattern
, test_trap_last_stderr
))
3290 logged_child_output
= logged_child_output
|| log_child_output (process_id
);
3292 msg
= g_strdup_printf ("stderr of child process (%s) %s: %s", process_id
, match_error
, stderr_pattern
);
3293 g_assertion_message (domain
, file
, line
, func
, msg
);
3296 g_free (process_id
);
3300 gstring_overwrite_int (GString
*gstring
,
3304 vuint
= g_htonl (vuint
);
3305 g_string_overwrite_len (gstring
, pos
, (const gchar
*) &vuint
, 4);
3309 gstring_append_int (GString
*gstring
,
3312 vuint
= g_htonl (vuint
);
3313 g_string_append_len (gstring
, (const gchar
*) &vuint
, 4);
3317 gstring_append_double (GString
*gstring
,
3320 union { double vdouble
; guint64 vuint64
; } u
;
3321 u
.vdouble
= vdouble
;
3322 u
.vuint64
= GUINT64_TO_BE (u
.vuint64
);
3323 g_string_append_len (gstring
, (const gchar
*) &u
.vuint64
, 8);
3327 g_test_log_dump (GTestLogMsg
*msg
,
3330 GString
*gstring
= g_string_sized_new (1024);
3332 gstring_append_int (gstring
, 0); /* message length */
3333 gstring_append_int (gstring
, msg
->log_type
);
3334 gstring_append_int (gstring
, msg
->n_strings
);
3335 gstring_append_int (gstring
, msg
->n_nums
);
3336 gstring_append_int (gstring
, 0); /* reserved */
3337 for (ui
= 0; ui
< msg
->n_strings
; ui
++)
3339 guint l
= strlen (msg
->strings
[ui
]);
3340 gstring_append_int (gstring
, l
);
3341 g_string_append_len (gstring
, msg
->strings
[ui
], l
);
3343 for (ui
= 0; ui
< msg
->n_nums
; ui
++)
3344 gstring_append_double (gstring
, msg
->nums
[ui
]);
3345 *len
= gstring
->len
;
3346 gstring_overwrite_int (gstring
, 0, *len
); /* message length */
3347 return (guint8
*) g_string_free (gstring
, FALSE
);
3350 static inline long double
3351 net_double (const gchar
**ipointer
)
3353 union { guint64 vuint64
; double vdouble
; } u
;
3354 guint64 aligned_int64
;
3355 memcpy (&aligned_int64
, *ipointer
, 8);
3357 u
.vuint64
= GUINT64_FROM_BE (aligned_int64
);
3361 static inline guint32
3362 net_int (const gchar
**ipointer
)
3364 guint32 aligned_int
;
3365 memcpy (&aligned_int
, *ipointer
, 4);
3367 return g_ntohl (aligned_int
);
3371 g_test_log_extract (GTestLogBuffer
*tbuffer
)
3373 const gchar
*p
= tbuffer
->data
->str
;
3376 if (tbuffer
->data
->len
< 4 * 5)
3378 mlength
= net_int (&p
);
3379 if (tbuffer
->data
->len
< mlength
)
3381 msg
.log_type
= net_int (&p
);
3382 msg
.n_strings
= net_int (&p
);
3383 msg
.n_nums
= net_int (&p
);
3384 if (net_int (&p
) == 0)
3387 msg
.strings
= g_new0 (gchar
*, msg
.n_strings
+ 1);
3388 msg
.nums
= g_new0 (long double, msg
.n_nums
);
3389 for (ui
= 0; ui
< msg
.n_strings
; ui
++)
3391 guint sl
= net_int (&p
);
3392 msg
.strings
[ui
] = g_strndup (p
, sl
);
3395 for (ui
= 0; ui
< msg
.n_nums
; ui
++)
3396 msg
.nums
[ui
] = net_double (&p
);
3397 if (p
<= tbuffer
->data
->str
+ mlength
)
3399 g_string_erase (tbuffer
->data
, 0, mlength
);
3400 tbuffer
->msgs
= g_slist_prepend (tbuffer
->msgs
, g_memdup (&msg
, sizeof (msg
)));
3405 g_strfreev (msg
.strings
);
3408 g_error ("corrupt log stream from test program");
3413 * g_test_log_buffer_new:
3415 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3418 g_test_log_buffer_new (void)
3420 GTestLogBuffer
*tb
= g_new0 (GTestLogBuffer
, 1);
3421 tb
->data
= g_string_sized_new (1024);
3426 * g_test_log_buffer_free:
3428 * Internal function for gtester to free test log messages, no ABI guarantees provided.
3431 g_test_log_buffer_free (GTestLogBuffer
*tbuffer
)
3433 g_return_if_fail (tbuffer
!= NULL
);
3434 while (tbuffer
->msgs
)
3435 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer
));
3436 g_string_free (tbuffer
->data
, TRUE
);
3441 * g_test_log_buffer_push:
3443 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3446 g_test_log_buffer_push (GTestLogBuffer
*tbuffer
,
3448 const guint8
*bytes
)
3450 g_return_if_fail (tbuffer
!= NULL
);
3453 gboolean more_messages
;
3454 g_return_if_fail (bytes
!= NULL
);
3455 g_string_append_len (tbuffer
->data
, (const gchar
*) bytes
, n_bytes
);
3457 more_messages
= g_test_log_extract (tbuffer
);
3458 while (more_messages
);
3463 * g_test_log_buffer_pop:
3465 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
3468 g_test_log_buffer_pop (GTestLogBuffer
*tbuffer
)
3470 GTestLogMsg
*msg
= NULL
;
3471 g_return_val_if_fail (tbuffer
!= NULL
, NULL
);
3474 GSList
*slist
= g_slist_last (tbuffer
->msgs
);
3476 tbuffer
->msgs
= g_slist_delete_link (tbuffer
->msgs
, slist
);
3482 * g_test_log_msg_free:
3484 * Internal function for gtester to free test log messages, no ABI guarantees provided.
3487 g_test_log_msg_free (GTestLogMsg
*tmsg
)
3489 g_return_if_fail (tmsg
!= NULL
);
3490 g_strfreev (tmsg
->strings
);
3491 g_free (tmsg
->nums
);
3496 g_test_build_filename_va (GTestFileType file_type
,
3497 const gchar
*first_path
,
3500 const gchar
*pathv
[16];
3501 gint num_path_segments
;
3503 if (file_type
== G_TEST_DIST
)
3504 pathv
[0] = test_disted_files_dir
;
3505 else if (file_type
== G_TEST_BUILT
)
3506 pathv
[0] = test_built_files_dir
;
3508 g_assert_not_reached ();
3510 pathv
[1] = first_path
;
3512 for (num_path_segments
= 2; num_path_segments
< G_N_ELEMENTS (pathv
); num_path_segments
++)
3514 pathv
[num_path_segments
] = va_arg (ap
, const char *);
3515 if (pathv
[num_path_segments
] == NULL
)
3519 g_assert_cmpint (num_path_segments
, <, G_N_ELEMENTS (pathv
));
3521 return g_build_filenamev ((gchar
**) pathv
);
3525 * g_test_build_filename:
3526 * @file_type: the type of file (built vs. distributed)
3527 * @first_path: the first segment of the pathname
3528 * @...: %NULL-terminated additional path segments
3530 * Creates the pathname to a data file that is required for a test.
3532 * This function is conceptually similar to g_build_filename() except
3533 * that the first argument has been replaced with a #GTestFileType
3536 * The data file should either have been distributed with the module
3537 * containing the test (%G_TEST_DIST) or built as part of the build
3538 * system of that module (%G_TEST_BUILT).
3540 * In order for this function to work in srcdir != builddir situations,
3541 * the G_TEST_SRCDIR and G_TEST_BUILDDIR environment variables need to
3542 * have been defined. As of 2.38, this is done by the glib.mk
3543 * included in GLib. Please ensure that your copy is up to date before
3544 * using this function.
3546 * In case neither variable is set, this function will fall back to
3547 * using the dirname portion of argv[0], possibly removing ".libs".
3548 * This allows for casual running of tests directly from the commandline
3549 * in the srcdir == builddir case and should also support running of
3550 * installed tests, assuming the data files have been installed in the
3551 * same relative path as the test binary.
3553 * Returns: the path of the file, to be freed using g_free()
3559 * @G_TEST_DIST: a file that was included in the distribution tarball
3560 * @G_TEST_BUILT: a file that was built on the compiling machine
3562 * The type of file to return the filename for, when used with
3563 * g_test_build_filename().
3565 * These two options correspond rather directly to the 'dist' and
3566 * 'built' terminology that automake uses and are explicitly used to
3567 * distinguish between the 'srcdir' and 'builddir' being separate. All
3568 * files in your project should either be dist (in the
3569 * `EXTRA_DIST` or `dist_schema_DATA`
3570 * sense, in which case they will always be in the srcdir) or built (in
3571 * the `BUILT_SOURCES` sense, in which case they will
3572 * always be in the builddir).
3574 * Note: as a general rule of automake, files that are generated only as
3575 * part of the build-from-git process (but then are distributed with the
3576 * tarball) always go in srcdir (even if doing a srcdir != builddir
3577 * build from git) and are considered as distributed files.
3582 g_test_build_filename (GTestFileType file_type
,
3583 const gchar
*first_path
,
3589 g_assert (g_test_initialized ());
3591 va_start (ap
, first_path
);
3592 result
= g_test_build_filename_va (file_type
, first_path
, ap
);
3600 * @file_type: the type of file (built vs. distributed)
3602 * Gets the pathname of the directory containing test files of the type
3603 * specified by @file_type.
3605 * This is approximately the same as calling g_test_build_filename("."),
3606 * but you don't need to free the return value.
3608 * Returns: (type filename): the path of the directory, owned by GLib
3613 g_test_get_dir (GTestFileType file_type
)
3615 g_assert (g_test_initialized ());
3617 if (file_type
== G_TEST_DIST
)
3618 return test_disted_files_dir
;
3619 else if (file_type
== G_TEST_BUILT
)
3620 return test_built_files_dir
;
3622 g_assert_not_reached ();
3626 * g_test_get_filename:
3627 * @file_type: the type of file (built vs. distributed)
3628 * @first_path: the first segment of the pathname
3629 * @...: %NULL-terminated additional path segments
3631 * Gets the pathname to a data file that is required for a test.
3633 * This is the same as g_test_build_filename() with two differences.
3634 * The first difference is that must only use this function from within
3635 * a testcase function. The second difference is that you need not free
3636 * the return value -- it will be automatically freed when the testcase
3639 * It is safe to use this function from a thread inside of a testcase
3640 * but you must ensure that all such uses occur before the main testcase
3641 * function returns (ie: it is best to ensure that all threads have been
3644 * Returns: the path, automatically freed at the end of the testcase
3649 g_test_get_filename (GTestFileType file_type
,
3650 const gchar
*first_path
,
3657 g_assert (g_test_initialized ());
3658 if (test_filename_free_list
== NULL
)
3659 g_error ("g_test_get_filename() can only be used within testcase functions");
3661 va_start (ap
, first_path
);
3662 result
= g_test_build_filename_va (file_type
, first_path
, ap
);
3665 node
= g_slist_prepend (NULL
, result
);
3667 node
->next
= *test_filename_free_list
;
3668 while (!g_atomic_pointer_compare_and_exchange (test_filename_free_list
, node
->next
, node
));
3673 /* --- macros docs START --- */
3676 * @testpath: The test path for a new test case.
3677 * @Fixture: The type of a fixture data structure.
3678 * @tdata: Data argument for the test functions.
3679 * @fsetup: The function to set up the fixture data.
3680 * @ftest: The actual test function.
3681 * @fteardown: The function to tear down the fixture data.
3683 * Hook up a new test case at @testpath, similar to g_test_add_func().
3684 * A fixture data structure with setup and teardown functions may be provided,
3685 * similar to g_test_create_case().
3687 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
3688 * fteardown() callbacks can expect a @Fixture pointer as their first argument
3689 * in a type safe manner. They otherwise have type #GTestFixtureFunc.
3693 /* --- macros docs END --- */