genmarshal Only wrap body prototypes in C++ guards
[glib.git] / glib / gtestutils.c
blob52a216f05bf5b616546697bee0c1ba82baf60e27
1 /* GLib testing utilities
2 * Copyright (C) 2007 Imendio AB
3 * Authors: Tim Janik, Sven Herzberg
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 #include "config.h"
21 #include "gtestutils.h"
22 #include "gfileutils.h"
24 #include <sys/types.h>
25 #ifdef G_OS_UNIX
26 #include <sys/wait.h>
27 #include <sys/time.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <glib/gstdio.h>
31 #endif
32 #include <string.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #ifdef HAVE_SYS_RESOURCE_H
36 #include <sys/resource.h>
37 #endif
38 #ifdef G_OS_WIN32
39 #include <io.h>
40 #include <windows.h>
41 #endif
42 #include <errno.h>
43 #include <signal.h>
44 #ifdef HAVE_SYS_SELECT_H
45 #include <sys/select.h>
46 #endif /* HAVE_SYS_SELECT_H */
48 #include "gmain.h"
49 #include "gpattern.h"
50 #include "grand.h"
51 #include "gstrfuncs.h"
52 #include "gtimer.h"
53 #include "gslice.h"
54 #include "gspawn.h"
55 #include "glib-private.h"
58 /**
59 * SECTION:testing
60 * @title: Testing
61 * @short_description: a test framework
62 * @see_also: [gtester][gtester], [gtester-report][gtester-report]
64 * GLib provides a framework for writing and maintaining unit tests
65 * in parallel to the code they are testing. The API is designed according
66 * to established concepts found in the other test frameworks (JUnit, NUnit,
67 * RUnit), which in turn is based on smalltalk unit testing concepts.
69 * - Test case: Tests (test methods) are grouped together with their
70 * fixture into test cases.
72 * - Fixture: A test fixture consists of fixture data and setup and
73 * teardown methods to establish the environment for the test
74 * functions. We use fresh fixtures, i.e. fixtures are newly set
75 * up and torn down around each test invocation to avoid dependencies
76 * between tests.
78 * - Test suite: Test cases can be grouped into test suites, to allow
79 * subsets of the available tests to be run. Test suites can be
80 * grouped into other test suites as well.
82 * The API is designed to handle creation and registration of test suites
83 * and test cases implicitly. A simple call like
84 * |[<!-- language="C" -->
85 * g_test_add_func ("/misc/assertions", test_assertions);
86 * ]|
87 * creates a test suite called "misc" with a single test case named
88 * "assertions", which consists of running the test_assertions function.
90 * In addition to the traditional g_assert(), the test framework provides
91 * an extended set of assertions for comparisons: g_assert_cmpfloat(),
92 * g_assert_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 * GLib ships with two utilities called [gtester][gtester] and
98 * [gtester-report][gtester-report] to facilitate running tests and producing
99 * nicely formatted test reports.
101 * A full example of creating a test suite with two tests using fixtures:
102 * |[<!-- language="C" -->
103 * #include <glib.h>
104 * #include <locale.h>
106 * typedef struct {
107 * MyObject *obj;
108 * OtherObject *helper;
109 * } MyObjectFixture;
111 * static void
112 * my_object_fixture_set_up (MyObjectFixture *fixture,
113 * gconstpointer user_data)
115 * fixture->obj = my_object_new ();
116 * my_object_set_prop1 (fixture->obj, "some-value");
117 * my_object_do_some_complex_setup (fixture->obj, user_data);
119 * fixture->helper = other_object_new ();
122 * static void
123 * my_object_fixture_tear_down (MyObjectFixture *fixture,
124 * gconstpointer user_data)
126 * g_clear_object (&fixture->helper);
127 * g_clear_object (&fixture->obj);
130 * static void
131 * test_my_object_test1 (MyObjectFixture *fixture,
132 * gconstpointer user_data)
134 * g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "initial-value");
137 * static void
138 * test_my_object_test2 (MyObjectFixture *fixture,
139 * gconstpointer user_data)
141 * my_object_do_some_work_using_helper (fixture->obj, fixture->helper);
142 * g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "updated-value");
145 * int
146 * main (int argc, char *argv[])
148 * setlocale (LC_ALL, "");
150 * g_test_init (&argc, &argv, NULL);
151 * g_test_bug_base ("http://bugzilla.gnome.org/show_bug.cgi?id=");
153 * // Define the tests.
154 * g_test_add ("/my-object/test1", MyObjectFixture, "some-user-data",
155 * my_object_fixture_set_up, test_my_object_test1,
156 * my_object_fixture_tear_down);
157 * g_test_add ("/my-object/test2", MyObjectFixture, "some-user-data",
158 * my_object_fixture_set_up, test_my_object_test2,
159 * my_object_fixture_tear_down);
161 * return g_test_run ();
163 * ]|
167 * g_test_initialized:
169 * Returns %TRUE if g_test_init() has been called.
171 * Returns: %TRUE if g_test_init() has been called.
173 * Since: 2.36
177 * g_test_quick:
179 * Returns %TRUE if tests are run in quick mode.
180 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
181 * there is no "medium speed".
183 * Returns: %TRUE if in quick mode
187 * g_test_slow:
189 * Returns %TRUE if tests are run in slow mode.
190 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
191 * there is no "medium speed".
193 * Returns: the opposite of g_test_quick()
197 * g_test_thorough:
199 * Returns %TRUE if tests are run in thorough mode, equivalent to
200 * g_test_slow().
202 * Returns: the same thing as g_test_slow()
206 * g_test_perf:
208 * Returns %TRUE if tests are run in performance mode.
210 * Returns: %TRUE if in performance mode
214 * g_test_undefined:
216 * Returns %TRUE if tests may provoke assertions and other formally-undefined
217 * behaviour, to verify that appropriate warnings are given. It might, in some
218 * cases, be useful to turn this off if running tests under valgrind.
220 * Returns: %TRUE if tests may provoke programming errors
224 * g_test_verbose:
226 * Returns %TRUE if tests are run in verbose mode.
227 * The default is neither g_test_verbose() nor g_test_quiet().
229 * Returns: %TRUE if in verbose mode
233 * g_test_quiet:
235 * Returns %TRUE if tests are run in quiet mode.
236 * The default is neither g_test_verbose() nor g_test_quiet().
238 * Returns: %TRUE if in quiet mode
242 * g_test_queue_unref:
243 * @gobject: the object to unref
245 * Enqueue an object to be released with g_object_unref() during
246 * the next teardown phase. This is equivalent to calling
247 * g_test_queue_destroy() with a destroy callback of g_object_unref().
249 * Since: 2.16
253 * GTestTrapFlags:
254 * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
255 * `/dev/null` so it cannot be observed on the console during test
256 * runs. The actual output is still captured though to allow later
257 * tests with g_test_trap_assert_stdout().
258 * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
259 * `/dev/null` so it cannot be observed on the console during test
260 * runs. The actual output is still captured though to allow later
261 * tests with g_test_trap_assert_stderr().
262 * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
263 * child process is shared with stdin of its parent process.
264 * It is redirected to `/dev/null` otherwise.
266 * Test traps are guards around forked tests.
267 * These flags determine what traps to set.
269 * Deprecated: #GTestTrapFlags is used only with g_test_trap_fork(),
270 * which is deprecated. g_test_trap_subprocess() uses
271 * #GTestTrapSubprocessFlags.
275 * GTestSubprocessFlags:
276 * @G_TEST_SUBPROCESS_INHERIT_STDIN: If this flag is given, the child
277 * process will inherit the parent's stdin. Otherwise, the child's
278 * stdin is redirected to `/dev/null`.
279 * @G_TEST_SUBPROCESS_INHERIT_STDOUT: If this flag is given, the child
280 * process will inherit the parent's stdout. Otherwise, the child's
281 * stdout will not be visible, but it will be captured to allow
282 * later tests with g_test_trap_assert_stdout().
283 * @G_TEST_SUBPROCESS_INHERIT_STDERR: If this flag is given, the child
284 * process will inherit the parent's stderr. Otherwise, the child's
285 * stderr will not be visible, but it will be captured to allow
286 * later tests with g_test_trap_assert_stderr().
288 * Flags to pass to g_test_trap_subprocess() to control input and output.
290 * Note that in contrast with g_test_trap_fork(), the default is to
291 * not show stdout and stderr.
295 * g_test_trap_assert_passed:
297 * Assert that the last test subprocess passed.
298 * See g_test_trap_subprocess().
300 * Since: 2.16
304 * g_test_trap_assert_failed:
306 * Assert that the last test subprocess failed.
307 * See g_test_trap_subprocess().
309 * This is sometimes used to test situations that are formally considered to
310 * be undefined behaviour, like inputs that fail a g_return_if_fail()
311 * check. In these situations you should skip the entire test, including the
312 * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
313 * to indicate that undefined behaviour may be tested.
315 * Since: 2.16
319 * g_test_trap_assert_stdout:
320 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
322 * Assert that the stdout output of the last test subprocess matches
323 * @soutpattern. See g_test_trap_subprocess().
325 * Since: 2.16
329 * g_test_trap_assert_stdout_unmatched:
330 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
332 * Assert that the stdout output of the last test subprocess
333 * does not match @soutpattern. See g_test_trap_subprocess().
335 * Since: 2.16
339 * g_test_trap_assert_stderr:
340 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
342 * Assert that the stderr output of the last test subprocess
343 * matches @serrpattern. See g_test_trap_subprocess().
345 * This is sometimes used to test situations that are formally
346 * considered to be undefined behaviour, like code that hits a
347 * g_assert() or g_error(). In these situations you should skip the
348 * entire test, including the call to g_test_trap_subprocess(), unless
349 * g_test_undefined() returns %TRUE to indicate that undefined
350 * behaviour may be tested.
352 * Since: 2.16
356 * g_test_trap_assert_stderr_unmatched:
357 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
359 * Assert that the stderr output of the last test subprocess
360 * does not match @serrpattern. See g_test_trap_subprocess().
362 * Since: 2.16
366 * g_test_rand_bit:
368 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
369 * for details on test case random numbers.
371 * Since: 2.16
375 * g_assert:
376 * @expr: the expression to check
378 * Debugging macro to terminate the application if the assertion
379 * fails. If the assertion fails (i.e. the expression is not true),
380 * an error message is logged and the application is terminated.
382 * The macro can be turned off in final releases of code by defining
383 * `G_DISABLE_ASSERT` when compiling the application, so code must
384 * not depend on any side effects from @expr.
388 * g_assert_not_reached:
390 * Debugging macro to terminate the application if it is ever
391 * reached. If it is reached, an error message is logged and the
392 * application is terminated.
394 * The macro can be turned off in final releases of code by defining
395 * `G_DISABLE_ASSERT` when compiling the application.
399 * g_assert_true:
400 * @expr: the expression to check
402 * Debugging macro to check that an expression is true.
404 * If the assertion fails (i.e. the expression is not true),
405 * an error message is logged and the application is either
406 * terminated or the testcase marked as failed.
408 * See g_test_set_nonfatal_assertions().
410 * Since: 2.38
414 * g_assert_false:
415 * @expr: the expression to check
417 * Debugging macro to check an expression is false.
419 * If the assertion fails (i.e. the expression is not false),
420 * an error message is logged and the application is either
421 * terminated or the testcase marked as failed.
423 * See g_test_set_nonfatal_assertions().
425 * Since: 2.38
429 * g_assert_null:
430 * @expr: the expression to check
432 * Debugging macro to check an expression is %NULL.
434 * If the assertion fails (i.e. the expression is not %NULL),
435 * an error message is logged and the application is either
436 * terminated or the testcase marked as failed.
438 * See g_test_set_nonfatal_assertions().
440 * Since: 2.38
444 * g_assert_nonnull:
445 * @expr: the expression to check
447 * Debugging macro to check an expression is not %NULL.
449 * If the assertion fails (i.e. the expression is %NULL),
450 * an error message is logged and the application is either
451 * terminated or the testcase marked as failed.
453 * See g_test_set_nonfatal_assertions().
455 * Since: 2.40
459 * g_assert_cmpstr:
460 * @s1: a string (may be %NULL)
461 * @cmp: The comparison operator to use.
462 * One of ==, !=, <, >, <=, >=.
463 * @s2: another string (may be %NULL)
465 * Debugging macro to compare two strings. If the comparison fails,
466 * an error message is logged and the application is either terminated
467 * or the testcase marked as failed.
468 * The strings are compared using g_strcmp0().
470 * The effect of `g_assert_cmpstr (s1, op, s2)` is
471 * the same as `g_assert_true (g_strcmp0 (s1, s2) op 0)`.
472 * The advantage of this macro is that it can produce a message that
473 * includes the actual values of @s1 and @s2.
475 * |[<!-- language="C" -->
476 * g_assert_cmpstr (mystring, ==, "fubar");
477 * ]|
479 * Since: 2.16
483 * g_assert_cmpint:
484 * @n1: an integer
485 * @cmp: The comparison operator to use.
486 * One of ==, !=, <, >, <=, >=.
487 * @n2: another integer
489 * Debugging macro to compare two integers.
491 * The effect of `g_assert_cmpint (n1, op, n2)` is
492 * the same as `g_assert_true (n1 op n2)`. The advantage
493 * of this macro is that it can produce a message that includes the
494 * actual values of @n1 and @n2.
496 * Since: 2.16
500 * g_assert_cmpuint:
501 * @n1: an unsigned integer
502 * @cmp: The comparison operator to use.
503 * One of ==, !=, <, >, <=, >=.
504 * @n2: another unsigned integer
506 * Debugging macro to compare two unsigned integers.
508 * The effect of `g_assert_cmpuint (n1, op, n2)` is
509 * the same as `g_assert_true (n1 op n2)`. The advantage
510 * of this macro is that it can produce a message that includes the
511 * actual values of @n1 and @n2.
513 * Since: 2.16
517 * g_assert_cmphex:
518 * @n1: an unsigned integer
519 * @cmp: The comparison operator to use.
520 * One of ==, !=, <, >, <=, >=.
521 * @n2: another unsigned integer
523 * Debugging macro to compare to unsigned integers.
525 * This is a variant of g_assert_cmpuint() that displays the numbers
526 * in hexadecimal notation in the message.
528 * Since: 2.16
532 * g_assert_cmpfloat:
533 * @n1: an floating point number
534 * @cmp: The comparison operator to use.
535 * One of ==, !=, <, >, <=, >=.
536 * @n2: another floating point number
538 * Debugging macro to compare two floating point numbers.
540 * The effect of `g_assert_cmpfloat (n1, op, n2)` is
541 * the same as `g_assert_true (n1 op n2)`. The advantage
542 * of this macro is that it can produce a message that includes the
543 * actual values of @n1 and @n2.
545 * Since: 2.16
549 * g_assert_cmpmem:
550 * @m1: pointer to a buffer
551 * @l1: length of @m1
552 * @m2: pointer to another buffer
553 * @l2: length of @m2
555 * Debugging macro to compare memory regions. If the comparison fails,
556 * an error message is logged and the application is either terminated
557 * or the testcase marked as failed.
559 * The effect of `g_assert_cmpmem (m1, l1, m2, l2)` is
560 * the same as `g_assert_true (l1 == l2 && memcmp (m1, m2, l1) == 0)`.
561 * The advantage of this macro is that it can produce a message that
562 * includes the actual values of @l1 and @l2.
564 * |[<!-- language="C" -->
565 * g_assert_cmpmem (buf->data, buf->len, expected, sizeof (expected));
566 * ]|
568 * Since: 2.46
572 * g_assert_no_error:
573 * @err: a #GError, possibly %NULL
575 * Debugging macro to check that a #GError is not set.
577 * The effect of `g_assert_no_error (err)` is
578 * the same as `g_assert_true (err == NULL)`. The advantage
579 * of this macro is that it can produce a message that includes
580 * the error message and code.
582 * Since: 2.20
586 * g_assert_error:
587 * @err: a #GError, possibly %NULL
588 * @dom: the expected error domain (a #GQuark)
589 * @c: the expected error code
591 * Debugging macro to check that a method has returned
592 * the correct #GError.
594 * The effect of `g_assert_error (err, dom, c)` is
595 * the same as `g_assert_true (err != NULL && err->domain
596 * == dom && err->code == c)`. The advantage of this
597 * macro is that it can produce a message that includes the incorrect
598 * error message and code.
600 * This can only be used to test for a specific error. If you want to
601 * test that @err is set, but don't care what it's set to, just use
602 * `g_assert (err != NULL)`
604 * Since: 2.20
608 * GTestCase:
610 * An opaque structure representing a test case.
614 * GTestSuite:
616 * An opaque structure representing a test suite.
620 /* Global variable for storing assertion messages; this is the counterpart to
621 * glibc's (private) __abort_msg variable, and allows developers and crash
622 * analysis systems like Apport and ABRT to fish out assertion messages from
623 * core dumps, instead of having to catch them on screen output.
625 GLIB_VAR char *__glib_assert_msg;
626 char *__glib_assert_msg = NULL;
628 /* --- constants --- */
629 #define G_TEST_STATUS_TIMED_OUT 1024
631 /* --- structures --- */
632 struct GTestCase
634 gchar *name;
635 guint fixture_size;
636 void (*fixture_setup) (void*, gconstpointer);
637 void (*fixture_test) (void*, gconstpointer);
638 void (*fixture_teardown) (void*, gconstpointer);
639 gpointer test_data;
641 struct GTestSuite
643 gchar *name;
644 GSList *suites;
645 GSList *cases;
647 typedef struct DestroyEntry DestroyEntry;
648 struct DestroyEntry
650 DestroyEntry *next;
651 GDestroyNotify destroy_func;
652 gpointer destroy_data;
655 /* --- prototypes --- */
656 static void test_run_seed (const gchar *rseed);
657 static void test_trap_clear (void);
658 static guint8* g_test_log_dump (GTestLogMsg *msg,
659 guint *len);
660 static void gtest_default_log_handler (const gchar *log_domain,
661 GLogLevelFlags log_level,
662 const gchar *message,
663 gpointer unused_data);
666 typedef enum {
667 G_TEST_RUN_SUCCESS,
668 G_TEST_RUN_SKIPPED,
669 G_TEST_RUN_FAILURE,
670 G_TEST_RUN_INCOMPLETE
671 } GTestResult;
672 static const char * const g_test_result_names[] = {
673 "OK",
674 "SKIP",
675 "FAIL",
676 "TODO"
679 /* --- variables --- */
680 static int test_log_fd = -1;
681 static gboolean test_mode_fatal = TRUE;
682 static gboolean g_test_run_once = TRUE;
683 static gboolean test_run_list = FALSE;
684 static gchar *test_run_seedstr = NULL;
685 static GRand *test_run_rand = NULL;
686 static gchar *test_run_name = "";
687 static GSList **test_filename_free_list;
688 static guint test_run_forks = 0;
689 static guint test_run_count = 0;
690 static guint test_count = 0;
691 static guint test_skipped_count = 0;
692 static GTestResult test_run_success = G_TEST_RUN_FAILURE;
693 static gchar *test_run_msg = NULL;
694 static guint test_startup_skip_count = 0;
695 static GTimer *test_user_timer = NULL;
696 static double test_user_stamp = 0;
697 static GSList *test_paths = NULL;
698 static GSList *test_paths_skipped = NULL;
699 static GTestSuite *test_suite_root = NULL;
700 static int test_trap_last_status = 0;
701 static GPid test_trap_last_pid = 0;
702 static char *test_trap_last_subprocess = NULL;
703 static char *test_trap_last_stdout = NULL;
704 static char *test_trap_last_stderr = NULL;
705 static char *test_uri_base = NULL;
706 static gboolean test_debug_log = FALSE;
707 static gboolean test_tap_log = FALSE;
708 static gboolean test_nonfatal_assertions = FALSE;
709 static DestroyEntry *test_destroy_queue = NULL;
710 static char *test_argv0 = NULL;
711 static char *test_argv0_dirname;
712 static const char *test_disted_files_dir;
713 static const char *test_built_files_dir;
714 static char *test_initial_cwd = NULL;
715 static gboolean test_in_subprocess = FALSE;
716 static GTestConfig mutable_test_config_vars = {
717 FALSE, /* test_initialized */
718 TRUE, /* test_quick */
719 FALSE, /* test_perf */
720 FALSE, /* test_verbose */
721 FALSE, /* test_quiet */
722 TRUE, /* test_undefined */
724 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
725 static gboolean no_g_set_prgname = FALSE;
727 /* --- functions --- */
728 const char*
729 g_test_log_type_name (GTestLogType log_type)
731 switch (log_type)
733 case G_TEST_LOG_NONE: return "none";
734 case G_TEST_LOG_ERROR: return "error";
735 case G_TEST_LOG_START_BINARY: return "binary";
736 case G_TEST_LOG_LIST_CASE: return "list";
737 case G_TEST_LOG_SKIP_CASE: return "skip";
738 case G_TEST_LOG_START_CASE: return "start";
739 case G_TEST_LOG_STOP_CASE: return "stop";
740 case G_TEST_LOG_MIN_RESULT: return "minperf";
741 case G_TEST_LOG_MAX_RESULT: return "maxperf";
742 case G_TEST_LOG_MESSAGE: return "message";
743 case G_TEST_LOG_START_SUITE: return "start suite";
744 case G_TEST_LOG_STOP_SUITE: return "stop suite";
746 return "???";
749 static void
750 g_test_log_send (guint n_bytes,
751 const guint8 *buffer)
753 if (test_log_fd >= 0)
755 int r;
757 r = write (test_log_fd, buffer, n_bytes);
758 while (r < 0 && errno == EINTR);
760 if (test_debug_log)
762 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
763 GTestLogMsg *msg;
764 guint ui;
765 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
766 msg = g_test_log_buffer_pop (lbuffer);
767 g_warn_if_fail (msg != NULL);
768 g_warn_if_fail (lbuffer->data->len == 0);
769 g_test_log_buffer_free (lbuffer);
770 /* print message */
771 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
772 for (ui = 0; ui < msg->n_strings; ui++)
773 g_printerr (":{%s}", msg->strings[ui]);
774 if (msg->n_nums)
776 g_printerr (":(");
777 for (ui = 0; ui < msg->n_nums; ui++)
779 if ((long double) (long) msg->nums[ui] == msg->nums[ui])
780 g_printerr ("%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
781 else
782 g_printerr ("%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
784 g_printerr (")");
786 g_printerr (":LOG*}\n");
787 g_test_log_msg_free (msg);
791 static void
792 g_test_log (GTestLogType lbit,
793 const gchar *string1,
794 const gchar *string2,
795 guint n_args,
796 long double *largs)
798 GTestResult result;
799 gboolean fail;
800 GTestLogMsg msg;
801 gchar *astrings[3] = { NULL, NULL, NULL };
802 guint8 *dbuffer;
803 guint32 dbufferlen;
805 switch (lbit)
807 case G_TEST_LOG_START_BINARY:
808 if (test_tap_log)
809 g_print ("# random seed: %s\n", string2);
810 else if (g_test_verbose())
811 g_print ("GTest: random seed: %s\n", string2);
812 break;
813 case G_TEST_LOG_START_SUITE:
814 if (test_tap_log)
816 if (string1[0] != 0)
817 g_print ("# Start of %s tests\n", string1);
818 else
819 g_print ("1..%d\n", test_count);
821 break;
822 case G_TEST_LOG_STOP_SUITE:
823 if (test_tap_log)
825 if (string1[0] != 0)
826 g_print ("# End of %s tests\n", string1);
828 break;
829 case G_TEST_LOG_STOP_CASE:
830 result = largs[0];
831 fail = result == G_TEST_RUN_FAILURE;
832 if (test_tap_log)
834 g_print ("%s %d %s", fail ? "not ok" : "ok", test_run_count, string1);
835 if (result == G_TEST_RUN_INCOMPLETE)
836 g_print (" # TODO %s\n", string2 ? string2 : "");
837 else if (result == G_TEST_RUN_SKIPPED)
838 g_print (" # SKIP %s\n", string2 ? string2 : "");
839 else
840 g_print ("\n");
842 else if (g_test_verbose())
843 g_print ("GTest: result: %s\n", g_test_result_names[result]);
844 else if (!g_test_quiet())
845 g_print ("%s\n", g_test_result_names[result]);
846 if (fail && test_mode_fatal)
848 if (test_tap_log)
849 g_print ("Bail out!\n");
850 g_abort();
852 if (result == G_TEST_RUN_SKIPPED)
853 test_skipped_count++;
854 break;
855 case G_TEST_LOG_MIN_RESULT:
856 if (test_tap_log)
857 g_print ("# min perf: %s\n", string1);
858 else if (g_test_verbose())
859 g_print ("(MINPERF:%s)\n", string1);
860 break;
861 case G_TEST_LOG_MAX_RESULT:
862 if (test_tap_log)
863 g_print ("# max perf: %s\n", string1);
864 else if (g_test_verbose())
865 g_print ("(MAXPERF:%s)\n", string1);
866 break;
867 case G_TEST_LOG_MESSAGE:
868 case G_TEST_LOG_ERROR:
869 if (test_tap_log)
870 g_print ("# %s\n", string1);
871 else if (g_test_verbose())
872 g_print ("(MSG: %s)\n", string1);
873 break;
874 default: ;
877 msg.log_type = lbit;
878 msg.n_strings = (string1 != NULL) + (string1 && string2);
879 msg.strings = astrings;
880 astrings[0] = (gchar*) string1;
881 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
882 msg.n_nums = n_args;
883 msg.nums = largs;
884 dbuffer = g_test_log_dump (&msg, &dbufferlen);
885 g_test_log_send (dbufferlen, dbuffer);
886 g_free (dbuffer);
888 switch (lbit)
890 case G_TEST_LOG_START_CASE:
891 if (test_tap_log)
893 else if (g_test_verbose())
894 g_print ("GTest: run: %s\n", string1);
895 else if (!g_test_quiet())
896 g_print ("%s: ", string1);
897 break;
898 default: ;
902 /* We intentionally parse the command line without GOptionContext
903 * because otherwise you would never be able to test it.
905 static void
906 parse_args (gint *argc_p,
907 gchar ***argv_p)
909 guint argc = *argc_p;
910 gchar **argv = *argv_p;
911 guint i, e;
913 test_argv0 = argv[0];
914 test_initial_cwd = g_get_current_dir ();
916 /* parse known args */
917 for (i = 1; i < argc; i++)
919 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
921 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
922 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
923 g_log_set_always_fatal (fatal_mask);
924 argv[i] = NULL;
926 else if (strcmp (argv[i], "--keep-going") == 0 ||
927 strcmp (argv[i], "-k") == 0)
929 test_mode_fatal = FALSE;
930 argv[i] = NULL;
932 else if (strcmp (argv[i], "--debug-log") == 0)
934 test_debug_log = TRUE;
935 argv[i] = NULL;
937 else if (strcmp (argv[i], "--tap") == 0)
939 test_tap_log = TRUE;
940 argv[i] = NULL;
942 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
944 gchar *equal = argv[i] + 12;
945 if (*equal == '=')
946 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
947 else if (i + 1 < argc)
949 argv[i++] = NULL;
950 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
952 argv[i] = NULL;
954 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
956 gchar *equal = argv[i] + 16;
957 if (*equal == '=')
958 test_startup_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
959 else if (i + 1 < argc)
961 argv[i++] = NULL;
962 test_startup_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
964 argv[i] = NULL;
966 else if (strcmp ("--GTestSubprocess", argv[i]) == 0)
968 test_in_subprocess = TRUE;
969 /* We typically expect these child processes to crash, and some
970 * tests spawn a *lot* of them. Avoid spamming system crash
971 * collection programs such as systemd-coredump and abrt.
973 #ifdef HAVE_SYS_RESOURCE_H
975 struct rlimit limit = { 0, 0 };
976 (void) setrlimit (RLIMIT_CORE, &limit);
978 #endif
979 argv[i] = NULL;
981 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
983 gchar *equal = argv[i] + 2;
984 if (*equal == '=')
985 test_paths = g_slist_prepend (test_paths, equal + 1);
986 else if (i + 1 < argc)
988 argv[i++] = NULL;
989 test_paths = g_slist_prepend (test_paths, argv[i]);
991 argv[i] = NULL;
993 else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
995 gchar *equal = argv[i] + 2;
996 if (*equal == '=')
997 test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
998 else if (i + 1 < argc)
1000 argv[i++] = NULL;
1001 test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
1003 argv[i] = NULL;
1005 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
1007 gchar *equal = argv[i] + 2;
1008 const gchar *mode = "";
1009 if (*equal == '=')
1010 mode = equal + 1;
1011 else if (i + 1 < argc)
1013 argv[i++] = NULL;
1014 mode = argv[i];
1016 if (strcmp (mode, "perf") == 0)
1017 mutable_test_config_vars.test_perf = TRUE;
1018 else if (strcmp (mode, "slow") == 0)
1019 mutable_test_config_vars.test_quick = FALSE;
1020 else if (strcmp (mode, "thorough") == 0)
1021 mutable_test_config_vars.test_quick = FALSE;
1022 else if (strcmp (mode, "quick") == 0)
1024 mutable_test_config_vars.test_quick = TRUE;
1025 mutable_test_config_vars.test_perf = FALSE;
1027 else if (strcmp (mode, "undefined") == 0)
1028 mutable_test_config_vars.test_undefined = TRUE;
1029 else if (strcmp (mode, "no-undefined") == 0)
1030 mutable_test_config_vars.test_undefined = FALSE;
1031 else
1032 g_error ("unknown test mode: -m %s", mode);
1033 argv[i] = NULL;
1035 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
1037 mutable_test_config_vars.test_quiet = TRUE;
1038 mutable_test_config_vars.test_verbose = FALSE;
1039 argv[i] = NULL;
1041 else if (strcmp ("--verbose", argv[i]) == 0)
1043 mutable_test_config_vars.test_quiet = FALSE;
1044 mutable_test_config_vars.test_verbose = TRUE;
1045 argv[i] = NULL;
1047 else if (strcmp ("-l", argv[i]) == 0)
1049 test_run_list = TRUE;
1050 argv[i] = NULL;
1052 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
1054 gchar *equal = argv[i] + 6;
1055 if (*equal == '=')
1056 test_run_seedstr = equal + 1;
1057 else if (i + 1 < argc)
1059 argv[i++] = NULL;
1060 test_run_seedstr = argv[i];
1062 argv[i] = NULL;
1064 else if (strcmp ("-?", argv[i]) == 0 ||
1065 strcmp ("-h", argv[i]) == 0 ||
1066 strcmp ("--help", argv[i]) == 0)
1068 printf ("Usage:\n"
1069 " %s [OPTION...]\n\n"
1070 "Help Options:\n"
1071 " -h, --help Show help options\n\n"
1072 "Test Options:\n"
1073 " --g-fatal-warnings Make all warnings fatal\n"
1074 " -l List test cases available in a test executable\n"
1075 " -m {perf|slow|thorough|quick} Execute tests according to mode\n"
1076 " -m {undefined|no-undefined} Execute tests according to mode\n"
1077 " -p TESTPATH Only start test cases matching TESTPATH\n"
1078 " -s TESTPATH Skip all tests matching TESTPATH\n"
1079 " --seed=SEEDSTRING Start tests with random seed SEEDSTRING\n"
1080 " --debug-log debug test logging output\n"
1081 " -q, --quiet Run tests quietly\n"
1082 " --verbose Run tests verbosely\n",
1083 argv[0]);
1084 exit (0);
1087 /* collapse argv */
1088 e = 1;
1089 for (i = 1; i < argc; i++)
1090 if (argv[i])
1092 argv[e++] = argv[i];
1093 if (i >= e)
1094 argv[i] = NULL;
1096 *argc_p = e;
1100 * g_test_init:
1101 * @argc: Address of the @argc parameter of the main() function.
1102 * Changed if any arguments were handled.
1103 * @argv: Address of the @argv parameter of main().
1104 * Any parameters understood by g_test_init() stripped before return.
1105 * @...: %NULL-terminated list of special options. Currently the only
1106 * defined option is `"no_g_set_prgname"`, which
1107 * will cause g_test_init() to not call g_set_prgname().
1109 * Initialize the GLib testing framework, e.g. by seeding the
1110 * test random number generator, the name for g_get_prgname()
1111 * and parsing test related command line args.
1113 * So far, the following arguments are understood:
1115 * - `-l`: List test cases available in a test executable.
1116 * - `--seed=SEED`: Provide a random seed to reproduce test
1117 * runs using random numbers.
1118 * - `--verbose`: Run tests verbosely.
1119 * - `-q`, `--quiet`: Run tests quietly.
1120 * - `-p PATH`: Execute all tests matching the given path.
1121 * - `-s PATH`: Skip all tests matching the given path.
1122 * This can also be used to force a test to run that would otherwise
1123 * be skipped (ie, a test whose name contains "/subprocess").
1124 * - `-m {perf|slow|thorough|quick|undefined|no-undefined}`: Execute tests according to these test modes:
1126 * `perf`: Performance tests, may take long and report results.
1128 * `slow`, `thorough`: Slow and thorough tests, may take quite long and maximize coverage.
1130 * `quick`: Quick tests, should run really quickly and give good coverage.
1132 * `undefined`: Tests for undefined behaviour, may provoke programming errors
1133 * under g_test_trap_subprocess() or g_test_expect_message() to check
1134 * that appropriate assertions or warnings are given
1136 * `no-undefined`: Avoid tests for undefined behaviour
1138 * - `--debug-log`: Debug test logging output.
1140 * Since: 2.16
1142 void
1143 g_test_init (int *argc,
1144 char ***argv,
1145 ...)
1147 static char seedstr[4 + 4 * 8 + 1];
1148 va_list args;
1149 gpointer option;
1150 /* make warnings and criticals fatal for all test programs */
1151 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1153 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1154 g_log_set_always_fatal (fatal_mask);
1155 /* check caller args */
1156 g_return_if_fail (argc != NULL);
1157 g_return_if_fail (argv != NULL);
1158 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
1159 mutable_test_config_vars.test_initialized = TRUE;
1161 va_start (args, argv);
1162 while ((option = va_arg (args, char *)))
1164 if (g_strcmp0 (option, "no_g_set_prgname") == 0)
1165 no_g_set_prgname = TRUE;
1167 va_end (args);
1169 /* setup random seed string */
1170 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
1171 test_run_seedstr = seedstr;
1173 /* parse args, sets up mode, changes seed, etc. */
1174 parse_args (argc, argv);
1176 if (!g_get_prgname() && !no_g_set_prgname)
1177 g_set_prgname ((*argv)[0]);
1179 /* sanity check */
1180 if (test_tap_log)
1182 if (test_paths || test_startup_skip_count)
1184 /* Not invoking every test (even if SKIPped) breaks the "1..XX" plan */
1185 g_printerr ("%s: -p and --GTestSkipCount options are incompatible with --tap\n",
1186 (*argv)[0]);
1187 exit (1);
1191 /* verify GRand reliability, needed for reliable seeds */
1192 if (1)
1194 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
1195 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
1196 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
1197 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
1198 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
1199 g_rand_free (rg);
1202 /* check rand seed */
1203 test_run_seed (test_run_seedstr);
1205 /* report program start */
1206 g_log_set_default_handler (gtest_default_log_handler, NULL);
1207 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
1209 test_argv0_dirname = g_path_get_dirname (test_argv0);
1211 /* Make sure we get the real dirname that the test was run from */
1212 if (g_str_has_suffix (test_argv0_dirname, "/.libs"))
1214 gchar *tmp;
1215 tmp = g_path_get_dirname (test_argv0_dirname);
1216 g_free (test_argv0_dirname);
1217 test_argv0_dirname = tmp;
1220 test_disted_files_dir = g_getenv ("G_TEST_SRCDIR");
1221 if (!test_disted_files_dir)
1222 test_disted_files_dir = test_argv0_dirname;
1224 test_built_files_dir = g_getenv ("G_TEST_BUILDDIR");
1225 if (!test_built_files_dir)
1226 test_built_files_dir = test_argv0_dirname;
1229 static void
1230 test_run_seed (const gchar *rseed)
1232 guint seed_failed = 0;
1233 if (test_run_rand)
1234 g_rand_free (test_run_rand);
1235 test_run_rand = NULL;
1236 while (strchr (" \t\v\r\n\f", *rseed))
1237 rseed++;
1238 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
1240 const char *s = rseed + 4;
1241 if (strlen (s) >= 32) /* require 4 * 8 chars */
1243 guint32 seedarray[4];
1244 gchar *p, hexbuf[9] = { 0, };
1245 memcpy (hexbuf, s + 0, 8);
1246 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
1247 seed_failed += p != NULL && *p != 0;
1248 memcpy (hexbuf, s + 8, 8);
1249 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
1250 seed_failed += p != NULL && *p != 0;
1251 memcpy (hexbuf, s + 16, 8);
1252 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
1253 seed_failed += p != NULL && *p != 0;
1254 memcpy (hexbuf, s + 24, 8);
1255 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
1256 seed_failed += p != NULL && *p != 0;
1257 if (!seed_failed)
1259 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
1260 return;
1264 g_error ("Unknown or invalid random seed: %s", rseed);
1268 * g_test_rand_int:
1270 * Get a reproducible random integer number.
1272 * The random numbers generated by the g_test_rand_*() family of functions
1273 * change with every new test program start, unless the --seed option is
1274 * given when starting test programs.
1276 * For individual test cases however, the random number generator is
1277 * reseeded, to avoid dependencies between tests and to make --seed
1278 * effective for all test cases.
1280 * Returns: a random number from the seeded random number generator.
1282 * Since: 2.16
1284 gint32
1285 g_test_rand_int (void)
1287 return g_rand_int (test_run_rand);
1291 * g_test_rand_int_range:
1292 * @begin: the minimum value returned by this function
1293 * @end: the smallest value not to be returned by this function
1295 * Get a reproducible random integer number out of a specified range,
1296 * see g_test_rand_int() for details on test case random numbers.
1298 * Returns: a number with @begin <= number < @end.
1300 * Since: 2.16
1302 gint32
1303 g_test_rand_int_range (gint32 begin,
1304 gint32 end)
1306 return g_rand_int_range (test_run_rand, begin, end);
1310 * g_test_rand_double:
1312 * Get a reproducible random floating point number,
1313 * see g_test_rand_int() for details on test case random numbers.
1315 * Returns: a random number from the seeded random number generator.
1317 * Since: 2.16
1319 double
1320 g_test_rand_double (void)
1322 return g_rand_double (test_run_rand);
1326 * g_test_rand_double_range:
1327 * @range_start: the minimum value returned by this function
1328 * @range_end: the minimum value not returned by this function
1330 * Get a reproducible random floating pointer number out of a specified range,
1331 * see g_test_rand_int() for details on test case random numbers.
1333 * Returns: a number with @range_start <= number < @range_end.
1335 * Since: 2.16
1337 double
1338 g_test_rand_double_range (double range_start,
1339 double range_end)
1341 return g_rand_double_range (test_run_rand, range_start, range_end);
1345 * g_test_timer_start:
1347 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1348 * to be done. Call this function again to restart the timer.
1350 * Since: 2.16
1352 void
1353 g_test_timer_start (void)
1355 if (!test_user_timer)
1356 test_user_timer = g_timer_new();
1357 test_user_stamp = 0;
1358 g_timer_start (test_user_timer);
1362 * g_test_timer_elapsed:
1364 * Get the time since the last start of the timer with g_test_timer_start().
1366 * Returns: the time since the last start of the timer, as a double
1368 * Since: 2.16
1370 double
1371 g_test_timer_elapsed (void)
1373 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1374 return test_user_stamp;
1378 * g_test_timer_last:
1380 * Report the last result of g_test_timer_elapsed().
1382 * Returns: the last result of g_test_timer_elapsed(), as a double
1384 * Since: 2.16
1386 double
1387 g_test_timer_last (void)
1389 return test_user_stamp;
1393 * g_test_minimized_result:
1394 * @minimized_quantity: the reported value
1395 * @format: the format string of the report message
1396 * @...: arguments to pass to the printf() function
1398 * Report the result of a performance or measurement test.
1399 * The test should generally strive to minimize the reported
1400 * quantities (smaller values are better than larger ones),
1401 * this and @minimized_quantity can determine sorting
1402 * order for test result reports.
1404 * Since: 2.16
1406 void
1407 g_test_minimized_result (double minimized_quantity,
1408 const char *format,
1409 ...)
1411 long double largs = minimized_quantity;
1412 gchar *buffer;
1413 va_list args;
1415 va_start (args, format);
1416 buffer = g_strdup_vprintf (format, args);
1417 va_end (args);
1419 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1420 g_free (buffer);
1424 * g_test_maximized_result:
1425 * @maximized_quantity: the reported value
1426 * @format: the format string of the report message
1427 * @...: arguments to pass to the printf() function
1429 * Report the result of a performance or measurement test.
1430 * The test should generally strive to maximize the reported
1431 * quantities (larger values are better than smaller ones),
1432 * this and @maximized_quantity can determine sorting
1433 * order for test result reports.
1435 * Since: 2.16
1437 void
1438 g_test_maximized_result (double maximized_quantity,
1439 const char *format,
1440 ...)
1442 long double largs = maximized_quantity;
1443 gchar *buffer;
1444 va_list args;
1446 va_start (args, format);
1447 buffer = g_strdup_vprintf (format, args);
1448 va_end (args);
1450 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1451 g_free (buffer);
1455 * g_test_message:
1456 * @format: the format string
1457 * @...: printf-like arguments to @format
1459 * Add a message to the test report.
1461 * Since: 2.16
1463 void
1464 g_test_message (const char *format,
1465 ...)
1467 gchar *buffer;
1468 va_list args;
1470 va_start (args, format);
1471 buffer = g_strdup_vprintf (format, args);
1472 va_end (args);
1474 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1475 g_free (buffer);
1479 * g_test_bug_base:
1480 * @uri_pattern: the base pattern for bug URIs
1482 * Specify the base URI for bug reports.
1484 * The base URI is used to construct bug report messages for
1485 * g_test_message() when g_test_bug() is called.
1486 * Calling this function outside of a test case sets the
1487 * default base URI for all test cases. Calling it from within
1488 * a test case changes the base URI for the scope of the test
1489 * case only.
1490 * Bug URIs are constructed by appending a bug specific URI
1491 * portion to @uri_pattern, or by replacing the special string
1492 * '\%s' within @uri_pattern if that is present.
1494 * Since: 2.16
1496 void
1497 g_test_bug_base (const char *uri_pattern)
1499 g_free (test_uri_base);
1500 test_uri_base = g_strdup (uri_pattern);
1504 * g_test_bug:
1505 * @bug_uri_snippet: Bug specific bug tracker URI portion.
1507 * This function adds a message to test reports that
1508 * associates a bug URI with a test case.
1509 * Bug URIs are constructed from a base URI set with g_test_bug_base()
1510 * and @bug_uri_snippet.
1512 * Since: 2.16
1514 void
1515 g_test_bug (const char *bug_uri_snippet)
1517 char *c;
1519 g_return_if_fail (test_uri_base != NULL);
1520 g_return_if_fail (bug_uri_snippet != NULL);
1522 c = strstr (test_uri_base, "%s");
1523 if (c)
1525 char *b = g_strndup (test_uri_base, c - test_uri_base);
1526 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1527 g_free (b);
1528 g_test_message ("Bug Reference: %s", s);
1529 g_free (s);
1531 else
1532 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1536 * g_test_get_root:
1538 * Get the toplevel test suite for the test path API.
1540 * Returns: the toplevel #GTestSuite
1542 * Since: 2.16
1544 GTestSuite*
1545 g_test_get_root (void)
1547 if (!test_suite_root)
1549 test_suite_root = g_test_create_suite ("root");
1550 g_free (test_suite_root->name);
1551 test_suite_root->name = g_strdup ("");
1554 return test_suite_root;
1558 * g_test_run:
1560 * Runs all tests under the toplevel suite which can be retrieved
1561 * with g_test_get_root(). Similar to g_test_run_suite(), the test
1562 * cases to be run are filtered according to test path arguments
1563 * (`-p testpath` and `-s testpath`) as parsed by g_test_init().
1564 * g_test_run_suite() or g_test_run() may only be called once in a
1565 * program.
1567 * In general, the tests and sub-suites within each suite are run in
1568 * the order in which they are defined. However, note that prior to
1569 * GLib 2.36, there was a bug in the `g_test_add_*`
1570 * functions which caused them to create multiple suites with the same
1571 * name, meaning that if you created tests "/foo/simple",
1572 * "/bar/simple", and "/foo/using-bar" in that order, they would get
1573 * run in that order (since g_test_run() would run the first "/foo"
1574 * suite, then the "/bar" suite, then the second "/foo" suite). As of
1575 * 2.36, this bug is fixed, and adding the tests in that order would
1576 * result in a running order of "/foo/simple", "/foo/using-bar",
1577 * "/bar/simple". If this new ordering is sub-optimal (because it puts
1578 * more-complicated tests before simpler ones, making it harder to
1579 * figure out exactly what has failed), you can fix it by changing the
1580 * test paths to group tests by suite in a way that will result in the
1581 * desired running order. Eg, "/simple/foo", "/simple/bar",
1582 * "/complex/foo-using-bar".
1584 * However, you should never make the actual result of a test depend
1585 * on the order that tests are run in. If you need to ensure that some
1586 * particular code runs before or after a given test case, use
1587 * g_test_add(), which lets you specify setup and teardown functions.
1589 * If all tests are skipped, this function will return 0 if
1590 * producing TAP output, or 77 (treated as "skip test" by Automake) otherwise.
1592 * Returns: 0 on success, 1 on failure (assuming it returns at all),
1593 * 0 or 77 if all tests were skipped with g_test_skip()
1595 * Since: 2.16
1598 g_test_run (void)
1600 if (g_test_run_suite (g_test_get_root()) != 0)
1601 return 1;
1603 /* 77 is special to Automake's default driver, but not Automake's TAP driver
1604 * or Perl's prove(1) TAP driver. */
1605 if (test_tap_log)
1606 return 0;
1608 if (test_run_count > 0 && test_run_count == test_skipped_count)
1609 return 77;
1610 else
1611 return 0;
1615 * g_test_create_case:
1616 * @test_name: the name for the test case
1617 * @data_size: the size of the fixture data structure
1618 * @test_data: test data argument for the test functions
1619 * @data_setup: (scope async): the function to set up the fixture data
1620 * @data_test: (scope async): the actual test function
1621 * @data_teardown: (scope async): the function to teardown the fixture data
1623 * Create a new #GTestCase, named @test_name, this API is fairly
1624 * low level, calling g_test_add() or g_test_add_func() is preferable.
1625 * When this test is executed, a fixture structure of size @data_size
1626 * will be automatically allocated and filled with zeros. Then @data_setup is
1627 * called to initialize the fixture. After fixture setup, the actual test
1628 * function @data_test is called. Once the test run completes, the
1629 * fixture structure is torn down by calling @data_teardown and
1630 * after that the memory is automatically released by the test framework.
1632 * Splitting up a test run into fixture setup, test function and
1633 * fixture teardown is most useful if the same fixture is used for
1634 * multiple tests. In this cases, g_test_create_case() will be
1635 * called with the same fixture, but varying @test_name and
1636 * @data_test arguments.
1638 * Returns: a newly allocated #GTestCase.
1640 * Since: 2.16
1642 GTestCase*
1643 g_test_create_case (const char *test_name,
1644 gsize data_size,
1645 gconstpointer test_data,
1646 GTestFixtureFunc data_setup,
1647 GTestFixtureFunc data_test,
1648 GTestFixtureFunc data_teardown)
1650 GTestCase *tc;
1652 g_return_val_if_fail (test_name != NULL, NULL);
1653 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1654 g_return_val_if_fail (test_name[0] != 0, NULL);
1655 g_return_val_if_fail (data_test != NULL, NULL);
1657 tc = g_slice_new0 (GTestCase);
1658 tc->name = g_strdup (test_name);
1659 tc->test_data = (gpointer) test_data;
1660 tc->fixture_size = data_size;
1661 tc->fixture_setup = (void*) data_setup;
1662 tc->fixture_test = (void*) data_test;
1663 tc->fixture_teardown = (void*) data_teardown;
1665 return tc;
1668 static gint
1669 find_suite (gconstpointer l, gconstpointer s)
1671 const GTestSuite *suite = l;
1672 const gchar *str = s;
1674 return strcmp (suite->name, str);
1677 static gint
1678 find_case (gconstpointer l, gconstpointer s)
1680 const GTestCase *tc = l;
1681 const gchar *str = s;
1683 return strcmp (tc->name, str);
1687 * GTestFixtureFunc:
1688 * @fixture: (not nullable): the test fixture
1689 * @user_data: the data provided when registering the test
1691 * The type used for functions that operate on test fixtures. This is
1692 * used for the fixture setup and teardown functions as well as for the
1693 * testcases themselves.
1695 * @user_data is a pointer to the data that was given when registering
1696 * the test case.
1698 * @fixture will be a pointer to the area of memory allocated by the
1699 * test framework, of the size requested. If the requested size was
1700 * zero then @fixture will be equal to @user_data.
1702 * Since: 2.28
1704 void
1705 g_test_add_vtable (const char *testpath,
1706 gsize data_size,
1707 gconstpointer test_data,
1708 GTestFixtureFunc data_setup,
1709 GTestFixtureFunc fixture_test_func,
1710 GTestFixtureFunc data_teardown)
1712 gchar **segments;
1713 guint ui;
1714 GTestSuite *suite;
1716 g_return_if_fail (testpath != NULL);
1717 g_return_if_fail (g_path_is_absolute (testpath));
1718 g_return_if_fail (fixture_test_func != NULL);
1720 suite = g_test_get_root();
1721 segments = g_strsplit (testpath, "/", -1);
1722 for (ui = 0; segments[ui] != NULL; ui++)
1724 const char *seg = segments[ui];
1725 gboolean islast = segments[ui + 1] == NULL;
1726 if (islast && !seg[0])
1727 g_error ("invalid test case path: %s", testpath);
1728 else if (!seg[0])
1729 continue; /* initial or duplicate slash */
1730 else if (!islast)
1732 GSList *l;
1733 GTestSuite *csuite;
1734 l = g_slist_find_custom (suite->suites, seg, find_suite);
1735 if (l)
1737 csuite = l->data;
1739 else
1741 csuite = g_test_create_suite (seg);
1742 g_test_suite_add_suite (suite, csuite);
1744 suite = csuite;
1746 else /* islast */
1748 GTestCase *tc;
1750 if (g_slist_find_custom (suite->cases, seg, find_case))
1751 g_error ("duplicate test case path: %s", testpath);
1753 tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1754 g_test_suite_add (suite, tc);
1757 g_strfreev (segments);
1761 * g_test_fail:
1763 * Indicates that a test failed. This function can be called
1764 * multiple times from the same test. You can use this function
1765 * if your test failed in a recoverable way.
1767 * Do not use this function if the failure of a test could cause
1768 * other tests to malfunction.
1770 * Calling this function will not stop the test from running, you
1771 * need to return from the test function yourself. So you can
1772 * produce additional diagnostic messages or even continue running
1773 * the test.
1775 * If not called from inside a test, this function does nothing.
1777 * Since: 2.30
1779 void
1780 g_test_fail (void)
1782 test_run_success = G_TEST_RUN_FAILURE;
1786 * g_test_incomplete:
1787 * @msg: (nullable): explanation
1789 * Indicates that a test failed because of some incomplete
1790 * functionality. This function can be called multiple times
1791 * from the same test.
1793 * Calling this function will not stop the test from running, you
1794 * need to return from the test function yourself. So you can
1795 * produce additional diagnostic messages or even continue running
1796 * the test.
1798 * If not called from inside a test, this function does nothing.
1800 * Since: 2.38
1802 void
1803 g_test_incomplete (const gchar *msg)
1805 test_run_success = G_TEST_RUN_INCOMPLETE;
1806 g_free (test_run_msg);
1807 test_run_msg = g_strdup (msg);
1811 * g_test_skip:
1812 * @msg: (nullable): explanation
1814 * Indicates that a test was skipped.
1816 * Calling this function will not stop the test from running, you
1817 * need to return from the test function yourself. So you can
1818 * produce additional diagnostic messages or even continue running
1819 * the test.
1821 * If not called from inside a test, this function does nothing.
1823 * Since: 2.38
1825 void
1826 g_test_skip (const gchar *msg)
1828 test_run_success = G_TEST_RUN_SKIPPED;
1829 g_free (test_run_msg);
1830 test_run_msg = g_strdup (msg);
1834 * g_test_failed:
1836 * Returns whether a test has already failed. This will
1837 * be the case when g_test_fail(), g_test_incomplete()
1838 * or g_test_skip() have been called, but also if an
1839 * assertion has failed.
1841 * This can be useful to return early from a test if
1842 * continuing after a failed assertion might be harmful.
1844 * The return value of this function is only meaningful
1845 * if it is called from inside a test function.
1847 * Returns: %TRUE if the test has failed
1849 * Since: 2.38
1851 gboolean
1852 g_test_failed (void)
1854 return test_run_success != G_TEST_RUN_SUCCESS;
1858 * g_test_set_nonfatal_assertions:
1860 * Changes the behaviour of g_assert_cmpstr(), g_assert_cmpint(),
1861 * g_assert_cmpuint(), g_assert_cmphex(), g_assert_cmpfloat(),
1862 * g_assert_true(), g_assert_false(), g_assert_null(), g_assert_no_error(),
1863 * g_assert_error(), g_test_assert_expected_messages() and the various
1864 * g_test_trap_assert_*() macros to not abort to program, but instead
1865 * call g_test_fail() and continue. (This also changes the behavior of
1866 * g_test_fail() so that it will not cause the test program to abort
1867 * after completing the failed test.)
1869 * Note that the g_assert_not_reached() and g_assert() are not
1870 * affected by this.
1872 * This function can only be called after g_test_init().
1874 * Since: 2.38
1876 void
1877 g_test_set_nonfatal_assertions (void)
1879 if (!g_test_config_vars->test_initialized)
1880 g_error ("g_test_set_nonfatal_assertions called without g_test_init");
1881 test_nonfatal_assertions = TRUE;
1882 test_mode_fatal = FALSE;
1886 * GTestFunc:
1888 * The type used for test case functions.
1890 * Since: 2.28
1894 * g_test_add_func:
1895 * @testpath: /-separated test case path name for the test.
1896 * @test_func: (scope async): The test function to invoke for this test.
1898 * Create a new test case, similar to g_test_create_case(). However
1899 * the test is assumed to use no fixture, and test suites are automatically
1900 * created on the fly and added to the root fixture, based on the
1901 * slash-separated portions of @testpath.
1903 * If @testpath includes the component "subprocess" anywhere in it,
1904 * the test will be skipped by default, and only run if explicitly
1905 * required via the `-p` command-line option or g_test_trap_subprocess().
1907 * Since: 2.16
1909 void
1910 g_test_add_func (const char *testpath,
1911 GTestFunc test_func)
1913 g_return_if_fail (testpath != NULL);
1914 g_return_if_fail (testpath[0] == '/');
1915 g_return_if_fail (test_func != NULL);
1916 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1920 * GTestDataFunc:
1921 * @user_data: the data provided when registering the test
1923 * The type used for test case functions that take an extra pointer
1924 * argument.
1926 * Since: 2.28
1930 * g_test_add_data_func:
1931 * @testpath: /-separated test case path name for the test.
1932 * @test_data: Test data argument for the test function.
1933 * @test_func: (scope async): The test function to invoke for this test.
1935 * Create a new test case, similar to g_test_create_case(). However
1936 * the test is assumed to use no fixture, and test suites are automatically
1937 * created on the fly and added to the root fixture, based on the
1938 * slash-separated portions of @testpath. The @test_data argument
1939 * will be passed as first argument to @test_func.
1941 * If @testpath includes the component "subprocess" anywhere in it,
1942 * the test will be skipped by default, and only run if explicitly
1943 * required via the `-p` command-line option or g_test_trap_subprocess().
1945 * Since: 2.16
1947 void
1948 g_test_add_data_func (const char *testpath,
1949 gconstpointer test_data,
1950 GTestDataFunc test_func)
1952 g_return_if_fail (testpath != NULL);
1953 g_return_if_fail (testpath[0] == '/');
1954 g_return_if_fail (test_func != NULL);
1956 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1960 * g_test_add_data_func_full:
1961 * @testpath: /-separated test case path name for the test.
1962 * @test_data: Test data argument for the test function.
1963 * @test_func: The test function to invoke for this test.
1964 * @data_free_func: #GDestroyNotify for @test_data.
1966 * Create a new test case, as with g_test_add_data_func(), but freeing
1967 * @test_data after the test run is complete.
1969 * Since: 2.34
1971 void
1972 g_test_add_data_func_full (const char *testpath,
1973 gpointer test_data,
1974 GTestDataFunc test_func,
1975 GDestroyNotify data_free_func)
1977 g_return_if_fail (testpath != NULL);
1978 g_return_if_fail (testpath[0] == '/');
1979 g_return_if_fail (test_func != NULL);
1981 g_test_add_vtable (testpath, 0, test_data, NULL,
1982 (GTestFixtureFunc) test_func,
1983 (GTestFixtureFunc) data_free_func);
1986 static gboolean
1987 g_test_suite_case_exists (GTestSuite *suite,
1988 const char *test_path)
1990 GSList *iter;
1991 char *slash;
1992 GTestCase *tc;
1994 test_path++;
1995 slash = strchr (test_path, '/');
1997 if (slash)
1999 for (iter = suite->suites; iter; iter = iter->next)
2001 GTestSuite *child_suite = iter->data;
2003 if (!strncmp (child_suite->name, test_path, slash - test_path))
2004 if (g_test_suite_case_exists (child_suite, slash))
2005 return TRUE;
2008 else
2010 for (iter = suite->cases; iter; iter = iter->next)
2012 tc = iter->data;
2013 if (!strcmp (tc->name, test_path))
2014 return TRUE;
2018 return FALSE;
2022 * g_test_create_suite:
2023 * @suite_name: a name for the suite
2025 * Create a new test suite with the name @suite_name.
2027 * Returns: A newly allocated #GTestSuite instance.
2029 * Since: 2.16
2031 GTestSuite*
2032 g_test_create_suite (const char *suite_name)
2034 GTestSuite *ts;
2035 g_return_val_if_fail (suite_name != NULL, NULL);
2036 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
2037 g_return_val_if_fail (suite_name[0] != 0, NULL);
2038 ts = g_slice_new0 (GTestSuite);
2039 ts->name = g_strdup (suite_name);
2040 return ts;
2044 * g_test_suite_add:
2045 * @suite: a #GTestSuite
2046 * @test_case: a #GTestCase
2048 * Adds @test_case to @suite.
2050 * Since: 2.16
2052 void
2053 g_test_suite_add (GTestSuite *suite,
2054 GTestCase *test_case)
2056 g_return_if_fail (suite != NULL);
2057 g_return_if_fail (test_case != NULL);
2059 suite->cases = g_slist_append (suite->cases, test_case);
2063 * g_test_suite_add_suite:
2064 * @suite: a #GTestSuite
2065 * @nestedsuite: another #GTestSuite
2067 * Adds @nestedsuite to @suite.
2069 * Since: 2.16
2071 void
2072 g_test_suite_add_suite (GTestSuite *suite,
2073 GTestSuite *nestedsuite)
2075 g_return_if_fail (suite != NULL);
2076 g_return_if_fail (nestedsuite != NULL);
2078 suite->suites = g_slist_append (suite->suites, nestedsuite);
2082 * g_test_queue_free:
2083 * @gfree_pointer: the pointer to be stored.
2085 * Enqueue a pointer to be released with g_free() during the next
2086 * teardown phase. This is equivalent to calling g_test_queue_destroy()
2087 * with a destroy callback of g_free().
2089 * Since: 2.16
2091 void
2092 g_test_queue_free (gpointer gfree_pointer)
2094 if (gfree_pointer)
2095 g_test_queue_destroy (g_free, gfree_pointer);
2099 * g_test_queue_destroy:
2100 * @destroy_func: Destroy callback for teardown phase.
2101 * @destroy_data: Destroy callback data.
2103 * This function enqueus a callback @destroy_func to be executed
2104 * during the next test case teardown phase. This is most useful
2105 * to auto destruct allocated test resources at the end of a test run.
2106 * Resources are released in reverse queue order, that means enqueueing
2107 * callback A before callback B will cause B() to be called before
2108 * A() during teardown.
2110 * Since: 2.16
2112 void
2113 g_test_queue_destroy (GDestroyNotify destroy_func,
2114 gpointer destroy_data)
2116 DestroyEntry *dentry;
2118 g_return_if_fail (destroy_func != NULL);
2120 dentry = g_slice_new0 (DestroyEntry);
2121 dentry->destroy_func = destroy_func;
2122 dentry->destroy_data = destroy_data;
2123 dentry->next = test_destroy_queue;
2124 test_destroy_queue = dentry;
2127 static gboolean
2128 test_case_run (GTestCase *tc)
2130 gchar *old_base = g_strdup (test_uri_base);
2131 GSList **old_free_list, *filename_free_list = NULL;
2132 gboolean success = G_TEST_RUN_SUCCESS;
2134 old_free_list = test_filename_free_list;
2135 test_filename_free_list = &filename_free_list;
2137 if (++test_run_count <= test_startup_skip_count)
2138 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
2139 else if (test_run_list)
2141 g_print ("%s\n", test_run_name);
2142 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
2144 else
2146 GTimer *test_run_timer = g_timer_new();
2147 long double largs[3];
2148 void *fixture;
2149 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
2150 test_run_forks = 0;
2151 test_run_success = G_TEST_RUN_SUCCESS;
2152 g_clear_pointer (&test_run_msg, g_free);
2153 g_test_log_set_fatal_handler (NULL, NULL);
2154 if (test_paths_skipped && g_slist_find_custom (test_paths_skipped, test_run_name, (GCompareFunc)g_strcmp0))
2155 g_test_skip ("by request (-s option)");
2156 else
2158 g_timer_start (test_run_timer);
2159 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
2160 test_run_seed (test_run_seedstr);
2161 if (tc->fixture_setup)
2162 tc->fixture_setup (fixture, tc->test_data);
2163 tc->fixture_test (fixture, tc->test_data);
2164 test_trap_clear();
2165 while (test_destroy_queue)
2167 DestroyEntry *dentry = test_destroy_queue;
2168 test_destroy_queue = dentry->next;
2169 dentry->destroy_func (dentry->destroy_data);
2170 g_slice_free (DestroyEntry, dentry);
2172 if (tc->fixture_teardown)
2173 tc->fixture_teardown (fixture, tc->test_data);
2174 if (tc->fixture_size)
2175 g_free (fixture);
2176 g_timer_stop (test_run_timer);
2178 success = test_run_success;
2179 test_run_success = G_TEST_RUN_FAILURE;
2180 largs[0] = success; /* OK */
2181 largs[1] = test_run_forks;
2182 largs[2] = g_timer_elapsed (test_run_timer, NULL);
2183 g_test_log (G_TEST_LOG_STOP_CASE, test_run_name, test_run_msg, G_N_ELEMENTS (largs), largs);
2184 g_clear_pointer (&test_run_msg, g_free);
2185 g_timer_destroy (test_run_timer);
2188 g_slist_free_full (filename_free_list, g_free);
2189 test_filename_free_list = old_free_list;
2190 g_free (test_uri_base);
2191 test_uri_base = old_base;
2193 return (success == G_TEST_RUN_SUCCESS ||
2194 success == G_TEST_RUN_SKIPPED);
2197 static gboolean
2198 path_has_prefix (const char *path,
2199 const char *prefix)
2201 int prefix_len = strlen (prefix);
2203 return (strncmp (path, prefix, prefix_len) == 0 &&
2204 (path[prefix_len] == '\0' ||
2205 path[prefix_len] == '/'));
2208 static gboolean
2209 test_should_run (const char *test_path,
2210 const char *cmp_path)
2212 if (strstr (test_run_name, "/subprocess"))
2214 if (g_strcmp0 (test_path, cmp_path) == 0)
2215 return TRUE;
2217 if (g_test_verbose ())
2218 g_print ("GTest: skipping: %s\n", test_run_name);
2219 return FALSE;
2222 return !cmp_path || path_has_prefix (test_path, cmp_path);
2225 /* Recurse through @suite, running tests matching @path (or all tests
2226 * if @path is %NULL).
2228 static int
2229 g_test_run_suite_internal (GTestSuite *suite,
2230 const char *path)
2232 guint n_bad = 0;
2233 gchar *old_name = test_run_name;
2234 GSList *iter;
2236 g_return_val_if_fail (suite != NULL, -1);
2238 g_test_log (G_TEST_LOG_START_SUITE, suite->name, NULL, 0, NULL);
2240 for (iter = suite->cases; iter; iter = iter->next)
2242 GTestCase *tc = iter->data;
2244 test_run_name = g_build_path ("/", old_name, tc->name, NULL);
2245 if (test_should_run (test_run_name, path))
2247 if (!test_case_run (tc))
2248 n_bad++;
2250 g_free (test_run_name);
2253 for (iter = suite->suites; iter; iter = iter->next)
2255 GTestSuite *ts = iter->data;
2257 test_run_name = g_build_path ("/", old_name, ts->name, NULL);
2258 if (!path || path_has_prefix (path, test_run_name))
2259 n_bad += g_test_run_suite_internal (ts, path);
2260 g_free (test_run_name);
2263 test_run_name = old_name;
2265 g_test_log (G_TEST_LOG_STOP_SUITE, suite->name, NULL, 0, NULL);
2267 return n_bad;
2270 static int
2271 g_test_suite_count (GTestSuite *suite)
2273 int n = 0;
2274 GSList *iter;
2276 g_return_val_if_fail (suite != NULL, -1);
2278 for (iter = suite->cases; iter; iter = iter->next)
2280 GTestCase *tc = iter->data;
2282 if (strcmp (tc->name, "subprocess") != 0)
2283 n++;
2286 for (iter = suite->suites; iter; iter = iter->next)
2288 GTestSuite *ts = iter->data;
2290 if (strcmp (ts->name, "subprocess") != 0)
2291 n += g_test_suite_count (ts);
2294 return n;
2298 * g_test_run_suite:
2299 * @suite: a #GTestSuite
2301 * Execute the tests within @suite and all nested #GTestSuites.
2302 * The test suites to be executed are filtered according to
2303 * test path arguments (`-p testpath` and `-s testpath`) as parsed by
2304 * g_test_init(). See the g_test_run() documentation for more
2305 * information on the order that tests are run in.
2308 * g_test_run_suite() or g_test_run() may only be called once
2309 * in a program.
2311 * Returns: 0 on success
2313 * Since: 2.16
2316 g_test_run_suite (GTestSuite *suite)
2318 int n_bad = 0;
2320 g_return_val_if_fail (g_test_run_once == TRUE, -1);
2322 g_test_run_once = FALSE;
2323 test_count = g_test_suite_count (suite);
2325 test_run_name = g_strdup_printf ("/%s", suite->name);
2327 if (test_paths)
2329 GSList *iter;
2331 for (iter = test_paths; iter; iter = iter->next)
2332 n_bad += g_test_run_suite_internal (suite, iter->data);
2334 else
2335 n_bad = g_test_run_suite_internal (suite, NULL);
2337 g_free (test_run_name);
2338 test_run_name = NULL;
2340 return n_bad;
2343 static void
2344 gtest_default_log_handler (const gchar *log_domain,
2345 GLogLevelFlags log_level,
2346 const gchar *message,
2347 gpointer unused_data)
2349 const gchar *strv[16];
2350 gboolean fatal = FALSE;
2351 gchar *msg;
2352 guint i = 0;
2354 if (log_domain)
2356 strv[i++] = log_domain;
2357 strv[i++] = "-";
2359 if (log_level & G_LOG_FLAG_FATAL)
2361 strv[i++] = "FATAL-";
2362 fatal = TRUE;
2364 if (log_level & G_LOG_FLAG_RECURSION)
2365 strv[i++] = "RECURSIVE-";
2366 if (log_level & G_LOG_LEVEL_ERROR)
2367 strv[i++] = "ERROR";
2368 if (log_level & G_LOG_LEVEL_CRITICAL)
2369 strv[i++] = "CRITICAL";
2370 if (log_level & G_LOG_LEVEL_WARNING)
2371 strv[i++] = "WARNING";
2372 if (log_level & G_LOG_LEVEL_MESSAGE)
2373 strv[i++] = "MESSAGE";
2374 if (log_level & G_LOG_LEVEL_INFO)
2375 strv[i++] = "INFO";
2376 if (log_level & G_LOG_LEVEL_DEBUG)
2377 strv[i++] = "DEBUG";
2378 strv[i++] = ": ";
2379 strv[i++] = message;
2380 strv[i++] = NULL;
2382 msg = g_strjoinv ("", (gchar**) strv);
2383 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
2384 g_log_default_handler (log_domain, log_level, message, unused_data);
2386 g_free (msg);
2389 void
2390 g_assertion_message (const char *domain,
2391 const char *file,
2392 int line,
2393 const char *func,
2394 const char *message)
2396 char lstr[32];
2397 char *s;
2399 if (!message)
2400 message = "code should not be reached";
2401 g_snprintf (lstr, 32, "%d", line);
2402 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
2403 "ERROR:", file, ":", lstr, ":",
2404 func, func[0] ? ":" : "",
2405 " ", message, NULL);
2406 g_printerr ("**\n%s\n", s);
2408 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
2410 if (test_nonfatal_assertions)
2412 g_free (s);
2413 g_test_fail ();
2414 return;
2417 /* store assertion message in global variable, so that it can be found in a
2418 * core dump */
2419 if (__glib_assert_msg != NULL)
2420 /* free the old one */
2421 free (__glib_assert_msg);
2422 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
2423 strcpy (__glib_assert_msg, s);
2425 g_free (s);
2427 if (test_in_subprocess)
2429 /* If this is a test case subprocess then it probably hit this
2430 * assertion on purpose, so just exit() rather than abort()ing,
2431 * to avoid triggering any system crash-reporting daemon.
2433 _exit (1);
2435 else
2436 g_abort ();
2440 * g_assertion_message_expr: (skip)
2441 * @domain: (nullable):
2442 * @file:
2443 * @line:
2444 * @func:
2445 * @expr: (nullable):
2447 void
2448 g_assertion_message_expr (const char *domain,
2449 const char *file,
2450 int line,
2451 const char *func,
2452 const char *expr)
2454 char *s;
2455 if (!expr)
2456 s = g_strdup ("code should not be reached");
2457 else
2458 s = g_strconcat ("assertion failed: (", expr, ")", NULL);
2459 g_assertion_message (domain, file, line, func, s);
2460 g_free (s);
2462 /* Normally g_assertion_message() won't return, but we need this for
2463 * when test_nonfatal_assertions is set, since
2464 * g_assertion_message_expr() is used for always-fatal assertions.
2466 if (test_in_subprocess)
2467 _exit (1);
2468 else
2469 g_abort ();
2472 void
2473 g_assertion_message_cmpnum (const char *domain,
2474 const char *file,
2475 int line,
2476 const char *func,
2477 const char *expr,
2478 long double arg1,
2479 const char *cmp,
2480 long double arg2,
2481 char numtype)
2483 char *s = NULL;
2485 switch (numtype)
2487 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;
2488 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;
2489 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr, (double) arg1, cmp, (double) arg2); break;
2490 /* ideally use: floats=%.7g double=%.17g */
2492 g_assertion_message (domain, file, line, func, s);
2493 g_free (s);
2496 void
2497 g_assertion_message_cmpstr (const char *domain,
2498 const char *file,
2499 int line,
2500 const char *func,
2501 const char *expr,
2502 const char *arg1,
2503 const char *cmp,
2504 const char *arg2)
2506 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
2507 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
2508 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
2509 g_free (t1);
2510 g_free (t2);
2511 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
2512 g_free (a1);
2513 g_free (a2);
2514 g_assertion_message (domain, file, line, func, s);
2515 g_free (s);
2518 void
2519 g_assertion_message_error (const char *domain,
2520 const char *file,
2521 int line,
2522 const char *func,
2523 const char *expr,
2524 const GError *error,
2525 GQuark error_domain,
2526 int error_code)
2528 GString *gstring;
2530 /* This is used by both g_assert_error() and g_assert_no_error(), so there
2531 * are three cases: expected an error but got the wrong error, expected
2532 * an error but got no error, and expected no error but got an error.
2535 gstring = g_string_new ("assertion failed ");
2536 if (error_domain)
2537 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
2538 g_quark_to_string (error_domain), error_code);
2539 else
2540 g_string_append_printf (gstring, "(%s == NULL): ", expr);
2542 if (error)
2543 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
2544 g_quark_to_string (error->domain), error->code);
2545 else
2546 g_string_append_printf (gstring, "%s is NULL", expr);
2548 g_assertion_message (domain, file, line, func, gstring->str);
2549 g_string_free (gstring, TRUE);
2553 * g_strcmp0:
2554 * @str1: (nullable): a C string or %NULL
2555 * @str2: (nullable): another C string or %NULL
2557 * Compares @str1 and @str2 like strcmp(). Handles %NULL
2558 * gracefully by sorting it before non-%NULL strings.
2559 * Comparing two %NULL pointers returns 0.
2561 * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
2563 * Since: 2.16
2566 g_strcmp0 (const char *str1,
2567 const char *str2)
2569 if (!str1)
2570 return -(str1 != str2);
2571 if (!str2)
2572 return str1 != str2;
2573 return strcmp (str1, str2);
2576 static void
2577 test_trap_clear (void)
2579 test_trap_last_status = 0;
2580 test_trap_last_pid = 0;
2581 g_clear_pointer (&test_trap_last_subprocess, g_free);
2582 g_clear_pointer (&test_trap_last_stdout, g_free);
2583 g_clear_pointer (&test_trap_last_stderr, g_free);
2586 #ifdef G_OS_UNIX
2588 static int
2589 sane_dup2 (int fd1,
2590 int fd2)
2592 int ret;
2594 ret = dup2 (fd1, fd2);
2595 while (ret < 0 && errno == EINTR);
2596 return ret;
2599 #endif
2601 typedef struct {
2602 GPid pid;
2603 GMainLoop *loop;
2604 int child_status;
2606 GIOChannel *stdout_io;
2607 gboolean echo_stdout;
2608 GString *stdout_str;
2610 GIOChannel *stderr_io;
2611 gboolean echo_stderr;
2612 GString *stderr_str;
2613 } WaitForChildData;
2615 static void
2616 check_complete (WaitForChildData *data)
2618 if (data->child_status != -1 && data->stdout_io == NULL && data->stderr_io == NULL)
2619 g_main_loop_quit (data->loop);
2622 static void
2623 child_exited (GPid pid,
2624 gint status,
2625 gpointer user_data)
2627 WaitForChildData *data = user_data;
2629 #ifdef G_OS_UNIX
2630 if (WIFEXITED (status)) /* normal exit */
2631 data->child_status = WEXITSTATUS (status); /* 0..255 */
2632 else if (WIFSIGNALED (status) && WTERMSIG (status) == SIGALRM)
2633 data->child_status = G_TEST_STATUS_TIMED_OUT;
2634 else if (WIFSIGNALED (status))
2635 data->child_status = (WTERMSIG (status) << 12); /* signalled */
2636 else /* WCOREDUMP (status) */
2637 data->child_status = 512; /* coredump */
2638 #else
2639 data->child_status = status;
2640 #endif
2642 check_complete (data);
2645 static gboolean
2646 child_timeout (gpointer user_data)
2648 WaitForChildData *data = user_data;
2650 #ifdef G_OS_WIN32
2651 TerminateProcess (data->pid, G_TEST_STATUS_TIMED_OUT);
2652 #else
2653 kill (data->pid, SIGALRM);
2654 #endif
2656 return FALSE;
2659 static gboolean
2660 child_read (GIOChannel *io, GIOCondition cond, gpointer user_data)
2662 WaitForChildData *data = user_data;
2663 GIOStatus status;
2664 gsize nread, nwrote, total;
2665 gchar buf[4096];
2666 FILE *echo_file = NULL;
2668 status = g_io_channel_read_chars (io, buf, sizeof (buf), &nread, NULL);
2669 if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF)
2671 // FIXME data->error = (status == G_IO_STATUS_ERROR);
2672 if (io == data->stdout_io)
2673 g_clear_pointer (&data->stdout_io, g_io_channel_unref);
2674 else
2675 g_clear_pointer (&data->stderr_io, g_io_channel_unref);
2677 check_complete (data);
2678 return FALSE;
2680 else if (status == G_IO_STATUS_AGAIN)
2681 return TRUE;
2683 if (io == data->stdout_io)
2685 g_string_append_len (data->stdout_str, buf, nread);
2686 if (data->echo_stdout)
2687 echo_file = stdout;
2689 else
2691 g_string_append_len (data->stderr_str, buf, nread);
2692 if (data->echo_stderr)
2693 echo_file = stderr;
2696 if (echo_file)
2698 for (total = 0; total < nread; total += nwrote)
2700 int errsv;
2702 nwrote = fwrite (buf + total, 1, nread - total, echo_file);
2703 errsv = errno;
2704 if (nwrote == 0)
2705 g_error ("write failed: %s", g_strerror (errsv));
2709 return TRUE;
2712 static void
2713 wait_for_child (GPid pid,
2714 int stdout_fd, gboolean echo_stdout,
2715 int stderr_fd, gboolean echo_stderr,
2716 guint64 timeout)
2718 WaitForChildData data;
2719 GMainContext *context;
2720 GSource *source;
2722 data.pid = pid;
2723 data.child_status = -1;
2725 context = g_main_context_new ();
2726 data.loop = g_main_loop_new (context, FALSE);
2728 source = g_child_watch_source_new (pid);
2729 g_source_set_callback (source, (GSourceFunc) child_exited, &data, NULL);
2730 g_source_attach (source, context);
2731 g_source_unref (source);
2733 data.echo_stdout = echo_stdout;
2734 data.stdout_str = g_string_new (NULL);
2735 data.stdout_io = g_io_channel_unix_new (stdout_fd);
2736 g_io_channel_set_close_on_unref (data.stdout_io, TRUE);
2737 g_io_channel_set_encoding (data.stdout_io, NULL, NULL);
2738 g_io_channel_set_buffered (data.stdout_io, FALSE);
2739 source = g_io_create_watch (data.stdout_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2740 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2741 g_source_attach (source, context);
2742 g_source_unref (source);
2744 data.echo_stderr = echo_stderr;
2745 data.stderr_str = g_string_new (NULL);
2746 data.stderr_io = g_io_channel_unix_new (stderr_fd);
2747 g_io_channel_set_close_on_unref (data.stderr_io, TRUE);
2748 g_io_channel_set_encoding (data.stderr_io, NULL, NULL);
2749 g_io_channel_set_buffered (data.stderr_io, FALSE);
2750 source = g_io_create_watch (data.stderr_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2751 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2752 g_source_attach (source, context);
2753 g_source_unref (source);
2755 if (timeout)
2757 source = g_timeout_source_new (0);
2758 g_source_set_ready_time (source, g_get_monotonic_time () + timeout);
2759 g_source_set_callback (source, (GSourceFunc) child_timeout, &data, NULL);
2760 g_source_attach (source, context);
2761 g_source_unref (source);
2764 g_main_loop_run (data.loop);
2765 g_main_loop_unref (data.loop);
2766 g_main_context_unref (context);
2768 test_trap_last_pid = pid;
2769 test_trap_last_status = data.child_status;
2770 test_trap_last_stdout = g_string_free (data.stdout_str, FALSE);
2771 test_trap_last_stderr = g_string_free (data.stderr_str, FALSE);
2773 g_clear_pointer (&data.stdout_io, g_io_channel_unref);
2774 g_clear_pointer (&data.stderr_io, g_io_channel_unref);
2778 * g_test_trap_fork:
2779 * @usec_timeout: Timeout for the forked test in micro seconds.
2780 * @test_trap_flags: Flags to modify forking behaviour.
2782 * Fork the current test program to execute a test case that might
2783 * not return or that might abort.
2785 * If @usec_timeout is non-0, the forked test case is aborted and
2786 * considered failing if its run time exceeds it.
2788 * The forking behavior can be configured with the #GTestTrapFlags flags.
2790 * In the following example, the test code forks, the forked child
2791 * process produces some sample output and exits successfully.
2792 * The forking parent process then asserts successful child program
2793 * termination and validates child program outputs.
2795 * |[<!-- language="C" -->
2796 * static void
2797 * test_fork_patterns (void)
2799 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2801 * g_print ("some stdout text: somagic17\n");
2802 * g_printerr ("some stderr text: semagic43\n");
2803 * exit (0); // successful test run
2805 * g_test_trap_assert_passed ();
2806 * g_test_trap_assert_stdout ("*somagic17*");
2807 * g_test_trap_assert_stderr ("*semagic43*");
2809 * ]|
2811 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2813 * Since: 2.16
2815 * Deprecated: This function is implemented only on Unix platforms,
2816 * and is not always reliable due to problems inherent in
2817 * fork-without-exec. Use g_test_trap_subprocess() instead.
2819 gboolean
2820 g_test_trap_fork (guint64 usec_timeout,
2821 GTestTrapFlags test_trap_flags)
2823 #ifdef G_OS_UNIX
2824 int stdout_pipe[2] = { -1, -1 };
2825 int stderr_pipe[2] = { -1, -1 };
2826 int errsv;
2828 test_trap_clear();
2829 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0)
2831 errsv = errno;
2832 g_error ("failed to create pipes to fork test program: %s", g_strerror (errsv));
2834 test_trap_last_pid = fork ();
2835 errsv = errno;
2836 if (test_trap_last_pid < 0)
2837 g_error ("failed to fork test program: %s", g_strerror (errsv));
2838 if (test_trap_last_pid == 0) /* child */
2840 int fd0 = -1;
2841 close (stdout_pipe[0]);
2842 close (stderr_pipe[0]);
2843 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2845 fd0 = g_open ("/dev/null", O_RDONLY, 0);
2846 if (fd0 < 0)
2847 g_error ("failed to open /dev/null for stdin redirection");
2849 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2851 errsv = errno;
2852 g_error ("failed to dup2() in forked test program: %s", g_strerror (errsv));
2854 if (fd0 >= 3)
2855 close (fd0);
2856 if (stdout_pipe[1] >= 3)
2857 close (stdout_pipe[1]);
2858 if (stderr_pipe[1] >= 3)
2859 close (stderr_pipe[1]);
2860 return TRUE;
2862 else /* parent */
2864 test_run_forks++;
2865 close (stdout_pipe[1]);
2866 close (stderr_pipe[1]);
2868 wait_for_child (test_trap_last_pid,
2869 stdout_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT),
2870 stderr_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR),
2871 usec_timeout);
2872 return FALSE;
2874 #else
2875 g_message ("Not implemented: g_test_trap_fork");
2877 return FALSE;
2878 #endif
2882 * g_test_trap_subprocess:
2883 * @test_path: (nullable): Test to run in a subprocess
2884 * @usec_timeout: Timeout for the subprocess test in micro seconds.
2885 * @test_flags: Flags to modify subprocess behaviour.
2887 * Respawns the test program to run only @test_path in a subprocess.
2888 * This can be used for a test case that might not return, or that
2889 * might abort.
2891 * If @test_path is %NULL then the same test is re-run in a subprocess.
2892 * You can use g_test_subprocess() to determine whether the test is in
2893 * a subprocess or not.
2895 * @test_path can also be the name of the parent test, followed by
2896 * "`/subprocess/`" and then a name for the specific subtest (or just
2897 * ending with "`/subprocess`" if the test only has one child test);
2898 * tests with names of this form will automatically be skipped in the
2899 * parent process.
2901 * If @usec_timeout is non-0, the test subprocess is aborted and
2902 * considered failing if its run time exceeds it.
2904 * The subprocess behavior can be configured with the
2905 * #GTestSubprocessFlags flags.
2907 * You can use methods such as g_test_trap_assert_passed(),
2908 * g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to
2909 * check the results of the subprocess. (But note that
2910 * g_test_trap_assert_stdout() and g_test_trap_assert_stderr()
2911 * cannot be used if @test_flags specifies that the child should
2912 * inherit the parent stdout/stderr.)
2914 * If your `main ()` needs to behave differently in
2915 * the subprocess, you can call g_test_subprocess() (after calling
2916 * g_test_init()) to see whether you are in a subprocess.
2918 * The following example tests that calling
2919 * `my_object_new(1000000)` will abort with an error
2920 * message.
2922 * |[<!-- language="C" -->
2923 * static void
2924 * test_create_large_object (void)
2926 * if (g_test_subprocess ())
2928 * my_object_new (1000000);
2929 * return;
2932 * // Reruns this same test in a subprocess
2933 * g_test_trap_subprocess (NULL, 0, 0);
2934 * g_test_trap_assert_failed ();
2935 * g_test_trap_assert_stderr ("*ERROR*too large*");
2938 * int
2939 * main (int argc, char **argv)
2941 * g_test_init (&argc, &argv, NULL);
2943 * g_test_add_func ("/myobject/create_large_object",
2944 * test_create_large_object);
2945 * return g_test_run ();
2947 * ]|
2949 * Since: 2.38
2951 void
2952 g_test_trap_subprocess (const char *test_path,
2953 guint64 usec_timeout,
2954 GTestSubprocessFlags test_flags)
2956 GError *error = NULL;
2957 GPtrArray *argv;
2958 GSpawnFlags flags;
2959 int stdout_fd, stderr_fd;
2960 GPid pid;
2962 /* Sanity check that they used GTestSubprocessFlags, not GTestTrapFlags */
2963 g_assert ((test_flags & (G_TEST_TRAP_INHERIT_STDIN | G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR)) == 0);
2965 if (test_path)
2967 if (!g_test_suite_case_exists (g_test_get_root (), test_path))
2968 g_error ("g_test_trap_subprocess: test does not exist: %s", test_path);
2970 else
2972 test_path = test_run_name;
2975 if (g_test_verbose ())
2976 g_print ("GTest: subprocess: %s\n", test_path);
2978 test_trap_clear ();
2979 test_trap_last_subprocess = g_strdup (test_path);
2981 argv = g_ptr_array_new ();
2982 g_ptr_array_add (argv, test_argv0);
2983 g_ptr_array_add (argv, "-q");
2984 g_ptr_array_add (argv, "-p");
2985 g_ptr_array_add (argv, (char *)test_path);
2986 g_ptr_array_add (argv, "--GTestSubprocess");
2987 if (test_log_fd != -1)
2989 char log_fd_buf[128];
2991 g_ptr_array_add (argv, "--GTestLogFD");
2992 g_snprintf (log_fd_buf, sizeof (log_fd_buf), "%d", test_log_fd);
2993 g_ptr_array_add (argv, log_fd_buf);
2995 g_ptr_array_add (argv, NULL);
2997 flags = G_SPAWN_DO_NOT_REAP_CHILD;
2998 if (test_flags & G_TEST_TRAP_INHERIT_STDIN)
2999 flags |= G_SPAWN_CHILD_INHERITS_STDIN;
3001 if (!g_spawn_async_with_pipes (test_initial_cwd,
3002 (char **)argv->pdata,
3003 NULL, flags,
3004 NULL, NULL,
3005 &pid, NULL, &stdout_fd, &stderr_fd,
3006 &error))
3008 g_error ("g_test_trap_subprocess() failed: %s\n",
3009 error->message);
3011 g_ptr_array_free (argv, TRUE);
3013 wait_for_child (pid,
3014 stdout_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDOUT),
3015 stderr_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDERR),
3016 usec_timeout);
3020 * g_test_subprocess:
3022 * Returns %TRUE (after g_test_init() has been called) if the test
3023 * program is running under g_test_trap_subprocess().
3025 * Returns: %TRUE if the test program is running under
3026 * g_test_trap_subprocess().
3028 * Since: 2.38
3030 gboolean
3031 g_test_subprocess (void)
3033 return test_in_subprocess;
3037 * g_test_trap_has_passed:
3039 * Check the result of the last g_test_trap_subprocess() call.
3041 * Returns: %TRUE if the last test subprocess terminated successfully.
3043 * Since: 2.16
3045 gboolean
3046 g_test_trap_has_passed (void)
3048 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
3052 * g_test_trap_reached_timeout:
3054 * Check the result of the last g_test_trap_subprocess() call.
3056 * Returns: %TRUE if the last test subprocess got killed due to a timeout.
3058 * Since: 2.16
3060 gboolean
3061 g_test_trap_reached_timeout (void)
3063 return test_trap_last_status == G_TEST_STATUS_TIMED_OUT;
3066 static gboolean
3067 log_child_output (const gchar *process_id)
3069 gchar *escaped;
3071 escaped = g_strescape (test_trap_last_stdout, NULL);
3072 g_test_message ("child process (%s) stdout: \"%s\"", process_id, escaped);
3073 g_free (escaped);
3075 escaped = g_strescape (test_trap_last_stderr, NULL);
3076 g_test_message ("child process (%s) stderr: \"%s\"", process_id, escaped);
3077 g_free (escaped);
3079 /* so we can use short-circuiting:
3080 * logged_child_output = logged_child_output || log_child_output (...) */
3081 return TRUE;
3084 void
3085 g_test_trap_assertions (const char *domain,
3086 const char *file,
3087 int line,
3088 const char *func,
3089 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
3090 const char *pattern)
3092 gboolean must_pass = assertion_flags == 0;
3093 gboolean must_fail = assertion_flags == 1;
3094 gboolean match_result = 0 == (assertion_flags & 1);
3095 gboolean logged_child_output = FALSE;
3096 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
3097 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
3098 const char *match_error = match_result ? "failed to match" : "contains invalid match";
3099 char *process_id;
3101 #ifdef G_OS_UNIX
3102 if (test_trap_last_subprocess != NULL)
3104 process_id = g_strdup_printf ("%s [%d]", test_trap_last_subprocess,
3105 test_trap_last_pid);
3107 else if (test_trap_last_pid != 0)
3108 process_id = g_strdup_printf ("%d", test_trap_last_pid);
3109 #else
3110 if (test_trap_last_subprocess != NULL)
3111 process_id = g_strdup (test_trap_last_subprocess);
3112 #endif
3113 else
3114 g_error ("g_test_trap_ assertion with no trapped test");
3116 if (must_pass && !g_test_trap_has_passed())
3118 char *msg;
3120 logged_child_output = logged_child_output || log_child_output (process_id);
3122 msg = g_strdup_printf ("child process (%s) failed unexpectedly", process_id);
3123 g_assertion_message (domain, file, line, func, msg);
3124 g_free (msg);
3126 if (must_fail && g_test_trap_has_passed())
3128 char *msg;
3130 logged_child_output = logged_child_output || log_child_output (process_id);
3132 msg = g_strdup_printf ("child process (%s) did not fail as expected", process_id);
3133 g_assertion_message (domain, file, line, func, msg);
3134 g_free (msg);
3136 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
3138 char *msg;
3140 logged_child_output = logged_child_output || log_child_output (process_id);
3142 msg = g_strdup_printf ("stdout of child process (%s) %s: %s", process_id, match_error, stdout_pattern);
3143 g_assertion_message (domain, file, line, func, msg);
3144 g_free (msg);
3146 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
3148 char *msg;
3150 logged_child_output = logged_child_output || log_child_output (process_id);
3152 msg = g_strdup_printf ("stderr of child process (%s) %s: %s", process_id, match_error, stderr_pattern);
3153 g_assertion_message (domain, file, line, func, msg);
3154 g_free (msg);
3156 g_free (process_id);
3159 static void
3160 gstring_overwrite_int (GString *gstring,
3161 guint pos,
3162 guint32 vuint)
3164 vuint = g_htonl (vuint);
3165 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
3168 static void
3169 gstring_append_int (GString *gstring,
3170 guint32 vuint)
3172 vuint = g_htonl (vuint);
3173 g_string_append_len (gstring, (const gchar*) &vuint, 4);
3176 static void
3177 gstring_append_double (GString *gstring,
3178 double vdouble)
3180 union { double vdouble; guint64 vuint64; } u;
3181 u.vdouble = vdouble;
3182 u.vuint64 = GUINT64_TO_BE (u.vuint64);
3183 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
3186 static guint8*
3187 g_test_log_dump (GTestLogMsg *msg,
3188 guint *len)
3190 GString *gstring = g_string_sized_new (1024);
3191 guint ui;
3192 gstring_append_int (gstring, 0); /* message length */
3193 gstring_append_int (gstring, msg->log_type);
3194 gstring_append_int (gstring, msg->n_strings);
3195 gstring_append_int (gstring, msg->n_nums);
3196 gstring_append_int (gstring, 0); /* reserved */
3197 for (ui = 0; ui < msg->n_strings; ui++)
3199 guint l = strlen (msg->strings[ui]);
3200 gstring_append_int (gstring, l);
3201 g_string_append_len (gstring, msg->strings[ui], l);
3203 for (ui = 0; ui < msg->n_nums; ui++)
3204 gstring_append_double (gstring, msg->nums[ui]);
3205 *len = gstring->len;
3206 gstring_overwrite_int (gstring, 0, *len); /* message length */
3207 return (guint8*) g_string_free (gstring, FALSE);
3210 static inline long double
3211 net_double (const gchar **ipointer)
3213 union { guint64 vuint64; double vdouble; } u;
3214 guint64 aligned_int64;
3215 memcpy (&aligned_int64, *ipointer, 8);
3216 *ipointer += 8;
3217 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
3218 return u.vdouble;
3221 static inline guint32
3222 net_int (const gchar **ipointer)
3224 guint32 aligned_int;
3225 memcpy (&aligned_int, *ipointer, 4);
3226 *ipointer += 4;
3227 return g_ntohl (aligned_int);
3230 static gboolean
3231 g_test_log_extract (GTestLogBuffer *tbuffer)
3233 const gchar *p = tbuffer->data->str;
3234 GTestLogMsg msg;
3235 guint mlength;
3236 if (tbuffer->data->len < 4 * 5)
3237 return FALSE;
3238 mlength = net_int (&p);
3239 if (tbuffer->data->len < mlength)
3240 return FALSE;
3241 msg.log_type = net_int (&p);
3242 msg.n_strings = net_int (&p);
3243 msg.n_nums = net_int (&p);
3244 if (net_int (&p) == 0)
3246 guint ui;
3247 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
3248 msg.nums = g_new0 (long double, msg.n_nums);
3249 for (ui = 0; ui < msg.n_strings; ui++)
3251 guint sl = net_int (&p);
3252 msg.strings[ui] = g_strndup (p, sl);
3253 p += sl;
3255 for (ui = 0; ui < msg.n_nums; ui++)
3256 msg.nums[ui] = net_double (&p);
3257 if (p <= tbuffer->data->str + mlength)
3259 g_string_erase (tbuffer->data, 0, mlength);
3260 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
3261 return TRUE;
3264 g_free (msg.nums);
3265 g_strfreev (msg.strings);
3268 g_error ("corrupt log stream from test program");
3269 return FALSE;
3273 * g_test_log_buffer_new:
3275 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3277 GTestLogBuffer*
3278 g_test_log_buffer_new (void)
3280 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
3281 tb->data = g_string_sized_new (1024);
3282 return tb;
3286 * g_test_log_buffer_free:
3288 * Internal function for gtester to free test log messages, no ABI guarantees provided.
3290 void
3291 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
3293 g_return_if_fail (tbuffer != NULL);
3294 while (tbuffer->msgs)
3295 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
3296 g_string_free (tbuffer->data, TRUE);
3297 g_free (tbuffer);
3301 * g_test_log_buffer_push:
3303 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3305 void
3306 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
3307 guint n_bytes,
3308 const guint8 *bytes)
3310 g_return_if_fail (tbuffer != NULL);
3311 if (n_bytes)
3313 gboolean more_messages;
3314 g_return_if_fail (bytes != NULL);
3315 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
3317 more_messages = g_test_log_extract (tbuffer);
3318 while (more_messages);
3323 * g_test_log_buffer_pop:
3325 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
3327 GTestLogMsg*
3328 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
3330 GTestLogMsg *msg = NULL;
3331 g_return_val_if_fail (tbuffer != NULL, NULL);
3332 if (tbuffer->msgs)
3334 GSList *slist = g_slist_last (tbuffer->msgs);
3335 msg = slist->data;
3336 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
3338 return msg;
3342 * g_test_log_msg_free:
3344 * Internal function for gtester to free test log messages, no ABI guarantees provided.
3346 void
3347 g_test_log_msg_free (GTestLogMsg *tmsg)
3349 g_return_if_fail (tmsg != NULL);
3350 g_strfreev (tmsg->strings);
3351 g_free (tmsg->nums);
3352 g_free (tmsg);
3355 static gchar *
3356 g_test_build_filename_va (GTestFileType file_type,
3357 const gchar *first_path,
3358 va_list ap)
3360 const gchar *pathv[16];
3361 gint num_path_segments;
3363 if (file_type == G_TEST_DIST)
3364 pathv[0] = test_disted_files_dir;
3365 else if (file_type == G_TEST_BUILT)
3366 pathv[0] = test_built_files_dir;
3367 else
3368 g_assert_not_reached ();
3370 pathv[1] = first_path;
3372 for (num_path_segments = 2; num_path_segments < G_N_ELEMENTS (pathv); num_path_segments++)
3374 pathv[num_path_segments] = va_arg (ap, const char *);
3375 if (pathv[num_path_segments] == NULL)
3376 break;
3379 g_assert_cmpint (num_path_segments, <, G_N_ELEMENTS (pathv));
3381 return g_build_filenamev ((gchar **) pathv);
3385 * g_test_build_filename:
3386 * @file_type: the type of file (built vs. distributed)
3387 * @first_path: the first segment of the pathname
3388 * @...: %NULL-terminated additional path segments
3390 * Creates the pathname to a data file that is required for a test.
3392 * This function is conceptually similar to g_build_filename() except
3393 * that the first argument has been replaced with a #GTestFileType
3394 * argument.
3396 * The data file should either have been distributed with the module
3397 * containing the test (%G_TEST_DIST) or built as part of the build
3398 * system of that module (%G_TEST_BUILT).
3400 * In order for this function to work in srcdir != builddir situations,
3401 * the G_TEST_SRCDIR and G_TEST_BUILDDIR environment variables need to
3402 * have been defined. As of 2.38, this is done by the glib.mk
3403 * included in GLib. Please ensure that your copy is up to date before
3404 * using this function.
3406 * In case neither variable is set, this function will fall back to
3407 * using the dirname portion of argv[0], possibly removing ".libs".
3408 * This allows for casual running of tests directly from the commandline
3409 * in the srcdir == builddir case and should also support running of
3410 * installed tests, assuming the data files have been installed in the
3411 * same relative path as the test binary.
3413 * Returns: the path of the file, to be freed using g_free()
3415 * Since: 2.38
3418 * GTestFileType:
3419 * @G_TEST_DIST: a file that was included in the distribution tarball
3420 * @G_TEST_BUILT: a file that was built on the compiling machine
3422 * The type of file to return the filename for, when used with
3423 * g_test_build_filename().
3425 * These two options correspond rather directly to the 'dist' and
3426 * 'built' terminology that automake uses and are explicitly used to
3427 * distinguish between the 'srcdir' and 'builddir' being separate. All
3428 * files in your project should either be dist (in the
3429 * `EXTRA_DIST` or `dist_schema_DATA`
3430 * sense, in which case they will always be in the srcdir) or built (in
3431 * the `BUILT_SOURCES` sense, in which case they will
3432 * always be in the builddir).
3434 * Note: as a general rule of automake, files that are generated only as
3435 * part of the build-from-git process (but then are distributed with the
3436 * tarball) always go in srcdir (even if doing a srcdir != builddir
3437 * build from git) and are considered as distributed files.
3439 * Since: 2.38
3441 gchar *
3442 g_test_build_filename (GTestFileType file_type,
3443 const gchar *first_path,
3444 ...)
3446 gchar *result;
3447 va_list ap;
3449 g_assert (g_test_initialized ());
3451 va_start (ap, first_path);
3452 result = g_test_build_filename_va (file_type, first_path, ap);
3453 va_end (ap);
3455 return result;
3459 * g_test_get_dir:
3460 * @file_type: the type of file (built vs. distributed)
3462 * Gets the pathname of the directory containing test files of the type
3463 * specified by @file_type.
3465 * This is approximately the same as calling g_test_build_filename("."),
3466 * but you don't need to free the return value.
3468 * Returns: (type filename): the path of the directory, owned by GLib
3470 * Since: 2.38
3472 const gchar *
3473 g_test_get_dir (GTestFileType file_type)
3475 g_assert (g_test_initialized ());
3477 if (file_type == G_TEST_DIST)
3478 return test_disted_files_dir;
3479 else if (file_type == G_TEST_BUILT)
3480 return test_built_files_dir;
3482 g_assert_not_reached ();
3486 * g_test_get_filename:
3487 * @file_type: the type of file (built vs. distributed)
3488 * @first_path: the first segment of the pathname
3489 * @...: %NULL-terminated additional path segments
3491 * Gets the pathname to a data file that is required for a test.
3493 * This is the same as g_test_build_filename() with two differences.
3494 * The first difference is that must only use this function from within
3495 * a testcase function. The second difference is that you need not free
3496 * the return value -- it will be automatically freed when the testcase
3497 * finishes running.
3499 * It is safe to use this function from a thread inside of a testcase
3500 * but you must ensure that all such uses occur before the main testcase
3501 * function returns (ie: it is best to ensure that all threads have been
3502 * joined).
3504 * Returns: the path, automatically freed at the end of the testcase
3506 * Since: 2.38
3508 const gchar *
3509 g_test_get_filename (GTestFileType file_type,
3510 const gchar *first_path,
3511 ...)
3513 gchar *result;
3514 GSList *node;
3515 va_list ap;
3517 g_assert (g_test_initialized ());
3518 if (test_filename_free_list == NULL)
3519 g_error ("g_test_get_filename() can only be used within testcase functions");
3521 va_start (ap, first_path);
3522 result = g_test_build_filename_va (file_type, first_path, ap);
3523 va_end (ap);
3525 node = g_slist_prepend (NULL, result);
3527 node->next = *test_filename_free_list;
3528 while (!g_atomic_pointer_compare_and_exchange (test_filename_free_list, node->next, node));
3530 return result;
3533 /* --- macros docs START --- */
3535 * g_test_add:
3536 * @testpath: The test path for a new test case.
3537 * @Fixture: The type of a fixture data structure.
3538 * @tdata: Data argument for the test functions.
3539 * @fsetup: The function to set up the fixture data.
3540 * @ftest: The actual test function.
3541 * @fteardown: The function to tear down the fixture data.
3543 * Hook up a new test case at @testpath, similar to g_test_add_func().
3544 * A fixture data structure with setup and teardown functions may be provided,
3545 * similar to g_test_create_case().
3547 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
3548 * fteardown() callbacks can expect a @Fixture pointer as their first argument
3549 * in a type safe manner. They otherwise have type #GTestFixtureFunc.
3551 * Since: 2.16
3553 /* --- macros docs END --- */