GSimpleProxyResolver: convert docs to markdown
[glib.git] / glib / gtestutils.c
blob4d8dbb84d300a721876152e959a423afed9fa8a5
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 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: <link linkend="gtester">gtester</link>,
63 * <link linkend="gtester-report">gtester-report</link>
65 * GLib provides a framework for writing and maintaining unit tests
66 * in parallel to the code they are testing. The API is designed according
67 * to established concepts found in the other test frameworks (JUnit, NUnit,
68 * RUnit), which in turn is based on smalltalk unit testing concepts.
70 * <variablelist>
71 * <varlistentry>
72 * <term>Test case</term>
73 * <listitem>Tests (test methods) are grouped together with their
74 * fixture into test cases.</listitem>
75 * </varlistentry>
76 * <varlistentry>
77 * <term>Fixture</term>
78 * <listitem>A test fixture consists of fixture data and setup and
79 * teardown methods to establish the environment for the test
80 * functions. We use fresh fixtures, i.e. fixtures are newly set
81 * up and torn down around each test invocation to avoid dependencies
82 * between tests.</listitem>
83 * </varlistentry>
84 * <varlistentry>
85 * <term>Test suite</term>
86 * <listitem>Test cases can be grouped into test suites, to allow
87 * subsets of the available tests to be run. Test suites can be
88 * grouped into other test suites as well.</listitem>
89 * </varlistentry>
90 * </variablelist>
91 * The API is designed to handle creation and registration of test suites
92 * and test cases implicitly. A simple call like
93 * |[
94 * g_test_add_func ("/misc/assertions", test_assertions);
95 * ]|
96 * creates a test suite called "misc" with a single test case named
97 * "assertions", which consists of running the test_assertions function.
99 * In addition to the traditional g_assert(), the test framework provides
100 * an extended set of assertions for string and numerical comparisons:
101 * g_assert_cmpfloat(), g_assert_cmpint(), g_assert_cmpuint(),
102 * g_assert_cmphex(), g_assert_cmpstr(). The advantage of these variants
103 * over plain g_assert() is that the assertion messages can be more
104 * elaborate, and include the values of the compared entities.
106 * GLib ships with two utilities called gtester and gtester-report to
107 * facilitate running tests and producing nicely formatted test reports.
111 * g_test_initialized:
113 * Returns %TRUE if g_test_init() has been called.
115 * Returns: %TRUE if g_test_init() has been called.
117 * Since: 2.36
121 * g_test_quick:
123 * Returns %TRUE if tests are run in quick mode.
124 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
125 * there is no "medium speed".
127 * Returns: %TRUE if in quick mode
131 * g_test_slow:
133 * Returns %TRUE if tests are run in slow mode.
134 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
135 * there is no "medium speed".
137 * Returns: the opposite of g_test_quick()
141 * g_test_thorough:
143 * Returns %TRUE if tests are run in thorough mode, equivalent to
144 * g_test_slow().
146 * Returns: the same thing as g_test_slow()
150 * g_test_perf:
152 * Returns %TRUE if tests are run in performance mode.
154 * Returns: %TRUE if in performance mode
158 * g_test_undefined:
160 * Returns %TRUE if tests may provoke assertions and other formally-undefined
161 * behaviour, to verify that appropriate warnings are given. It might, in some
162 * cases, be useful to turn this off if running tests under valgrind.
164 * Returns: %TRUE if tests may provoke programming errors
168 * g_test_verbose:
170 * Returns %TRUE if tests are run in verbose mode.
171 * The default is neither g_test_verbose() nor g_test_quiet().
173 * Returns: %TRUE if in verbose mode
177 * g_test_quiet:
179 * Returns %TRUE if tests are run in quiet mode.
180 * The default is neither g_test_verbose() nor g_test_quiet().
182 * Returns: %TRUE if in quiet mode
186 * g_test_queue_unref:
187 * @gobject: the object to unref
189 * Enqueue an object to be released with g_object_unref() during
190 * the next teardown phase. This is equivalent to calling
191 * g_test_queue_destroy() with a destroy callback of g_object_unref().
193 * Since: 2.16
197 * GTestTrapFlags:
198 * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
199 * <filename>/dev/null</filename> so it cannot be observed on the
200 * console during test runs. The actual output is still captured
201 * though to allow later tests with g_test_trap_assert_stdout().
202 * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
203 * <filename>/dev/null</filename> so it cannot be observed on the
204 * console during test runs. The actual output is still captured
205 * though to allow later tests with g_test_trap_assert_stderr().
206 * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
207 * child process is shared with stdin of its parent process.
208 * It is redirected to <filename>/dev/null</filename> otherwise.
210 * Test traps are guards around forked tests.
211 * These flags determine what traps to set.
213 * Deprecated: #GTestTrapFlags is used only with g_test_trap_fork(),
214 * which is deprecated. g_test_trap_subprocess() uses
215 * #GTestTrapSubprocessFlags.
219 * GTestSubprocessFlags:
220 * @G_TEST_SUBPROCESS_INHERIT_STDIN: If this flag is given, the child
221 * process will inherit the parent's stdin. Otherwise, the child's
222 * stdin is redirected to <filename>/dev/null</filename>.
223 * @G_TEST_SUBPROCESS_INHERIT_STDOUT: If this flag is given, the child
224 * process will inherit the parent's stdout. Otherwise, the child's
225 * stdout will not be visible, but it will be captured to allow
226 * later tests with g_test_trap_assert_stdout().
227 * @G_TEST_SUBPROCESS_INHERIT_STDERR: If this flag is given, the child
228 * process will inherit the parent's stderr. Otherwise, the child's
229 * stderr will not be visible, but it will be captured to allow
230 * later tests with g_test_trap_assert_stderr().
232 * Flags to pass to g_test_trap_subprocess() to control input and output.
234 * Note that in contrast with g_test_trap_fork(), the default is to
235 * not show stdout and stderr.
239 * g_test_trap_assert_passed:
241 * Assert that the last test subprocess passed.
242 * See g_test_trap_subprocess().
244 * Since: 2.16
248 * g_test_trap_assert_failed:
250 * Assert that the last test subprocess failed.
251 * See g_test_trap_subprocess().
253 * This is sometimes used to test situations that are formally considered to
254 * be undefined behaviour, like inputs that fail a g_return_if_fail()
255 * check. In these situations you should skip the entire test, including the
256 * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
257 * to indicate that undefined behaviour may be tested.
259 * Since: 2.16
263 * g_test_trap_assert_stdout:
264 * @soutpattern: a glob-style
265 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
267 * Assert that the stdout output of the last test subprocess matches
268 * @soutpattern. See g_test_trap_subprocess().
270 * Since: 2.16
274 * g_test_trap_assert_stdout_unmatched:
275 * @soutpattern: a glob-style
276 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
278 * Assert that the stdout output of the last test subprocess
279 * does not match @soutpattern. See g_test_trap_subprocess().
281 * Since: 2.16
285 * g_test_trap_assert_stderr:
286 * @serrpattern: a glob-style
287 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
289 * Assert that the stderr output of the last test subprocess
290 * matches @serrpattern. See g_test_trap_subprocess().
292 * This is sometimes used to test situations that are formally
293 * considered to be undefined behaviour, like code that hits a
294 * g_assert() or g_error(). In these situations you should skip the
295 * entire test, including the call to g_test_trap_subprocess(), unless
296 * g_test_undefined() returns %TRUE to indicate that undefined
297 * behaviour may be tested.
299 * Since: 2.16
303 * g_test_trap_assert_stderr_unmatched:
304 * @serrpattern: a glob-style
305 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
307 * Assert that the stderr output of the last test subprocess
308 * does not match @serrpattern. See g_test_trap_subprocess().
310 * Since: 2.16
314 * g_test_rand_bit:
316 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
317 * for details on test case random numbers.
319 * Since: 2.16
323 * g_assert:
324 * @expr: the expression to check
326 * Debugging macro to terminate the application if the assertion
327 * fails. If the assertion fails (i.e. the expression is not true),
328 * an error message is logged and the application is terminated.
330 * The macro can be turned off in final releases of code by defining
331 * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
335 * g_assert_not_reached:
337 * Debugging macro to terminate the application if it is ever
338 * reached. If it is reached, an error message is logged and the
339 * application is terminated.
341 * The macro can be turned off in final releases of code by defining
342 * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
346 * g_assert_true:
347 * @expr: the expression to check
349 * Debugging macro to check that an expression is true.
351 * If the assertion fails (i.e. the expression is not true),
352 * an error message is logged and the application is either
353 * terminated or the testcase marked as failed.
355 * See g_test_set_nonfatal_assertions().
357 * Since: 2.38
361 * g_assert_false:
362 * @expr: the expression to check
364 * Debugging macro to check an expression is false.
366 * If the assertion fails (i.e. the expression is not false),
367 * an error message is logged and the application is either
368 * terminated or the testcase marked as failed.
370 * See g_test_set_nonfatal_assertions().
372 * Since: 2.38
376 * g_assert_null:
377 * @expr: the expression to check
379 * Debugging macro to check an expression is %NULL.
381 * If the assertion fails (i.e. the expression is not %NULL),
382 * an error message is logged and the application is either
383 * terminated or the testcase marked as failed.
385 * See g_test_set_nonfatal_assertions().
387 * Since: 2.38
391 * g_assert_nonnull:
392 * @expr: the expression to check
394 * Debugging macro to check an expression is not %NULL.
396 * If the assertion fails (i.e. the expression is %NULL),
397 * an error message is logged and the application is either
398 * terminated or the testcase marked as failed.
400 * See g_test_set_nonfatal_assertions().
402 * Since: 2.40
406 * g_assert_cmpstr:
407 * @s1: a string (may be %NULL)
408 * @cmp: The comparison operator to use.
409 * One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
410 * @s2: another string (may be %NULL)
412 * Debugging macro to compare two strings. If the comparison fails,
413 * an error message is logged and the application is either terminated
414 * or the testcase marked as failed.
415 * The strings are compared using g_strcmp0().
417 * The effect of <literal>g_assert_cmpstr (s1, op, s2)</literal> is
418 * the same as <literal>g_assert_true (g_strcmp0 (s1, s2) op 0)</literal>.
419 * The advantage of this macro is that it can produce a message that
420 * includes the actual values of @s1 and @s2.
422 * |[
423 * g_assert_cmpstr (mystring, ==, "fubar");
424 * ]|
426 * Since: 2.16
430 * g_assert_cmpint:
431 * @n1: an integer
432 * @cmp: The comparison operator to use.
433 * One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
434 * @n2: another integer
436 * Debugging macro to compare two integers.
438 * The effect of <literal>g_assert_cmpint (n1, op, n2)</literal> is
439 * the same as <literal>g_assert_true (n1 op n2)</literal>. The advantage
440 * of this macro is that it can produce a message that includes the
441 * actual values of @n1 and @n2.
443 * Since: 2.16
447 * g_assert_cmpuint:
448 * @n1: an unsigned integer
449 * @cmp: The comparison operator to use.
450 * One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
451 * @n2: another unsigned integer
453 * Debugging macro to compare two unsigned integers.
455 * The effect of <literal>g_assert_cmpuint (n1, op, n2)</literal> is
456 * the same as <literal>g_assert_true (n1 op n2)</literal>. The advantage
457 * of this macro is that it can produce a message that includes the
458 * actual values of @n1 and @n2.
460 * Since: 2.16
464 * g_assert_cmphex:
465 * @n1: an unsigned integer
466 * @cmp: The comparison operator to use.
467 * One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
468 * @n2: another unsigned integer
470 * Debugging macro to compare to unsigned integers.
472 * This is a variant of g_assert_cmpuint() that displays the numbers
473 * in hexadecimal notation in the message.
475 * Since: 2.16
479 * g_assert_cmpfloat:
480 * @n1: an floating point number
481 * @cmp: The comparison operator to use.
482 * One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
483 * @n2: another floating point number
485 * Debugging macro to compare two floating point numbers.
487 * The effect of <literal>g_assert_cmpfloat (n1, op, n2)</literal> is
488 * the same as <literal>g_assert_true (n1 op n2)</literal>. The advantage
489 * of this macro is that it can produce a message that includes the
490 * actual values of @n1 and @n2.
492 * Since: 2.16
496 * g_assert_no_error:
497 * @err: a #GError, possibly %NULL
499 * Debugging macro to check that a #GError is not set.
501 * The effect of <literal>g_assert_no_error (err)</literal> is
502 * the same as <literal>g_assert_true (err == NULL)</literal>. The advantage
503 * of this macro is that it can produce a message that includes
504 * the error message and code.
506 * Since: 2.20
510 * g_assert_error:
511 * @err: a #GError, possibly %NULL
512 * @dom: the expected error domain (a #GQuark)
513 * @c: the expected error code
515 * Debugging macro to check that a method has returned
516 * the correct #GError.
518 * The effect of <literal>g_assert_error (err, dom, c)</literal> is
519 * the same as <literal>g_assert_true (err != NULL &amp;&amp; err->domain
520 * == dom &amp;&amp; err->code == c)</literal>. The advantage of this
521 * macro is that it can produce a message that includes the incorrect
522 * error message and code.
524 * This can only be used to test for a specific error. If you want to
525 * test that @err is set, but don't care what it's set to, just use
526 * <literal>g_assert (err != NULL)</literal>
528 * Since: 2.20
532 * GTestCase:
534 * An opaque structure representing a test case.
538 * GTestSuite:
540 * An opaque structure representing a test suite.
544 /* Global variable for storing assertion messages; this is the counterpart to
545 * glibc's (private) __abort_msg variable, and allows developers and crash
546 * analysis systems like Apport and ABRT to fish out assertion messages from
547 * core dumps, instead of having to catch them on screen output.
549 GLIB_VAR char *__glib_assert_msg;
550 char *__glib_assert_msg = NULL;
552 /* --- constants --- */
553 #define G_TEST_STATUS_TIMED_OUT 1024
555 /* --- structures --- */
556 struct GTestCase
558 gchar *name;
559 guint fixture_size;
560 void (*fixture_setup) (void*, gconstpointer);
561 void (*fixture_test) (void*, gconstpointer);
562 void (*fixture_teardown) (void*, gconstpointer);
563 gpointer test_data;
565 struct GTestSuite
567 gchar *name;
568 GSList *suites;
569 GSList *cases;
571 typedef struct DestroyEntry DestroyEntry;
572 struct DestroyEntry
574 DestroyEntry *next;
575 GDestroyNotify destroy_func;
576 gpointer destroy_data;
579 /* --- prototypes --- */
580 static void test_run_seed (const gchar *rseed);
581 static void test_trap_clear (void);
582 static guint8* g_test_log_dump (GTestLogMsg *msg,
583 guint *len);
584 static void gtest_default_log_handler (const gchar *log_domain,
585 GLogLevelFlags log_level,
586 const gchar *message,
587 gpointer unused_data);
590 typedef enum {
591 G_TEST_RUN_SUCCESS,
592 G_TEST_RUN_SKIPPED,
593 G_TEST_RUN_FAILURE,
594 G_TEST_RUN_INCOMPLETE
595 } GTestResult;
597 /* --- variables --- */
598 static int test_log_fd = -1;
599 static gboolean test_mode_fatal = TRUE;
600 static gboolean g_test_run_once = TRUE;
601 static gboolean test_run_list = FALSE;
602 static gchar *test_run_seedstr = NULL;
603 static GRand *test_run_rand = NULL;
604 static gchar *test_run_name = "";
605 static GSList **test_filename_free_list;
606 static guint test_run_forks = 0;
607 static guint test_run_count = 0;
608 static guint test_skipped_count = 0;
609 static GTestResult test_run_success = G_TEST_RUN_FAILURE;
610 static gchar *test_run_msg = NULL;
611 static guint test_startup_skip_count = 0;
612 static GTimer *test_user_timer = NULL;
613 static double test_user_stamp = 0;
614 static GSList *test_paths = NULL;
615 static GSList *test_paths_skipped = NULL;
616 static GTestSuite *test_suite_root = NULL;
617 static int test_trap_last_status = 0;
618 static GPid test_trap_last_pid = 0;
619 static char *test_trap_last_subprocess = NULL;
620 static char *test_trap_last_stdout = NULL;
621 static char *test_trap_last_stderr = NULL;
622 static char *test_uri_base = NULL;
623 static gboolean test_debug_log = FALSE;
624 static gboolean test_tap_log = FALSE;
625 static gboolean test_nonfatal_assertions = FALSE;
626 static DestroyEntry *test_destroy_queue = NULL;
627 static char *test_argv0 = NULL;
628 static char *test_argv0_dirname;
629 static const char *test_disted_files_dir;
630 static const char *test_built_files_dir;
631 static char *test_initial_cwd = NULL;
632 static gboolean test_in_subprocess = FALSE;
633 static GTestConfig mutable_test_config_vars = {
634 FALSE, /* test_initialized */
635 TRUE, /* test_quick */
636 FALSE, /* test_perf */
637 FALSE, /* test_verbose */
638 FALSE, /* test_quiet */
639 TRUE, /* test_undefined */
641 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
642 static gboolean no_g_set_prgname = FALSE;
644 /* --- functions --- */
645 const char*
646 g_test_log_type_name (GTestLogType log_type)
648 switch (log_type)
650 case G_TEST_LOG_NONE: return "none";
651 case G_TEST_LOG_ERROR: return "error";
652 case G_TEST_LOG_START_BINARY: return "binary";
653 case G_TEST_LOG_LIST_CASE: return "list";
654 case G_TEST_LOG_SKIP_CASE: return "skip";
655 case G_TEST_LOG_START_CASE: return "start";
656 case G_TEST_LOG_STOP_CASE: return "stop";
657 case G_TEST_LOG_MIN_RESULT: return "minperf";
658 case G_TEST_LOG_MAX_RESULT: return "maxperf";
659 case G_TEST_LOG_MESSAGE: return "message";
660 case G_TEST_LOG_START_SUITE: return "start suite";
661 case G_TEST_LOG_STOP_SUITE: return "stop suite";
663 return "???";
666 static void
667 g_test_log_send (guint n_bytes,
668 const guint8 *buffer)
670 if (test_log_fd >= 0)
672 int r;
674 r = write (test_log_fd, buffer, n_bytes);
675 while (r < 0 && errno == EINTR);
677 if (test_debug_log)
679 GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
680 GTestLogMsg *msg;
681 guint ui;
682 g_test_log_buffer_push (lbuffer, n_bytes, buffer);
683 msg = g_test_log_buffer_pop (lbuffer);
684 g_warn_if_fail (msg != NULL);
685 g_warn_if_fail (lbuffer->data->len == 0);
686 g_test_log_buffer_free (lbuffer);
687 /* print message */
688 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
689 for (ui = 0; ui < msg->n_strings; ui++)
690 g_printerr (":{%s}", msg->strings[ui]);
691 if (msg->n_nums)
693 g_printerr (":(");
694 for (ui = 0; ui < msg->n_nums; ui++)
696 if ((long double) (long) msg->nums[ui] == msg->nums[ui])
697 g_printerr ("%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
698 else
699 g_printerr ("%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
701 g_printerr (")");
703 g_printerr (":LOG*}\n");
704 g_test_log_msg_free (msg);
708 static void
709 g_test_log (GTestLogType lbit,
710 const gchar *string1,
711 const gchar *string2,
712 guint n_args,
713 long double *largs)
715 gboolean fail;
716 GTestLogMsg msg;
717 gchar *astrings[3] = { NULL, NULL, NULL };
718 guint8 *dbuffer;
719 guint32 dbufferlen;
721 switch (lbit)
723 case G_TEST_LOG_START_BINARY:
724 if (test_tap_log)
725 g_print ("# random seed: %s\n", string2);
726 else if (g_test_verbose())
727 g_print ("GTest: random seed: %s\n", string2);
728 break;
729 case G_TEST_LOG_START_SUITE:
730 if (test_tap_log)
732 if (string1[0] != 0)
733 g_print ("# Start of %s tests\n", string1);
735 break;
736 case G_TEST_LOG_STOP_SUITE:
737 if (test_tap_log)
739 if (string1[0] != 0)
740 g_print ("# End of %s tests\n", string1);
741 else
742 g_print ("1..%d\n", test_run_count);
744 break;
745 case G_TEST_LOG_STOP_CASE:
746 fail = largs[0] != G_TEST_RUN_SUCCESS && largs[0] != G_TEST_RUN_SKIPPED;
747 if (test_tap_log)
749 g_print ("%s %d %s", fail ? "not ok" : "ok", test_run_count, string1);
750 if (largs[0] == G_TEST_RUN_INCOMPLETE)
751 g_print (" # TODO %s\n", string2 ? string2 : "");
752 else if (largs[0] == G_TEST_RUN_SKIPPED)
753 g_print (" # SKIP %s\n", string2 ? string2 : "");
754 else
755 g_print ("\n");
757 else if (g_test_verbose())
758 g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
759 else if (!g_test_quiet())
760 g_print ("%s\n", fail ? "FAIL" : "OK");
761 if (fail && test_mode_fatal)
763 if (test_tap_log)
764 g_print ("Bail out!\n");
765 abort();
767 if (largs[0] == G_TEST_RUN_SKIPPED)
768 test_skipped_count++;
769 break;
770 case G_TEST_LOG_MIN_RESULT:
771 if (test_tap_log)
772 g_print ("# min perf: %s\n", string1);
773 else if (g_test_verbose())
774 g_print ("(MINPERF:%s)\n", string1);
775 break;
776 case G_TEST_LOG_MAX_RESULT:
777 if (test_tap_log)
778 g_print ("# max perf: %s\n", string1);
779 else if (g_test_verbose())
780 g_print ("(MAXPERF:%s)\n", string1);
781 break;
782 case G_TEST_LOG_MESSAGE:
783 case G_TEST_LOG_ERROR:
784 if (test_tap_log)
785 g_print ("# %s\n", string1);
786 else if (g_test_verbose())
787 g_print ("(MSG: %s)\n", string1);
788 break;
789 default: ;
792 msg.log_type = lbit;
793 msg.n_strings = (string1 != NULL) + (string1 && string2);
794 msg.strings = astrings;
795 astrings[0] = (gchar*) string1;
796 astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
797 msg.n_nums = n_args;
798 msg.nums = largs;
799 dbuffer = g_test_log_dump (&msg, &dbufferlen);
800 g_test_log_send (dbufferlen, dbuffer);
801 g_free (dbuffer);
803 switch (lbit)
805 case G_TEST_LOG_START_CASE:
806 if (test_tap_log)
808 else if (g_test_verbose())
809 g_print ("GTest: run: %s\n", string1);
810 else if (!g_test_quiet())
811 g_print ("%s: ", string1);
812 break;
813 default: ;
817 /* We intentionally parse the command line without GOptionContext
818 * because otherwise you would never be able to test it.
820 static void
821 parse_args (gint *argc_p,
822 gchar ***argv_p)
824 guint argc = *argc_p;
825 gchar **argv = *argv_p;
826 guint i, e;
828 test_argv0 = argv[0];
829 test_initial_cwd = g_get_current_dir ();
831 /* parse known args */
832 for (i = 1; i < argc; i++)
834 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
836 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
837 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
838 g_log_set_always_fatal (fatal_mask);
839 argv[i] = NULL;
841 else if (strcmp (argv[i], "--keep-going") == 0 ||
842 strcmp (argv[i], "-k") == 0)
844 test_mode_fatal = FALSE;
845 argv[i] = NULL;
847 else if (strcmp (argv[i], "--debug-log") == 0)
849 test_debug_log = TRUE;
850 argv[i] = NULL;
852 else if (strcmp (argv[i], "--tap") == 0)
854 test_tap_log = TRUE;
855 argv[i] = NULL;
857 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
859 gchar *equal = argv[i] + 12;
860 if (*equal == '=')
861 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
862 else if (i + 1 < argc)
864 argv[i++] = NULL;
865 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
867 argv[i] = NULL;
869 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
871 gchar *equal = argv[i] + 16;
872 if (*equal == '=')
873 test_startup_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
874 else if (i + 1 < argc)
876 argv[i++] = NULL;
877 test_startup_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
879 argv[i] = NULL;
881 else if (strcmp ("--GTestSubprocess", argv[i]) == 0)
883 test_in_subprocess = TRUE;
884 /* We typically expect these child processes to crash, and some
885 * tests spawn a *lot* of them. Avoid spamming system crash
886 * collection programs such as systemd-coredump and abrt.
888 #ifdef HAVE_SYS_RESOURCE_H
890 struct rlimit limit = { 0, 0 };
891 (void) setrlimit (RLIMIT_CORE, &limit);
893 #endif
894 argv[i] = NULL;
896 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
898 gchar *equal = argv[i] + 2;
899 if (*equal == '=')
900 test_paths = g_slist_prepend (test_paths, equal + 1);
901 else if (i + 1 < argc)
903 argv[i++] = NULL;
904 test_paths = g_slist_prepend (test_paths, argv[i]);
906 argv[i] = NULL;
908 else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
910 gchar *equal = argv[i] + 2;
911 if (*equal == '=')
912 test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
913 else if (i + 1 < argc)
915 argv[i++] = NULL;
916 test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
918 argv[i] = NULL;
920 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
922 gchar *equal = argv[i] + 2;
923 const gchar *mode = "";
924 if (*equal == '=')
925 mode = equal + 1;
926 else if (i + 1 < argc)
928 argv[i++] = NULL;
929 mode = argv[i];
931 if (strcmp (mode, "perf") == 0)
932 mutable_test_config_vars.test_perf = TRUE;
933 else if (strcmp (mode, "slow") == 0)
934 mutable_test_config_vars.test_quick = FALSE;
935 else if (strcmp (mode, "thorough") == 0)
936 mutable_test_config_vars.test_quick = FALSE;
937 else if (strcmp (mode, "quick") == 0)
939 mutable_test_config_vars.test_quick = TRUE;
940 mutable_test_config_vars.test_perf = FALSE;
942 else if (strcmp (mode, "undefined") == 0)
943 mutable_test_config_vars.test_undefined = TRUE;
944 else if (strcmp (mode, "no-undefined") == 0)
945 mutable_test_config_vars.test_undefined = FALSE;
946 else
947 g_error ("unknown test mode: -m %s", mode);
948 argv[i] = NULL;
950 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
952 mutable_test_config_vars.test_quiet = TRUE;
953 mutable_test_config_vars.test_verbose = FALSE;
954 argv[i] = NULL;
956 else if (strcmp ("--verbose", argv[i]) == 0)
958 mutable_test_config_vars.test_quiet = FALSE;
959 mutable_test_config_vars.test_verbose = TRUE;
960 argv[i] = NULL;
962 else if (strcmp ("-l", argv[i]) == 0)
964 test_run_list = TRUE;
965 argv[i] = NULL;
967 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
969 gchar *equal = argv[i] + 6;
970 if (*equal == '=')
971 test_run_seedstr = equal + 1;
972 else if (i + 1 < argc)
974 argv[i++] = NULL;
975 test_run_seedstr = argv[i];
977 argv[i] = NULL;
979 else if (strcmp ("-?", argv[i]) == 0 ||
980 strcmp ("-h", argv[i]) == 0 ||
981 strcmp ("--help", argv[i]) == 0)
983 printf ("Usage:\n"
984 " %s [OPTION...]\n\n"
985 "Help Options:\n"
986 " -h, --help Show help options\n\n"
987 "Test Options:\n"
988 " --g-fatal-warnings Make all warnings fatal\n"
989 " -l List test cases available in a test executable\n"
990 " -m {perf|slow|thorough|quick} Execute tests according to mode\n"
991 " -m {undefined|no-undefined} Execute tests according to mode\n"
992 " -p TESTPATH Only start test cases matching TESTPATH\n"
993 " -s TESTPATH Skip all tests matching TESTPATH\n"
994 " -seed=SEEDSTRING Start tests with random seed SEEDSTRING\n"
995 " --debug-log debug test logging output\n"
996 " -q, --quiet Run tests quietly\n"
997 " --verbose Run tests verbosely\n",
998 argv[0]);
999 exit (0);
1002 /* collapse argv */
1003 e = 1;
1004 for (i = 1; i < argc; i++)
1005 if (argv[i])
1007 argv[e++] = argv[i];
1008 if (i >= e)
1009 argv[i] = NULL;
1011 *argc_p = e;
1015 * g_test_init:
1016 * @argc: Address of the @argc parameter of the main() function.
1017 * Changed if any arguments were handled.
1018 * @argv: Address of the @argv parameter of main().
1019 * Any parameters understood by g_test_init() stripped before return.
1020 * @...: %NULL-terminated list of special options. Currently the only
1021 * defined option is <literal>"no_g_set_prgname"</literal>, which
1022 * will cause g_test_init() to not call g_set_prgname().
1024 * Initialize the GLib testing framework, e.g. by seeding the
1025 * test random number generator, the name for g_get_prgname()
1026 * and parsing test related command line args.
1027 * So far, the following arguments are understood:
1028 * <variablelist>
1029 * <varlistentry>
1030 * <term><option>-l</option></term>
1031 * <listitem><para>
1032 * List test cases available in a test executable.
1033 * </para></listitem>
1034 * </varlistentry>
1035 * <varlistentry>
1036 * <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
1037 * <listitem><para>
1038 * Provide a random seed to reproduce test runs using random numbers.
1039 * </para></listitem>
1040 * </varlistentry>
1041 * <varlistentry>
1042 * <term><option>--verbose</option></term>
1043 * <listitem><para>Run tests verbosely.</para></listitem>
1044 * </varlistentry>
1045 * <varlistentry>
1046 * <term><option>-q</option>, <option>--quiet</option></term>
1047 * <listitem><para>Run tests quietly.</para></listitem>
1048 * </varlistentry>
1049 * <varlistentry>
1050 * <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
1051 * <listitem><para>
1052 * Execute all tests matching <replaceable>TESTPATH</replaceable>.
1053 * This can also be used to force a test to run that would otherwise
1054 * be skipped (ie, a test whose name contains "/subprocess").
1055 * </para></listitem>
1056 * </varlistentry>
1057 * <varlistentry>
1058 * <term><option>-m {perf|slow|thorough|quick|undefined|no-undefined}</option></term>
1059 * <listitem><para>
1060 * Execute tests according to these test modes:
1061 * <variablelist>
1062 * <varlistentry>
1063 * <term>perf</term>
1064 * <listitem><para>
1065 * Performance tests, may take long and report results.
1066 * </para></listitem>
1067 * </varlistentry>
1068 * <varlistentry>
1069 * <term>slow, thorough</term>
1070 * <listitem><para>
1071 * Slow and thorough tests, may take quite long and
1072 * maximize coverage.
1073 * </para></listitem>
1074 * </varlistentry>
1075 * <varlistentry>
1076 * <term>quick</term>
1077 * <listitem><para>
1078 * Quick tests, should run really quickly and give good coverage.
1079 * </para></listitem>
1080 * </varlistentry>
1081 * <varlistentry>
1082 * <term>undefined</term>
1083 * <listitem><para>
1084 * Tests for undefined behaviour, may provoke programming errors
1085 * under g_test_trap_subprocess() or g_test_expect_messages() to check
1086 * that appropriate assertions or warnings are given
1087 * </para></listitem>
1088 * </varlistentry>
1089 * <varlistentry>
1090 * <term>no-undefined</term>
1091 * <listitem><para>
1092 * Avoid tests for undefined behaviour
1093 * </para></listitem>
1094 * </varlistentry>
1095 * </variablelist>
1096 * </para></listitem>
1097 * </varlistentry>
1098 * <varlistentry>
1099 * <term><option>--debug-log</option></term>
1100 * <listitem><para>Debug test logging output.</para></listitem>
1101 * </varlistentry>
1102 * </variablelist>
1104 * Since: 2.16
1106 void
1107 g_test_init (int *argc,
1108 char ***argv,
1109 ...)
1111 static char seedstr[4 + 4 * 8 + 1];
1112 va_list args;
1113 gpointer option;
1114 /* make warnings and criticals fatal for all test programs */
1115 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1117 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1118 g_log_set_always_fatal (fatal_mask);
1119 /* check caller args */
1120 g_return_if_fail (argc != NULL);
1121 g_return_if_fail (argv != NULL);
1122 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
1123 mutable_test_config_vars.test_initialized = TRUE;
1125 va_start (args, argv);
1126 while ((option = va_arg (args, char *)))
1128 if (g_strcmp0 (option, "no_g_set_prgname") == 0)
1129 no_g_set_prgname = TRUE;
1131 va_end (args);
1133 /* setup random seed string */
1134 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
1135 test_run_seedstr = seedstr;
1137 /* parse args, sets up mode, changes seed, etc. */
1138 parse_args (argc, argv);
1140 if (!g_get_prgname() && !no_g_set_prgname)
1141 g_set_prgname ((*argv)[0]);
1143 /* verify GRand reliability, needed for reliable seeds */
1144 if (1)
1146 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
1147 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
1148 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
1149 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
1150 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
1151 g_rand_free (rg);
1154 /* check rand seed */
1155 test_run_seed (test_run_seedstr);
1157 /* report program start */
1158 g_log_set_default_handler (gtest_default_log_handler, NULL);
1159 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
1161 test_argv0_dirname = g_path_get_dirname (test_argv0);
1163 /* Make sure we get the real dirname that the test was run from */
1164 if (g_str_has_suffix (test_argv0_dirname, "/.libs"))
1166 gchar *tmp;
1167 tmp = g_path_get_dirname (test_argv0_dirname);
1168 g_free (test_argv0_dirname);
1169 test_argv0_dirname = tmp;
1172 test_disted_files_dir = g_getenv ("G_TEST_SRCDIR");
1173 if (!test_disted_files_dir)
1174 test_disted_files_dir = test_argv0_dirname;
1176 test_built_files_dir = g_getenv ("G_TEST_BUILDDIR");
1177 if (!test_built_files_dir)
1178 test_built_files_dir = test_argv0_dirname;
1181 static void
1182 test_run_seed (const gchar *rseed)
1184 guint seed_failed = 0;
1185 if (test_run_rand)
1186 g_rand_free (test_run_rand);
1187 test_run_rand = NULL;
1188 while (strchr (" \t\v\r\n\f", *rseed))
1189 rseed++;
1190 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
1192 const char *s = rseed + 4;
1193 if (strlen (s) >= 32) /* require 4 * 8 chars */
1195 guint32 seedarray[4];
1196 gchar *p, hexbuf[9] = { 0, };
1197 memcpy (hexbuf, s + 0, 8);
1198 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
1199 seed_failed += p != NULL && *p != 0;
1200 memcpy (hexbuf, s + 8, 8);
1201 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
1202 seed_failed += p != NULL && *p != 0;
1203 memcpy (hexbuf, s + 16, 8);
1204 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
1205 seed_failed += p != NULL && *p != 0;
1206 memcpy (hexbuf, s + 24, 8);
1207 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
1208 seed_failed += p != NULL && *p != 0;
1209 if (!seed_failed)
1211 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
1212 return;
1216 g_error ("Unknown or invalid random seed: %s", rseed);
1220 * g_test_rand_int:
1222 * Get a reproducible random integer number.
1224 * The random numbers generated by the g_test_rand_*() family of functions
1225 * change with every new test program start, unless the --seed option is
1226 * given when starting test programs.
1228 * For individual test cases however, the random number generator is
1229 * reseeded, to avoid dependencies between tests and to make --seed
1230 * effective for all test cases.
1232 * Returns: a random number from the seeded random number generator.
1234 * Since: 2.16
1236 gint32
1237 g_test_rand_int (void)
1239 return g_rand_int (test_run_rand);
1243 * g_test_rand_int_range:
1244 * @begin: the minimum value returned by this function
1245 * @end: the smallest value not to be returned by this function
1247 * Get a reproducible random integer number out of a specified range,
1248 * see g_test_rand_int() for details on test case random numbers.
1250 * Returns: a number with @begin <= number < @end.
1252 * Since: 2.16
1254 gint32
1255 g_test_rand_int_range (gint32 begin,
1256 gint32 end)
1258 return g_rand_int_range (test_run_rand, begin, end);
1262 * g_test_rand_double:
1264 * Get a reproducible random floating point number,
1265 * see g_test_rand_int() for details on test case random numbers.
1267 * Returns: a random number from the seeded random number generator.
1269 * Since: 2.16
1271 double
1272 g_test_rand_double (void)
1274 return g_rand_double (test_run_rand);
1278 * g_test_rand_double_range:
1279 * @range_start: the minimum value returned by this function
1280 * @range_end: the minimum value not returned by this function
1282 * Get a reproducible random floating pointer number out of a specified range,
1283 * see g_test_rand_int() for details on test case random numbers.
1285 * Returns: a number with @range_start <= number < @range_end.
1287 * Since: 2.16
1289 double
1290 g_test_rand_double_range (double range_start,
1291 double range_end)
1293 return g_rand_double_range (test_run_rand, range_start, range_end);
1297 * g_test_timer_start:
1299 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1300 * to be done. Call this function again to restart the timer.
1302 * Since: 2.16
1304 void
1305 g_test_timer_start (void)
1307 if (!test_user_timer)
1308 test_user_timer = g_timer_new();
1309 test_user_stamp = 0;
1310 g_timer_start (test_user_timer);
1314 * g_test_timer_elapsed:
1316 * Get the time since the last start of the timer with g_test_timer_start().
1318 * Returns: the time since the last start of the timer, as a double
1320 * Since: 2.16
1322 double
1323 g_test_timer_elapsed (void)
1325 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1326 return test_user_stamp;
1330 * g_test_timer_last:
1332 * Report the last result of g_test_timer_elapsed().
1334 * Returns: the last result of g_test_timer_elapsed(), as a double
1336 * Since: 2.16
1338 double
1339 g_test_timer_last (void)
1341 return test_user_stamp;
1345 * g_test_minimized_result:
1346 * @minimized_quantity: the reported value
1347 * @format: the format string of the report message
1348 * @...: arguments to pass to the printf() function
1350 * Report the result of a performance or measurement test.
1351 * The test should generally strive to minimize the reported
1352 * quantities (smaller values are better than larger ones),
1353 * this and @minimized_quantity can determine sorting
1354 * order for test result reports.
1356 * Since: 2.16
1358 void
1359 g_test_minimized_result (double minimized_quantity,
1360 const char *format,
1361 ...)
1363 long double largs = minimized_quantity;
1364 gchar *buffer;
1365 va_list args;
1367 va_start (args, format);
1368 buffer = g_strdup_vprintf (format, args);
1369 va_end (args);
1371 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1372 g_free (buffer);
1376 * g_test_maximized_result:
1377 * @maximized_quantity: the reported value
1378 * @format: the format string of the report message
1379 * @...: arguments to pass to the printf() function
1381 * Report the result of a performance or measurement test.
1382 * The test should generally strive to maximize the reported
1383 * quantities (larger values are better than smaller ones),
1384 * this and @maximized_quantity can determine sorting
1385 * order for test result reports.
1387 * Since: 2.16
1389 void
1390 g_test_maximized_result (double maximized_quantity,
1391 const char *format,
1392 ...)
1394 long double largs = maximized_quantity;
1395 gchar *buffer;
1396 va_list args;
1398 va_start (args, format);
1399 buffer = g_strdup_vprintf (format, args);
1400 va_end (args);
1402 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1403 g_free (buffer);
1407 * g_test_message:
1408 * @format: the format string
1409 * @...: printf-like arguments to @format
1411 * Add a message to the test report.
1413 * Since: 2.16
1415 void
1416 g_test_message (const char *format,
1417 ...)
1419 gchar *buffer;
1420 va_list args;
1422 va_start (args, format);
1423 buffer = g_strdup_vprintf (format, args);
1424 va_end (args);
1426 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1427 g_free (buffer);
1431 * g_test_bug_base:
1432 * @uri_pattern: the base pattern for bug URIs
1434 * Specify the base URI for bug reports.
1436 * The base URI is used to construct bug report messages for
1437 * g_test_message() when g_test_bug() is called.
1438 * Calling this function outside of a test case sets the
1439 * default base URI for all test cases. Calling it from within
1440 * a test case changes the base URI for the scope of the test
1441 * case only.
1442 * Bug URIs are constructed by appending a bug specific URI
1443 * portion to @uri_pattern, or by replacing the special string
1444 * '\%s' within @uri_pattern if that is present.
1446 * Since: 2.16
1448 void
1449 g_test_bug_base (const char *uri_pattern)
1451 g_free (test_uri_base);
1452 test_uri_base = g_strdup (uri_pattern);
1456 * g_test_bug:
1457 * @bug_uri_snippet: Bug specific bug tracker URI portion.
1459 * This function adds a message to test reports that
1460 * associates a bug URI with a test case.
1461 * Bug URIs are constructed from a base URI set with g_test_bug_base()
1462 * and @bug_uri_snippet.
1464 * Since: 2.16
1466 void
1467 g_test_bug (const char *bug_uri_snippet)
1469 char *c;
1471 g_return_if_fail (test_uri_base != NULL);
1472 g_return_if_fail (bug_uri_snippet != NULL);
1474 c = strstr (test_uri_base, "%s");
1475 if (c)
1477 char *b = g_strndup (test_uri_base, c - test_uri_base);
1478 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1479 g_free (b);
1480 g_test_message ("Bug Reference: %s", s);
1481 g_free (s);
1483 else
1484 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1488 * g_test_get_root:
1490 * Get the toplevel test suite for the test path API.
1492 * Returns: the toplevel #GTestSuite
1494 * Since: 2.16
1496 GTestSuite*
1497 g_test_get_root (void)
1499 if (!test_suite_root)
1501 test_suite_root = g_test_create_suite ("root");
1502 g_free (test_suite_root->name);
1503 test_suite_root->name = g_strdup ("");
1506 return test_suite_root;
1510 * g_test_run:
1512 * Runs all tests under the toplevel suite which can be retrieved
1513 * with g_test_get_root(). Similar to g_test_run_suite(), the test
1514 * cases to be run are filtered according to
1515 * test path arguments (-p <replaceable>testpath</replaceable>) as
1516 * parsed by g_test_init().
1517 * g_test_run_suite() or g_test_run() may only be called once
1518 * in a program.
1520 * In general, the tests and sub-suites within each suite are run in
1521 * the order in which they are defined. However, note that prior to
1522 * GLib 2.36, there was a bug in the <literal>g_test_add_*</literal>
1523 * functions which caused them to create multiple suites with the same
1524 * name, meaning that if you created tests "/foo/simple",
1525 * "/bar/simple", and "/foo/using-bar" in that order, they would get
1526 * run in that order (since g_test_run() would run the first "/foo"
1527 * suite, then the "/bar" suite, then the second "/foo" suite). As of
1528 * 2.36, this bug is fixed, and adding the tests in that order would
1529 * result in a running order of "/foo/simple", "/foo/using-bar",
1530 * "/bar/simple". If this new ordering is sub-optimal (because it puts
1531 * more-complicated tests before simpler ones, making it harder to
1532 * figure out exactly what has failed), you can fix it by changing the
1533 * test paths to group tests by suite in a way that will result in the
1534 * desired running order. Eg, "/simple/foo", "/simple/bar",
1535 * "/complex/foo-using-bar".
1537 * However, you should never make the actual result of a test depend
1538 * on the order that tests are run in. If you need to ensure that some
1539 * particular code runs before or after a given test case, use
1540 * g_test_add(), which lets you specify setup and teardown functions.
1542 * Returns: 0 on success, 1 on failure (assuming it returns at all),
1543 * 77 if all tests were skipped with g_test_skip().
1545 * Since: 2.16
1548 g_test_run (void)
1550 if (g_test_run_suite (g_test_get_root()) != 0)
1551 return 1;
1553 if (test_run_count > 0 && test_run_count == test_skipped_count)
1554 return 77;
1555 else
1556 return 0;
1560 * g_test_create_case:
1561 * @test_name: the name for the test case
1562 * @data_size: the size of the fixture data structure
1563 * @test_data: test data argument for the test functions
1564 * @data_setup: the function to set up the fixture data
1565 * @data_test: the actual test function
1566 * @data_teardown: the function to teardown the fixture data
1568 * Create a new #GTestCase, named @test_name, this API is fairly
1569 * low level, calling g_test_add() or g_test_add_func() is preferable.
1570 * When this test is executed, a fixture structure of size @data_size
1571 * will be allocated and filled with 0s. Then @data_setup is called
1572 * to initialize the fixture. After fixture setup, the actual test
1573 * function @data_test is called. Once the test run completed, the
1574 * fixture structure is torn down by calling @data_teardown and
1575 * after that the memory is released.
1577 * Splitting up a test run into fixture setup, test function and
1578 * fixture teardown is most usful if the same fixture is used for
1579 * multiple tests. In this cases, g_test_create_case() will be
1580 * called with the same fixture, but varying @test_name and
1581 * @data_test arguments.
1583 * Returns: a newly allocated #GTestCase.
1585 * Since: 2.16
1587 GTestCase*
1588 g_test_create_case (const char *test_name,
1589 gsize data_size,
1590 gconstpointer test_data,
1591 GTestFixtureFunc data_setup,
1592 GTestFixtureFunc data_test,
1593 GTestFixtureFunc data_teardown)
1595 GTestCase *tc;
1597 g_return_val_if_fail (test_name != NULL, NULL);
1598 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1599 g_return_val_if_fail (test_name[0] != 0, NULL);
1600 g_return_val_if_fail (data_test != NULL, NULL);
1602 tc = g_slice_new0 (GTestCase);
1603 tc->name = g_strdup (test_name);
1604 tc->test_data = (gpointer) test_data;
1605 tc->fixture_size = data_size;
1606 tc->fixture_setup = (void*) data_setup;
1607 tc->fixture_test = (void*) data_test;
1608 tc->fixture_teardown = (void*) data_teardown;
1610 return tc;
1613 static gint
1614 find_suite (gconstpointer l, gconstpointer s)
1616 const GTestSuite *suite = l;
1617 const gchar *str = s;
1619 return strcmp (suite->name, str);
1623 * GTestFixtureFunc:
1624 * @fixture: the test fixture
1625 * @user_data: the data provided when registering the test
1627 * The type used for functions that operate on test fixtures. This is
1628 * used for the fixture setup and teardown functions as well as for the
1629 * testcases themselves.
1631 * @user_data is a pointer to the data that was given when registering
1632 * the test case.
1634 * @fixture will be a pointer to the area of memory allocated by the
1635 * test framework, of the size requested. If the requested size was
1636 * zero then @fixture will be equal to @user_data.
1638 * Since: 2.28
1640 void
1641 g_test_add_vtable (const char *testpath,
1642 gsize data_size,
1643 gconstpointer test_data,
1644 GTestFixtureFunc data_setup,
1645 GTestFixtureFunc fixture_test_func,
1646 GTestFixtureFunc data_teardown)
1648 gchar **segments;
1649 guint ui;
1650 GTestSuite *suite;
1652 g_return_if_fail (testpath != NULL);
1653 g_return_if_fail (g_path_is_absolute (testpath));
1654 g_return_if_fail (fixture_test_func != NULL);
1656 if (g_slist_find_custom (test_paths_skipped, testpath, (GCompareFunc)g_strcmp0))
1657 return;
1659 suite = g_test_get_root();
1660 segments = g_strsplit (testpath, "/", -1);
1661 for (ui = 0; segments[ui] != NULL; ui++)
1663 const char *seg = segments[ui];
1664 gboolean islast = segments[ui + 1] == NULL;
1665 if (islast && !seg[0])
1666 g_error ("invalid test case path: %s", testpath);
1667 else if (!seg[0])
1668 continue; /* initial or duplicate slash */
1669 else if (!islast)
1671 GSList *l;
1672 GTestSuite *csuite;
1673 l = g_slist_find_custom (suite->suites, seg, find_suite);
1674 if (l)
1676 csuite = l->data;
1678 else
1680 csuite = g_test_create_suite (seg);
1681 g_test_suite_add_suite (suite, csuite);
1683 suite = csuite;
1685 else /* islast */
1687 GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1688 g_test_suite_add (suite, tc);
1691 g_strfreev (segments);
1695 * g_test_fail:
1697 * Indicates that a test failed. This function can be called
1698 * multiple times from the same test. You can use this function
1699 * if your test failed in a recoverable way.
1701 * Do not use this function if the failure of a test could cause
1702 * other tests to malfunction.
1704 * Calling this function will not stop the test from running, you
1705 * need to return from the test function yourself. So you can
1706 * produce additional diagnostic messages or even continue running
1707 * the test.
1709 * If not called from inside a test, this function does nothing.
1711 * Since: 2.30
1713 void
1714 g_test_fail (void)
1716 test_run_success = G_TEST_RUN_FAILURE;
1720 * g_test_incomplete:
1721 * @msg: (allow-none): explanation
1723 * Indicates that a test failed because of some incomplete
1724 * functionality. This function can be called multiple times
1725 * from the same test.
1727 * Calling this function will not stop the test from running, you
1728 * need to return from the test function yourself. So you can
1729 * produce additional diagnostic messages or even continue running
1730 * the test.
1732 * If not called from inside a test, this function does nothing.
1734 * Since: 2.38
1736 void
1737 g_test_incomplete (const gchar *msg)
1739 test_run_success = G_TEST_RUN_INCOMPLETE;
1740 g_free (test_run_msg);
1741 test_run_msg = g_strdup (msg);
1745 * g_test_skip:
1746 * @msg: (allow-none): explanation
1748 * Indicates that a test was skipped.
1750 * Calling this function will not stop the test from running, you
1751 * need to return from the test function yourself. So you can
1752 * produce additional diagnostic messages or even continue running
1753 * the test.
1755 * If not called from inside a test, this function does nothing.
1757 * Since: 2.38
1759 void
1760 g_test_skip (const gchar *msg)
1762 test_run_success = G_TEST_RUN_SKIPPED;
1763 g_free (test_run_msg);
1764 test_run_msg = g_strdup (msg);
1768 * g_test_failed:
1770 * Returns whether a test has already failed. This will
1771 * be the case when g_test_fail(), g_test_incomplete()
1772 * or g_test_skip() have been called, but also if an
1773 * assertion has failed.
1775 * This can be useful to return early from a test if
1776 * continuing after a failed assertion might be harmful.
1778 * The return value of this function is only meaningful
1779 * if it is called from inside a test function.
1781 * Returns: %TRUE if the test has failed
1783 * Since: 2.38
1785 gboolean
1786 g_test_failed (void)
1788 return test_run_success != G_TEST_RUN_SUCCESS;
1792 * g_test_set_nonfatal_assertions:
1794 * Changes the behaviour of g_assert_cmpstr(), g_assert_cmpint(),
1795 * g_assert_cmpuint(), g_assert_cmphex(), g_assert_cmpfloat(),
1796 * g_assert_true(), g_assert_false(), g_assert_null(), g_assert_no_error(),
1797 * g_assert_error(), g_test_assert_expected_messages() and the various
1798 * g_test_trap_assert_*() macros to not abort to program, but instead
1799 * call g_test_fail() and continue. (This also changes the behavior of
1800 * g_test_fail() so that it will not cause the test program to abort
1801 * after completing the failed test.)
1803 * Note that the g_assert_not_reached() and g_assert() are not
1804 * affected by this.
1806 * This function can only be called after g_test_init().
1808 * Since: 2.38
1810 void
1811 g_test_set_nonfatal_assertions (void)
1813 if (!g_test_config_vars->test_initialized)
1814 g_error ("g_test_set_nonfatal_assertions called without g_test_init");
1815 test_nonfatal_assertions = TRUE;
1816 test_mode_fatal = FALSE;
1820 * GTestFunc:
1822 * The type used for test case functions.
1824 * Since: 2.28
1828 * g_test_add_func:
1829 * @testpath: /-separated test case path name for the test.
1830 * @test_func: The test function to invoke for this test.
1832 * Create a new test case, similar to g_test_create_case(). However
1833 * the test is assumed to use no fixture, and test suites are automatically
1834 * created on the fly and added to the root fixture, based on the
1835 * slash-separated portions of @testpath.
1837 * If @testpath includes the component "subprocess" anywhere in it,
1838 * the test will be skipped by default, and only run if explicitly
1839 * required via the <option>-p</option> command-line option or
1840 * g_test_trap_subprocess().
1842 * Since: 2.16
1844 void
1845 g_test_add_func (const char *testpath,
1846 GTestFunc test_func)
1848 g_return_if_fail (testpath != NULL);
1849 g_return_if_fail (testpath[0] == '/');
1850 g_return_if_fail (test_func != NULL);
1851 g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1855 * GTestDataFunc:
1856 * @user_data: the data provided when registering the test
1858 * The type used for test case functions that take an extra pointer
1859 * argument.
1861 * Since: 2.28
1865 * g_test_add_data_func:
1866 * @testpath: /-separated test case path name for the test.
1867 * @test_data: Test data argument for the test function.
1868 * @test_func: The test function to invoke for this test.
1870 * Create a new test case, similar to g_test_create_case(). However
1871 * the test is assumed to use no fixture, and test suites are automatically
1872 * created on the fly and added to the root fixture, based on the
1873 * slash-separated portions of @testpath. The @test_data argument
1874 * will be passed as first argument to @test_func.
1876 * If @testpath includes the component "subprocess" anywhere in it,
1877 * the test will be skipped by default, and only run if explicitly
1878 * required via the <option>-p</option> command-line option or
1879 * g_test_trap_subprocess().
1881 * Since: 2.16
1883 void
1884 g_test_add_data_func (const char *testpath,
1885 gconstpointer test_data,
1886 GTestDataFunc test_func)
1888 g_return_if_fail (testpath != NULL);
1889 g_return_if_fail (testpath[0] == '/');
1890 g_return_if_fail (test_func != NULL);
1892 g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1896 * g_test_add_data_func_full:
1897 * @testpath: /-separated test case path name for the test.
1898 * @test_data: Test data argument for the test function.
1899 * @test_func: The test function to invoke for this test.
1900 * @data_free_func: #GDestroyNotify for @test_data.
1902 * Create a new test case, as with g_test_add_data_func(), but freeing
1903 * @test_data after the test run is complete.
1905 * Since: 2.34
1907 void
1908 g_test_add_data_func_full (const char *testpath,
1909 gpointer test_data,
1910 GTestDataFunc test_func,
1911 GDestroyNotify data_free_func)
1913 g_return_if_fail (testpath != NULL);
1914 g_return_if_fail (testpath[0] == '/');
1915 g_return_if_fail (test_func != NULL);
1917 g_test_add_vtable (testpath, 0, test_data, NULL,
1918 (GTestFixtureFunc) test_func,
1919 (GTestFixtureFunc) data_free_func);
1922 static gboolean
1923 g_test_suite_case_exists (GTestSuite *suite,
1924 const char *test_path)
1926 GSList *iter;
1927 char *slash;
1928 GTestCase *tc;
1930 test_path++;
1931 slash = strchr (test_path, '/');
1933 if (slash)
1935 for (iter = suite->suites; iter; iter = iter->next)
1937 GTestSuite *child_suite = iter->data;
1939 if (!strncmp (child_suite->name, test_path, slash - test_path))
1940 if (g_test_suite_case_exists (child_suite, slash))
1941 return TRUE;
1944 else
1946 for (iter = suite->cases; iter; iter = iter->next)
1948 tc = iter->data;
1949 if (!strcmp (tc->name, test_path))
1950 return TRUE;
1954 return FALSE;
1958 * g_test_create_suite:
1959 * @suite_name: a name for the suite
1961 * Create a new test suite with the name @suite_name.
1963 * Returns: A newly allocated #GTestSuite instance.
1965 * Since: 2.16
1967 GTestSuite*
1968 g_test_create_suite (const char *suite_name)
1970 GTestSuite *ts;
1971 g_return_val_if_fail (suite_name != NULL, NULL);
1972 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1973 g_return_val_if_fail (suite_name[0] != 0, NULL);
1974 ts = g_slice_new0 (GTestSuite);
1975 ts->name = g_strdup (suite_name);
1976 return ts;
1980 * g_test_suite_add:
1981 * @suite: a #GTestSuite
1982 * @test_case: a #GTestCase
1984 * Adds @test_case to @suite.
1986 * Since: 2.16
1988 void
1989 g_test_suite_add (GTestSuite *suite,
1990 GTestCase *test_case)
1992 g_return_if_fail (suite != NULL);
1993 g_return_if_fail (test_case != NULL);
1995 suite->cases = g_slist_prepend (suite->cases, test_case);
1999 * g_test_suite_add_suite:
2000 * @suite: a #GTestSuite
2001 * @nestedsuite: another #GTestSuite
2003 * Adds @nestedsuite to @suite.
2005 * Since: 2.16
2007 void
2008 g_test_suite_add_suite (GTestSuite *suite,
2009 GTestSuite *nestedsuite)
2011 g_return_if_fail (suite != NULL);
2012 g_return_if_fail (nestedsuite != NULL);
2014 suite->suites = g_slist_prepend (suite->suites, nestedsuite);
2018 * g_test_queue_free:
2019 * @gfree_pointer: the pointer to be stored.
2021 * Enqueue a pointer to be released with g_free() during the next
2022 * teardown phase. This is equivalent to calling g_test_queue_destroy()
2023 * with a destroy callback of g_free().
2025 * Since: 2.16
2027 void
2028 g_test_queue_free (gpointer gfree_pointer)
2030 if (gfree_pointer)
2031 g_test_queue_destroy (g_free, gfree_pointer);
2035 * g_test_queue_destroy:
2036 * @destroy_func: Destroy callback for teardown phase.
2037 * @destroy_data: Destroy callback data.
2039 * This function enqueus a callback @destroy_func to be executed
2040 * during the next test case teardown phase. This is most useful
2041 * to auto destruct allocted test resources at the end of a test run.
2042 * Resources are released in reverse queue order, that means enqueueing
2043 * callback A before callback B will cause B() to be called before
2044 * A() during teardown.
2046 * Since: 2.16
2048 void
2049 g_test_queue_destroy (GDestroyNotify destroy_func,
2050 gpointer destroy_data)
2052 DestroyEntry *dentry;
2054 g_return_if_fail (destroy_func != NULL);
2056 dentry = g_slice_new0 (DestroyEntry);
2057 dentry->destroy_func = destroy_func;
2058 dentry->destroy_data = destroy_data;
2059 dentry->next = test_destroy_queue;
2060 test_destroy_queue = dentry;
2063 static gboolean
2064 test_case_run (GTestCase *tc)
2066 gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
2067 GSList **old_free_list, *filename_free_list = NULL;
2068 gboolean success = G_TEST_RUN_SUCCESS;
2070 old_free_list = test_filename_free_list;
2071 test_filename_free_list = &filename_free_list;
2073 test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
2074 if (strstr (test_run_name, "/subprocess"))
2076 GSList *iter;
2077 gboolean found = FALSE;
2079 for (iter = test_paths; iter; iter = iter->next)
2081 if (!strcmp (test_run_name, iter->data))
2083 found = TRUE;
2084 break;
2088 if (!found)
2090 if (g_test_verbose ())
2091 g_print ("GTest: skipping: %s\n", test_run_name);
2092 goto out;
2096 if (++test_run_count <= test_startup_skip_count)
2097 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
2098 else if (test_run_list)
2100 g_print ("%s\n", test_run_name);
2101 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
2103 else
2105 GTimer *test_run_timer = g_timer_new();
2106 long double largs[3];
2107 void *fixture;
2108 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
2109 test_run_forks = 0;
2110 test_run_success = G_TEST_RUN_SUCCESS;
2111 g_clear_pointer (&test_run_msg, g_free);
2112 g_test_log_set_fatal_handler (NULL, NULL);
2113 g_timer_start (test_run_timer);
2114 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
2115 test_run_seed (test_run_seedstr);
2116 if (tc->fixture_setup)
2117 tc->fixture_setup (fixture, tc->test_data);
2118 tc->fixture_test (fixture, tc->test_data);
2119 test_trap_clear();
2120 while (test_destroy_queue)
2122 DestroyEntry *dentry = test_destroy_queue;
2123 test_destroy_queue = dentry->next;
2124 dentry->destroy_func (dentry->destroy_data);
2125 g_slice_free (DestroyEntry, dentry);
2127 if (tc->fixture_teardown)
2128 tc->fixture_teardown (fixture, tc->test_data);
2129 if (tc->fixture_size)
2130 g_free (fixture);
2131 g_timer_stop (test_run_timer);
2132 success = test_run_success;
2133 test_run_success = G_TEST_RUN_FAILURE;
2134 largs[0] = success; /* OK */
2135 largs[1] = test_run_forks;
2136 largs[2] = g_timer_elapsed (test_run_timer, NULL);
2137 g_test_log (G_TEST_LOG_STOP_CASE, test_run_name, test_run_msg, G_N_ELEMENTS (largs), largs);
2138 g_clear_pointer (&test_run_msg, g_free);
2139 g_timer_destroy (test_run_timer);
2142 out:
2143 g_slist_free_full (filename_free_list, g_free);
2144 test_filename_free_list = old_free_list;
2145 g_free (test_run_name);
2146 test_run_name = old_name;
2147 g_free (test_uri_base);
2148 test_uri_base = old_base;
2150 return (success == G_TEST_RUN_SUCCESS ||
2151 success == G_TEST_RUN_SKIPPED);
2154 static int
2155 g_test_run_suite_internal (GTestSuite *suite,
2156 const char *path)
2158 guint n_bad = 0, l;
2159 gchar *rest, *old_name = test_run_name;
2160 GSList *slist, *reversed;
2162 g_return_val_if_fail (suite != NULL, -1);
2164 g_test_log (G_TEST_LOG_START_SUITE, suite->name, NULL, 0, NULL);
2166 while (path[0] == '/')
2167 path++;
2168 l = strlen (path);
2169 rest = strchr (path, '/');
2170 l = rest ? MIN (l, rest - path) : l;
2171 test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
2172 reversed = g_slist_reverse (g_slist_copy (suite->cases));
2173 for (slist = reversed; slist; slist = slist->next)
2175 GTestCase *tc = slist->data;
2176 guint n = l ? strlen (tc->name) : 0;
2177 if (l == n && !rest && strncmp (path, tc->name, n) == 0)
2179 if (!test_case_run (tc))
2180 n_bad++;
2183 g_slist_free (reversed);
2184 reversed = g_slist_reverse (g_slist_copy (suite->suites));
2185 for (slist = reversed; slist; slist = slist->next)
2187 GTestSuite *ts = slist->data;
2188 guint n = l ? strlen (ts->name) : 0;
2189 if (l == n && strncmp (path, ts->name, n) == 0)
2190 n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
2192 g_slist_free (reversed);
2193 g_free (test_run_name);
2194 test_run_name = old_name;
2196 g_test_log (G_TEST_LOG_STOP_SUITE, suite->name, NULL, 0, NULL);
2198 return n_bad;
2202 * g_test_run_suite:
2203 * @suite: a #GTestSuite
2205 * Execute the tests within @suite and all nested #GTestSuites.
2206 * The test suites to be executed are filtered according to
2207 * test path arguments (-p <replaceable>testpath</replaceable>)
2208 * as parsed by g_test_init(). See the g_test_run() documentation
2209 * for more information on the order that tests are run in.
2211 * g_test_run_suite() or g_test_run() may only be called once
2212 * in a program.
2214 * Returns: 0 on success
2216 * Since: 2.16
2219 g_test_run_suite (GTestSuite *suite)
2221 GSList *my_test_paths;
2222 guint n_bad = 0;
2224 g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
2225 g_return_val_if_fail (g_test_run_once == TRUE, -1);
2227 g_test_run_once = FALSE;
2229 if (test_paths)
2230 my_test_paths = g_slist_copy (test_paths);
2231 else
2232 my_test_paths = g_slist_prepend (NULL, "");
2234 while (my_test_paths)
2236 const char *rest, *path = my_test_paths->data;
2237 guint l, n = strlen (suite->name);
2238 my_test_paths = g_slist_delete_link (my_test_paths, my_test_paths);
2239 while (path[0] == '/')
2240 path++;
2241 if (!n) /* root suite, run unconditionally */
2243 n_bad += g_test_run_suite_internal (suite, path);
2244 continue;
2246 /* regular suite, match path */
2247 rest = strchr (path, '/');
2248 l = strlen (path);
2249 l = rest ? MIN (l, rest - path) : l;
2250 if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
2251 n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
2254 return n_bad;
2257 static void
2258 gtest_default_log_handler (const gchar *log_domain,
2259 GLogLevelFlags log_level,
2260 const gchar *message,
2261 gpointer unused_data)
2263 const gchar *strv[16];
2264 gboolean fatal = FALSE;
2265 gchar *msg;
2266 guint i = 0;
2268 if (log_domain)
2270 strv[i++] = log_domain;
2271 strv[i++] = "-";
2273 if (log_level & G_LOG_FLAG_FATAL)
2275 strv[i++] = "FATAL-";
2276 fatal = TRUE;
2278 if (log_level & G_LOG_FLAG_RECURSION)
2279 strv[i++] = "RECURSIVE-";
2280 if (log_level & G_LOG_LEVEL_ERROR)
2281 strv[i++] = "ERROR";
2282 if (log_level & G_LOG_LEVEL_CRITICAL)
2283 strv[i++] = "CRITICAL";
2284 if (log_level & G_LOG_LEVEL_WARNING)
2285 strv[i++] = "WARNING";
2286 if (log_level & G_LOG_LEVEL_MESSAGE)
2287 strv[i++] = "MESSAGE";
2288 if (log_level & G_LOG_LEVEL_INFO)
2289 strv[i++] = "INFO";
2290 if (log_level & G_LOG_LEVEL_DEBUG)
2291 strv[i++] = "DEBUG";
2292 strv[i++] = ": ";
2293 strv[i++] = message;
2294 strv[i++] = NULL;
2296 msg = g_strjoinv ("", (gchar**) strv);
2297 g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
2298 g_log_default_handler (log_domain, log_level, message, unused_data);
2300 g_free (msg);
2303 void
2304 g_assertion_message (const char *domain,
2305 const char *file,
2306 int line,
2307 const char *func,
2308 const char *message)
2310 char lstr[32];
2311 char *s;
2313 if (!message)
2314 message = "code should not be reached";
2315 g_snprintf (lstr, 32, "%d", line);
2316 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
2317 "ERROR:", file, ":", lstr, ":",
2318 func, func[0] ? ":" : "",
2319 " ", message, NULL);
2320 g_printerr ("**\n%s\n", s);
2322 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
2324 if (test_nonfatal_assertions)
2326 g_free (s);
2327 g_test_fail ();
2328 return;
2331 /* store assertion message in global variable, so that it can be found in a
2332 * core dump */
2333 if (__glib_assert_msg != NULL)
2334 /* free the old one */
2335 free (__glib_assert_msg);
2336 __glib_assert_msg = (char*) malloc (strlen (s) + 1);
2337 strcpy (__glib_assert_msg, s);
2339 g_free (s);
2341 if (test_in_subprocess)
2343 /* If this is a test case subprocess then it probably hit this
2344 * assertion on purpose, so just exit() rather than abort()ing,
2345 * to avoid triggering any system crash-reporting daemon.
2347 _exit (1);
2349 else
2350 abort ();
2353 void
2354 g_assertion_message_expr (const char *domain,
2355 const char *file,
2356 int line,
2357 const char *func,
2358 const char *expr)
2360 char *s;
2361 if (!expr)
2362 s = g_strdup ("code should not be reached");
2363 else
2364 s = g_strconcat ("assertion failed: (", expr, ")", NULL);
2365 g_assertion_message (domain, file, line, func, s);
2366 g_free (s);
2368 /* Normally g_assertion_message() won't return, but we need this for
2369 * when test_nonfatal_assertions is set, since
2370 * g_assertion_message_expr() is used for always-fatal assertions.
2372 if (test_in_subprocess)
2373 _exit (1);
2374 else
2375 abort ();
2378 void
2379 g_assertion_message_cmpnum (const char *domain,
2380 const char *file,
2381 int line,
2382 const char *func,
2383 const char *expr,
2384 long double arg1,
2385 const char *cmp,
2386 long double arg2,
2387 char numtype)
2389 char *s = NULL;
2391 switch (numtype)
2393 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;
2394 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;
2395 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr, (double) arg1, cmp, (double) arg2); break;
2396 /* ideally use: floats=%.7g double=%.17g */
2398 g_assertion_message (domain, file, line, func, s);
2399 g_free (s);
2402 void
2403 g_assertion_message_cmpstr (const char *domain,
2404 const char *file,
2405 int line,
2406 const char *func,
2407 const char *expr,
2408 const char *arg1,
2409 const char *cmp,
2410 const char *arg2)
2412 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
2413 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
2414 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
2415 g_free (t1);
2416 g_free (t2);
2417 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
2418 g_free (a1);
2419 g_free (a2);
2420 g_assertion_message (domain, file, line, func, s);
2421 g_free (s);
2424 void
2425 g_assertion_message_error (const char *domain,
2426 const char *file,
2427 int line,
2428 const char *func,
2429 const char *expr,
2430 const GError *error,
2431 GQuark error_domain,
2432 int error_code)
2434 GString *gstring;
2436 /* This is used by both g_assert_error() and g_assert_no_error(), so there
2437 * are three cases: expected an error but got the wrong error, expected
2438 * an error but got no error, and expected no error but got an error.
2441 gstring = g_string_new ("assertion failed ");
2442 if (error_domain)
2443 g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
2444 g_quark_to_string (error_domain), error_code);
2445 else
2446 g_string_append_printf (gstring, "(%s == NULL): ", expr);
2448 if (error)
2449 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
2450 g_quark_to_string (error->domain), error->code);
2451 else
2452 g_string_append_printf (gstring, "%s is NULL", expr);
2454 g_assertion_message (domain, file, line, func, gstring->str);
2455 g_string_free (gstring, TRUE);
2459 * g_strcmp0:
2460 * @str1: (allow-none): a C string or %NULL
2461 * @str2: (allow-none): another C string or %NULL
2463 * Compares @str1 and @str2 like strcmp(). Handles %NULL
2464 * gracefully by sorting it before non-%NULL strings.
2465 * Comparing two %NULL pointers returns 0.
2467 * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
2469 * Since: 2.16
2472 g_strcmp0 (const char *str1,
2473 const char *str2)
2475 if (!str1)
2476 return -(str1 != str2);
2477 if (!str2)
2478 return str1 != str2;
2479 return strcmp (str1, str2);
2482 static void
2483 test_trap_clear (void)
2485 test_trap_last_status = 0;
2486 test_trap_last_pid = 0;
2487 g_clear_pointer (&test_trap_last_subprocess, g_free);
2488 g_clear_pointer (&test_trap_last_stdout, g_free);
2489 g_clear_pointer (&test_trap_last_stderr, g_free);
2492 #ifdef G_OS_UNIX
2494 static int
2495 sane_dup2 (int fd1,
2496 int fd2)
2498 int ret;
2500 ret = dup2 (fd1, fd2);
2501 while (ret < 0 && errno == EINTR);
2502 return ret;
2505 #endif
2507 typedef struct {
2508 GPid pid;
2509 GMainLoop *loop;
2510 int child_status;
2512 GIOChannel *stdout_io;
2513 gboolean echo_stdout;
2514 GString *stdout_str;
2516 GIOChannel *stderr_io;
2517 gboolean echo_stderr;
2518 GString *stderr_str;
2519 } WaitForChildData;
2521 static void
2522 check_complete (WaitForChildData *data)
2524 if (data->child_status != -1 && data->stdout_io == NULL && data->stderr_io == NULL)
2525 g_main_loop_quit (data->loop);
2528 static void
2529 child_exited (GPid pid,
2530 gint status,
2531 gpointer user_data)
2533 WaitForChildData *data = user_data;
2535 #ifdef G_OS_UNIX
2536 if (WIFEXITED (status)) /* normal exit */
2537 data->child_status = WEXITSTATUS (status); /* 0..255 */
2538 else if (WIFSIGNALED (status) && WTERMSIG (status) == SIGALRM)
2539 data->child_status = G_TEST_STATUS_TIMED_OUT;
2540 else if (WIFSIGNALED (status))
2541 data->child_status = (WTERMSIG (status) << 12); /* signalled */
2542 else /* WCOREDUMP (status) */
2543 data->child_status = 512; /* coredump */
2544 #else
2545 data->child_status = status;
2546 #endif
2548 check_complete (data);
2551 static gboolean
2552 child_timeout (gpointer user_data)
2554 WaitForChildData *data = user_data;
2556 #ifdef G_OS_WIN32
2557 TerminateProcess (data->pid, G_TEST_STATUS_TIMED_OUT);
2558 #else
2559 kill (data->pid, SIGALRM);
2560 #endif
2562 return FALSE;
2565 static gboolean
2566 child_read (GIOChannel *io, GIOCondition cond, gpointer user_data)
2568 WaitForChildData *data = user_data;
2569 GIOStatus status;
2570 gsize nread, nwrote, total;
2571 gchar buf[4096];
2572 FILE *echo_file = NULL;
2574 status = g_io_channel_read_chars (io, buf, sizeof (buf), &nread, NULL);
2575 if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF)
2577 // FIXME data->error = (status == G_IO_STATUS_ERROR);
2578 if (io == data->stdout_io)
2579 g_clear_pointer (&data->stdout_io, g_io_channel_unref);
2580 else
2581 g_clear_pointer (&data->stderr_io, g_io_channel_unref);
2583 check_complete (data);
2584 return FALSE;
2586 else if (status == G_IO_STATUS_AGAIN)
2587 return TRUE;
2589 if (io == data->stdout_io)
2591 g_string_append_len (data->stdout_str, buf, nread);
2592 if (data->echo_stdout)
2593 echo_file = stdout;
2595 else
2597 g_string_append_len (data->stderr_str, buf, nread);
2598 if (data->echo_stderr)
2599 echo_file = stderr;
2602 if (echo_file)
2604 for (total = 0; total < nread; total += nwrote)
2606 nwrote = fwrite (buf + total, 1, nread - total, echo_file);
2607 if (nwrote == 0)
2608 g_error ("write failed: %s", g_strerror (errno));
2612 return TRUE;
2615 static void
2616 wait_for_child (GPid pid,
2617 int stdout_fd, gboolean echo_stdout,
2618 int stderr_fd, gboolean echo_stderr,
2619 guint64 timeout)
2621 WaitForChildData data;
2622 GMainContext *context;
2623 GSource *source;
2625 data.pid = pid;
2626 data.child_status = -1;
2628 context = g_main_context_new ();
2629 data.loop = g_main_loop_new (context, FALSE);
2631 source = g_child_watch_source_new (pid);
2632 g_source_set_callback (source, (GSourceFunc) child_exited, &data, NULL);
2633 g_source_attach (source, context);
2634 g_source_unref (source);
2636 data.echo_stdout = echo_stdout;
2637 data.stdout_str = g_string_new (NULL);
2638 data.stdout_io = g_io_channel_unix_new (stdout_fd);
2639 g_io_channel_set_close_on_unref (data.stdout_io, TRUE);
2640 g_io_channel_set_encoding (data.stdout_io, NULL, NULL);
2641 g_io_channel_set_buffered (data.stdout_io, FALSE);
2642 source = g_io_create_watch (data.stdout_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2643 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2644 g_source_attach (source, context);
2645 g_source_unref (source);
2647 data.echo_stderr = echo_stderr;
2648 data.stderr_str = g_string_new (NULL);
2649 data.stderr_io = g_io_channel_unix_new (stderr_fd);
2650 g_io_channel_set_close_on_unref (data.stderr_io, TRUE);
2651 g_io_channel_set_encoding (data.stderr_io, NULL, NULL);
2652 g_io_channel_set_buffered (data.stderr_io, FALSE);
2653 source = g_io_create_watch (data.stderr_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2654 g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2655 g_source_attach (source, context);
2656 g_source_unref (source);
2658 if (timeout)
2660 source = g_timeout_source_new (0);
2661 g_source_set_ready_time (source, g_get_monotonic_time () + timeout);
2662 g_source_set_callback (source, (GSourceFunc) child_timeout, &data, NULL);
2663 g_source_attach (source, context);
2664 g_source_unref (source);
2667 g_main_loop_run (data.loop);
2668 g_main_loop_unref (data.loop);
2669 g_main_context_unref (context);
2671 test_trap_last_pid = pid;
2672 test_trap_last_status = data.child_status;
2673 test_trap_last_stdout = g_string_free (data.stdout_str, FALSE);
2674 test_trap_last_stderr = g_string_free (data.stderr_str, FALSE);
2676 g_clear_pointer (&data.stdout_io, g_io_channel_unref);
2677 g_clear_pointer (&data.stderr_io, g_io_channel_unref);
2681 * g_test_trap_fork:
2682 * @usec_timeout: Timeout for the forked test in micro seconds.
2683 * @test_trap_flags: Flags to modify forking behaviour.
2685 * Fork the current test program to execute a test case that might
2686 * not return or that might abort.
2688 * If @usec_timeout is non-0, the forked test case is aborted and
2689 * considered failing if its run time exceeds it.
2691 * The forking behavior can be configured with the #GTestTrapFlags flags.
2693 * In the following example, the test code forks, the forked child
2694 * process produces some sample output and exits successfully.
2695 * The forking parent process then asserts successful child program
2696 * termination and validates child program outputs.
2698 * |[
2699 * static void
2700 * test_fork_patterns (void)
2702 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2704 * g_print ("some stdout text: somagic17\n");
2705 * g_printerr ("some stderr text: semagic43\n");
2706 * exit (0); /&ast; successful test run &ast;/
2708 * g_test_trap_assert_passed ();
2709 * g_test_trap_assert_stdout ("*somagic17*");
2710 * g_test_trap_assert_stderr ("*semagic43*");
2712 * ]|
2714 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2716 * Since: 2.16
2718 * Deprecated: This function is implemented only on Unix platforms,
2719 * and is not always reliable due to problems inherent in
2720 * fork-without-exec. Use g_test_trap_subprocess() instead.
2722 gboolean
2723 g_test_trap_fork (guint64 usec_timeout,
2724 GTestTrapFlags test_trap_flags)
2726 #ifdef G_OS_UNIX
2727 int stdout_pipe[2] = { -1, -1 };
2728 int stderr_pipe[2] = { -1, -1 };
2730 test_trap_clear();
2731 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0)
2732 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
2733 test_trap_last_pid = fork ();
2734 if (test_trap_last_pid < 0)
2735 g_error ("failed to fork test program: %s", g_strerror (errno));
2736 if (test_trap_last_pid == 0) /* child */
2738 int fd0 = -1;
2739 close (stdout_pipe[0]);
2740 close (stderr_pipe[0]);
2741 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2742 fd0 = g_open ("/dev/null", O_RDONLY, 0);
2743 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2744 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
2745 if (fd0 >= 3)
2746 close (fd0);
2747 if (stdout_pipe[1] >= 3)
2748 close (stdout_pipe[1]);
2749 if (stderr_pipe[1] >= 3)
2750 close (stderr_pipe[1]);
2751 return TRUE;
2753 else /* parent */
2755 test_run_forks++;
2756 close (stdout_pipe[1]);
2757 close (stderr_pipe[1]);
2759 wait_for_child (test_trap_last_pid,
2760 stdout_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT),
2761 stderr_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR),
2762 usec_timeout);
2763 return FALSE;
2765 #else
2766 g_message ("Not implemented: g_test_trap_fork");
2768 return FALSE;
2769 #endif
2773 * g_test_trap_subprocess:
2774 * @test_path: (allow-none): Test to run in a subprocess
2775 * @usec_timeout: Timeout for the subprocess test in micro seconds.
2776 * @test_flags: Flags to modify subprocess behaviour.
2778 * Respawns the test program to run only @test_path in a subprocess.
2779 * This can be used for a test case that might not return, or that
2780 * might abort.
2782 * If @test_path is %NULL then the same test is re-run in a subprocess.
2783 * You can use g_test_subprocess() to determine whether the test is in
2784 * a subprocess or not.
2786 * @test_path can also be the name of the parent
2787 * test, followed by "<literal>/subprocess/</literal>" and then a name
2788 * for the specific subtest (or just ending with
2789 * "<literal>/subprocess</literal>" if the test only has one child
2790 * test); tests with names of this form will automatically be skipped
2791 * in the parent process.
2793 * If @usec_timeout is non-0, the test subprocess is aborted and
2794 * considered failing if its run time exceeds it.
2796 * The subprocess behavior can be configured with the
2797 * #GTestSubprocessFlags flags.
2799 * You can use methods such as g_test_trap_assert_passed(),
2800 * g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to
2801 * check the results of the subprocess. (But note that
2802 * g_test_trap_assert_stdout() and g_test_trap_assert_stderr()
2803 * cannot be used if @test_flags specifies that the child should
2804 * inherit the parent stdout/stderr.)
2806 * If your <literal>main ()</literal> needs to behave differently in
2807 * the subprocess, you can call g_test_subprocess() (after calling
2808 * g_test_init()) to see whether you are in a subprocess.
2810 * The following example tests that calling
2811 * <literal>my_object_new(1000000)</literal> will abort with an error
2812 * message.
2814 * |[
2815 * static void
2816 * test_create_large_object_subprocess (void)
2818 * if (g_test_subprocess ())
2820 * my_object_new (1000000);
2821 * return;
2824 * /&ast; Reruns this same test in a subprocess &ast;/
2825 * g_test_trap_subprocess (NULL, 0, 0);
2826 * g_test_trap_assert_failed ();
2827 * g_test_trap_assert_stderr ("*ERROR*too large*");
2830 * int
2831 * main (int argc, char **argv)
2833 * g_test_init (&argc, &argv, NULL);
2835 * g_test_add_func ("/myobject/create_large_object",
2836 * test_create_large_object);
2837 * return g_test_run ();
2839 * ]|
2841 * Since: 2.38
2843 void
2844 g_test_trap_subprocess (const char *test_path,
2845 guint64 usec_timeout,
2846 GTestSubprocessFlags test_flags)
2848 GError *error = NULL;
2849 GPtrArray *argv;
2850 GSpawnFlags flags;
2851 int stdout_fd, stderr_fd;
2852 GPid pid;
2854 /* Sanity check that they used GTestSubprocessFlags, not GTestTrapFlags */
2855 g_assert ((test_flags & (G_TEST_TRAP_INHERIT_STDIN | G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR)) == 0);
2857 if (test_path)
2859 if (!g_test_suite_case_exists (g_test_get_root (), test_path))
2860 g_error ("g_test_trap_subprocess: test does not exist: %s", test_path);
2862 else
2864 test_path = test_run_name;
2867 if (g_test_verbose ())
2868 g_print ("GTest: subprocess: %s\n", test_path);
2870 test_trap_clear ();
2871 test_trap_last_subprocess = g_strdup (test_path);
2873 argv = g_ptr_array_new ();
2874 g_ptr_array_add (argv, test_argv0);
2875 g_ptr_array_add (argv, "-q");
2876 g_ptr_array_add (argv, "-p");
2877 g_ptr_array_add (argv, (char *)test_path);
2878 g_ptr_array_add (argv, "--GTestSubprocess");
2879 if (test_log_fd != -1)
2881 char log_fd_buf[128];
2883 g_ptr_array_add (argv, "--GTestLogFD");
2884 g_snprintf (log_fd_buf, sizeof (log_fd_buf), "%d", test_log_fd);
2885 g_ptr_array_add (argv, log_fd_buf);
2887 g_ptr_array_add (argv, NULL);
2889 flags = G_SPAWN_DO_NOT_REAP_CHILD;
2890 if (test_flags & G_TEST_TRAP_INHERIT_STDIN)
2891 flags |= G_SPAWN_CHILD_INHERITS_STDIN;
2893 if (!g_spawn_async_with_pipes (test_initial_cwd,
2894 (char **)argv->pdata,
2895 NULL, flags,
2896 NULL, NULL,
2897 &pid, NULL, &stdout_fd, &stderr_fd,
2898 &error))
2900 g_error ("g_test_trap_subprocess() failed: %s\n",
2901 error->message);
2903 g_ptr_array_free (argv, TRUE);
2905 wait_for_child (pid,
2906 stdout_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDOUT),
2907 stderr_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDERR),
2908 usec_timeout);
2912 * g_test_subprocess:
2914 * Returns %TRUE (after g_test_init() has been called) if the test
2915 * program is running under g_test_trap_subprocess().
2917 * Returns: %TRUE if the test program is running under
2918 * g_test_trap_subprocess().
2920 * Since: 2.38
2922 gboolean
2923 g_test_subprocess (void)
2925 return test_in_subprocess;
2929 * g_test_trap_has_passed:
2931 * Check the result of the last g_test_trap_subprocess() call.
2933 * Returns: %TRUE if the last test subprocess terminated successfully.
2935 * Since: 2.16
2937 gboolean
2938 g_test_trap_has_passed (void)
2940 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
2944 * g_test_trap_reached_timeout:
2946 * Check the result of the last g_test_trap_subprocess() call.
2948 * Returns: %TRUE if the last test subprocess got killed due to a timeout.
2950 * Since: 2.16
2952 gboolean
2953 g_test_trap_reached_timeout (void)
2955 return test_trap_last_status == G_TEST_STATUS_TIMED_OUT;
2958 void
2959 g_test_trap_assertions (const char *domain,
2960 const char *file,
2961 int line,
2962 const char *func,
2963 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
2964 const char *pattern)
2966 gboolean must_pass = assertion_flags == 0;
2967 gboolean must_fail = assertion_flags == 1;
2968 gboolean match_result = 0 == (assertion_flags & 1);
2969 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
2970 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
2971 const char *match_error = match_result ? "failed to match" : "contains invalid match";
2972 char *process_id;
2974 #ifdef G_OS_UNIX
2975 if (test_trap_last_subprocess != NULL)
2977 process_id = g_strdup_printf ("%s [%d]", test_trap_last_subprocess,
2978 test_trap_last_pid);
2980 else if (test_trap_last_pid != 0)
2981 process_id = g_strdup_printf ("%d", test_trap_last_pid);
2982 #else
2983 if (test_trap_last_subprocess != NULL)
2984 process_id = g_strdup (test_trap_last_subprocess);
2985 #endif
2986 else
2987 g_error ("g_test_trap_ assertion with no trapped test");
2989 if (must_pass && !g_test_trap_has_passed())
2991 char *msg = g_strdup_printf ("child process (%s) failed unexpectedly", process_id);
2992 g_assertion_message (domain, file, line, func, msg);
2993 g_free (msg);
2995 if (must_fail && g_test_trap_has_passed())
2997 char *msg = g_strdup_printf ("child process (%s) did not fail as expected", process_id);
2998 g_assertion_message (domain, file, line, func, msg);
2999 g_free (msg);
3001 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
3003 char *msg = g_strdup_printf ("stdout of child process (%s) %s: %s", process_id, match_error, stdout_pattern);
3004 g_assertion_message (domain, file, line, func, msg);
3005 g_free (msg);
3007 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
3009 char *msg = g_strdup_printf ("stderr of child process (%s) %s: %s", process_id, match_error, stderr_pattern);
3010 g_assertion_message (domain, file, line, func, msg);
3011 g_free (msg);
3013 g_free (process_id);
3016 static void
3017 gstring_overwrite_int (GString *gstring,
3018 guint pos,
3019 guint32 vuint)
3021 vuint = g_htonl (vuint);
3022 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
3025 static void
3026 gstring_append_int (GString *gstring,
3027 guint32 vuint)
3029 vuint = g_htonl (vuint);
3030 g_string_append_len (gstring, (const gchar*) &vuint, 4);
3033 static void
3034 gstring_append_double (GString *gstring,
3035 double vdouble)
3037 union { double vdouble; guint64 vuint64; } u;
3038 u.vdouble = vdouble;
3039 u.vuint64 = GUINT64_TO_BE (u.vuint64);
3040 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
3043 static guint8*
3044 g_test_log_dump (GTestLogMsg *msg,
3045 guint *len)
3047 GString *gstring = g_string_sized_new (1024);
3048 guint ui;
3049 gstring_append_int (gstring, 0); /* message length */
3050 gstring_append_int (gstring, msg->log_type);
3051 gstring_append_int (gstring, msg->n_strings);
3052 gstring_append_int (gstring, msg->n_nums);
3053 gstring_append_int (gstring, 0); /* reserved */
3054 for (ui = 0; ui < msg->n_strings; ui++)
3056 guint l = strlen (msg->strings[ui]);
3057 gstring_append_int (gstring, l);
3058 g_string_append_len (gstring, msg->strings[ui], l);
3060 for (ui = 0; ui < msg->n_nums; ui++)
3061 gstring_append_double (gstring, msg->nums[ui]);
3062 *len = gstring->len;
3063 gstring_overwrite_int (gstring, 0, *len); /* message length */
3064 return (guint8*) g_string_free (gstring, FALSE);
3067 static inline long double
3068 net_double (const gchar **ipointer)
3070 union { guint64 vuint64; double vdouble; } u;
3071 guint64 aligned_int64;
3072 memcpy (&aligned_int64, *ipointer, 8);
3073 *ipointer += 8;
3074 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
3075 return u.vdouble;
3078 static inline guint32
3079 net_int (const gchar **ipointer)
3081 guint32 aligned_int;
3082 memcpy (&aligned_int, *ipointer, 4);
3083 *ipointer += 4;
3084 return g_ntohl (aligned_int);
3087 static gboolean
3088 g_test_log_extract (GTestLogBuffer *tbuffer)
3090 const gchar *p = tbuffer->data->str;
3091 GTestLogMsg msg;
3092 guint mlength;
3093 if (tbuffer->data->len < 4 * 5)
3094 return FALSE;
3095 mlength = net_int (&p);
3096 if (tbuffer->data->len < mlength)
3097 return FALSE;
3098 msg.log_type = net_int (&p);
3099 msg.n_strings = net_int (&p);
3100 msg.n_nums = net_int (&p);
3101 if (net_int (&p) == 0)
3103 guint ui;
3104 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
3105 msg.nums = g_new0 (long double, msg.n_nums);
3106 for (ui = 0; ui < msg.n_strings; ui++)
3108 guint sl = net_int (&p);
3109 msg.strings[ui] = g_strndup (p, sl);
3110 p += sl;
3112 for (ui = 0; ui < msg.n_nums; ui++)
3113 msg.nums[ui] = net_double (&p);
3114 if (p <= tbuffer->data->str + mlength)
3116 g_string_erase (tbuffer->data, 0, mlength);
3117 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
3118 return TRUE;
3121 g_free (msg.nums);
3122 g_strfreev (msg.strings);
3123 g_error ("corrupt log stream from test program");
3124 return FALSE;
3128 * g_test_log_buffer_new:
3130 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3132 GTestLogBuffer*
3133 g_test_log_buffer_new (void)
3135 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
3136 tb->data = g_string_sized_new (1024);
3137 return tb;
3141 * g_test_log_buffer_free:
3143 * Internal function for gtester to free test log messages, no ABI guarantees provided.
3145 void
3146 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
3148 g_return_if_fail (tbuffer != NULL);
3149 while (tbuffer->msgs)
3150 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
3151 g_string_free (tbuffer->data, TRUE);
3152 g_free (tbuffer);
3156 * g_test_log_buffer_push:
3158 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3160 void
3161 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
3162 guint n_bytes,
3163 const guint8 *bytes)
3165 g_return_if_fail (tbuffer != NULL);
3166 if (n_bytes)
3168 gboolean more_messages;
3169 g_return_if_fail (bytes != NULL);
3170 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
3172 more_messages = g_test_log_extract (tbuffer);
3173 while (more_messages);
3178 * g_test_log_buffer_pop:
3180 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
3182 GTestLogMsg*
3183 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
3185 GTestLogMsg *msg = NULL;
3186 g_return_val_if_fail (tbuffer != NULL, NULL);
3187 if (tbuffer->msgs)
3189 GSList *slist = g_slist_last (tbuffer->msgs);
3190 msg = slist->data;
3191 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
3193 return msg;
3197 * g_test_log_msg_free:
3199 * Internal function for gtester to free test log messages, no ABI guarantees provided.
3201 void
3202 g_test_log_msg_free (GTestLogMsg *tmsg)
3204 g_return_if_fail (tmsg != NULL);
3205 g_strfreev (tmsg->strings);
3206 g_free (tmsg->nums);
3207 g_free (tmsg);
3210 static gchar *
3211 g_test_build_filename_va (GTestFileType file_type,
3212 const gchar *first_path,
3213 va_list ap)
3215 const gchar *pathv[16];
3216 gint num_path_segments;
3218 if (file_type == G_TEST_DIST)
3219 pathv[0] = test_disted_files_dir;
3220 else if (file_type == G_TEST_BUILT)
3221 pathv[0] = test_built_files_dir;
3222 else
3223 g_assert_not_reached ();
3225 pathv[1] = first_path;
3227 for (num_path_segments = 2; num_path_segments < G_N_ELEMENTS (pathv); num_path_segments++)
3229 pathv[num_path_segments] = va_arg (ap, const char *);
3230 if (pathv[num_path_segments] == NULL)
3231 break;
3234 g_assert_cmpint (num_path_segments, <, G_N_ELEMENTS (pathv));
3236 return g_build_filenamev ((gchar **) pathv);
3240 * g_test_build_filename:
3241 * @file_type: the type of file (built vs. distributed)
3242 * @first_path: the first segment of the pathname
3243 * @...: %NULL-terminated additional path segments
3245 * Creates the pathname to a data file that is required for a test.
3247 * This function is conceptually similar to g_build_filename() except
3248 * that the first argument has been replaced with a #GTestFileType
3249 * argument.
3251 * The data file should either have been distributed with the module
3252 * containing the test (%G_TEST_DIST) or built as part of the build
3253 * system of that module (%G_TEST_BUILT).
3255 * In order for this function to work in srcdir != builddir situations,
3256 * the G_TEST_SRCDIR and G_TEST_BUILDDIR environment variables need to
3257 * have been defined. As of 2.38, this is done by the glib.mk
3258 * included in GLib. Please ensure that your copy is up to date before
3259 * using this function.
3261 * In case neither variable is set, this function will fall back to
3262 * using the dirname portion of argv[0], possibly removing ".libs".
3263 * This allows for casual running of tests directly from the commandline
3264 * in the srcdir == builddir case and should also support running of
3265 * installed tests, assuming the data files have been installed in the
3266 * same relative path as the test binary.
3268 * Returns: the path of the file, to be freed using g_free()
3270 * Since: 2.38
3273 * GTestFileType:
3274 * @G_TEST_DIST: a file that was included in the distribution tarball
3275 * @G_TEST_BUILT: a file that was built on the compiling machine
3277 * The type of file to return the filename for, when used with
3278 * g_test_build_filename().
3280 * These two options correspond rather directly to the 'dist' and
3281 * 'built' terminology that automake uses and are explicitly used to
3282 * distinguish between the 'srcdir' and 'builddir' being separate. All
3283 * files in your project should either be dist (in the
3284 * <literal>DIST_EXTRA</literal> or <literal>dist_schema_DATA</literal>
3285 * sense, in which case they will always be in the srcdir) or built (in
3286 * the <literal>BUILT_SOURCES</literal> sense, in which case they will
3287 * always be in the builddir).
3289 * Note: as a general rule of automake, files that are generated only as
3290 * part of the build-from-git process (but then are distributed with the
3291 * tarball) always go in srcdir (even if doing a srcdir != builddir
3292 * build from git) and are considered as distributed files.
3294 * Since: 2.38
3296 gchar *
3297 g_test_build_filename (GTestFileType file_type,
3298 const gchar *first_path,
3299 ...)
3301 gchar *result;
3302 va_list ap;
3304 g_assert (g_test_initialized ());
3306 va_start (ap, first_path);
3307 result = g_test_build_filename_va (file_type, first_path, ap);
3308 va_end (ap);
3310 return result;
3314 * g_test_get_dir:
3315 * @file_type: the type of file (built vs. distributed)
3317 * Gets the pathname of the directory containing test files of the type
3318 * specified by @file_type.
3320 * This is approximately the same as calling g_test_build_filename("."),
3321 * but you don't need to free the return value.
3323 * Returns: the path of the directory, owned by GLib
3325 * Since: 2.38
3327 const gchar *
3328 g_test_get_dir (GTestFileType file_type)
3330 g_assert (g_test_initialized ());
3332 if (file_type == G_TEST_DIST)
3333 return test_disted_files_dir;
3334 else if (file_type == G_TEST_BUILT)
3335 return test_built_files_dir;
3337 g_assert_not_reached ();
3341 * g_test_get_filename:
3342 * @file_type: the type of file (built vs. distributed)
3343 * @first_path: the first segment of the pathname
3344 * @...: %NULL-terminated additional path segments
3346 * Gets the pathname to a data file that is required for a test.
3348 * This is the same as g_test_build_filename() with two differences.
3349 * The first difference is that must only use this function from within
3350 * a testcase function. The second difference is that you need not free
3351 * the return value -- it will be automatically freed when the testcase
3352 * finishes running.
3354 * It is safe to use this function from a thread inside of a testcase
3355 * but you must ensure that all such uses occur before the main testcase
3356 * function returns (ie: it is best to ensure that all threads have been
3357 * joined).
3359 * Returns: the path, automatically freed at the end of the testcase
3361 * Since: 2.38
3363 const gchar *
3364 g_test_get_filename (GTestFileType file_type,
3365 const gchar *first_path,
3366 ...)
3368 gchar *result;
3369 GSList *node;
3370 va_list ap;
3372 g_assert (g_test_initialized ());
3373 if (test_filename_free_list == NULL)
3374 g_error ("g_test_get_filename() can only be used within testcase functions");
3376 va_start (ap, first_path);
3377 result = g_test_build_filename_va (file_type, first_path, ap);
3378 va_end (ap);
3380 node = g_slist_prepend (NULL, result);
3382 node->next = *test_filename_free_list;
3383 while (!g_atomic_pointer_compare_and_exchange (test_filename_free_list, node->next, node));
3385 return result;
3388 /* --- macros docs START --- */
3390 * g_test_add:
3391 * @testpath: The test path for a new test case.
3392 * @Fixture: The type of a fixture data structure.
3393 * @tdata: Data argument for the test functions.
3394 * @fsetup: The function to set up the fixture data.
3395 * @ftest: The actual test function.
3396 * @fteardown: The function to tear down the fixture data.
3398 * Hook up a new test case at @testpath, similar to g_test_add_func().
3399 * A fixture data structure with setup and teardown function may be provided
3400 * though, similar to g_test_create_case().
3401 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
3402 * fteardown() callbacks can expect a @Fixture pointer as first argument in
3403 * a type safe manner.
3405 * Since: 2.16
3407 /* --- macros docs END --- */