651a712c174c639ca1a14952523daf9dd468b6ec
[platform/upstream/glib.git] / glib / gtestutils.c
1 /* GLib testing utilities
2  * Copyright (C) 2007 Imendio AB
3  * Authors: Tim Janik, Sven Herzberg
4  *
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.
9  *
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.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 #include "config.h"
22
23 #include "gtestutils.h"
24 #include "gfileutils.h"
25
26 #include <sys/types.h>
27 #ifdef G_OS_UNIX
28 #include <sys/wait.h>
29 #include <sys/time.h>
30 #include <fcntl.h>
31 #include <unistd.h>
32 #include <glib/gstdio.h>
33 #endif
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #ifdef HAVE_SYS_RESOURCE_H
38 #include <sys/resource.h>
39 #endif
40 #ifdef G_OS_WIN32
41 #include <io.h>
42 #include <windows.h>
43 #endif
44 #include <errno.h>
45 #include <signal.h>
46 #ifdef HAVE_SYS_SELECT_H
47 #include <sys/select.h>
48 #endif /* HAVE_SYS_SELECT_H */
49
50 #include "gmain.h"
51 #include "gpattern.h"
52 #include "grand.h"
53 #include "gstrfuncs.h"
54 #include "gtimer.h"
55 #include "gslice.h"
56 #include "gspawn.h"
57 #include "glib-private.h"
58
59
60 /**
61  * SECTION:testing
62  * @title: Testing
63  * @short_description: a test framework
64  * @see_also: <link linkend="gtester">gtester</link>,
65  *            <link linkend="gtester-report">gtester-report</link>
66  *
67  * GLib provides a framework for writing and maintaining unit tests
68  * in parallel to the code they are testing. The API is designed according
69  * to established concepts found in the other test frameworks (JUnit, NUnit,
70  * RUnit), which in turn is based on smalltalk unit testing concepts.
71  *
72  * <variablelist>
73  *   <varlistentry>
74  *     <term>Test case</term>
75  *     <listitem>Tests (test methods) are grouped together with their
76  *       fixture into test cases.</listitem>
77  *   </varlistentry>
78  *   <varlistentry>
79  *     <term>Fixture</term>
80  *     <listitem>A test fixture consists of fixture data and setup and
81  *       teardown methods to establish the environment for the test
82  *       functions. We use fresh fixtures, i.e. fixtures are newly set
83  *       up and torn down around each test invocation to avoid dependencies
84  *       between tests.</listitem>
85  *   </varlistentry>
86  *   <varlistentry>
87  *     <term>Test suite</term>
88  *     <listitem>Test cases can be grouped into test suites, to allow
89  *       subsets of the available tests to be run. Test suites can be
90  *       grouped into other test suites as well.</listitem>
91  *   </varlistentry>
92  * </variablelist>
93  * The API is designed to handle creation and registration of test suites
94  * and test cases implicitly. A simple call like
95  * |[
96  *   g_test_add_func ("/misc/assertions", test_assertions);
97  * ]|
98  * creates a test suite called "misc" with a single test case named
99  * "assertions", which consists of running the test_assertions function.
100  *
101  * In addition to the traditional g_assert(), the test framework provides
102  * an extended set of assertions for string and numerical comparisons:
103  * g_assert_cmpfloat(), g_assert_cmpint(), g_assert_cmpuint(),
104  * g_assert_cmphex(), g_assert_cmpstr(). The advantage of these variants
105  * over plain g_assert() is that the assertion messages can be more
106  * elaborate, and include the values of the compared entities.
107  *
108  * GLib ships with two utilities called gtester and gtester-report to
109  * facilitate running tests and producing nicely formatted test reports.
110  */
111
112 /**
113  * g_test_initialized:
114  *
115  * Returns %TRUE if g_test_init() has been called.
116  *
117  * Returns: %TRUE if g_test_init() has been called.
118  *
119  * Since: 2.36
120  */
121
122 /**
123  * g_test_quick:
124  *
125  * Returns %TRUE if tests are run in quick mode.
126  * Exactly one of g_test_quick() and g_test_slow() is active in any run;
127  * there is no "medium speed".
128  *
129  * Returns: %TRUE if in quick mode
130  */
131
132 /**
133  * g_test_slow:
134  *
135  * Returns %TRUE if tests are run in slow mode.
136  * Exactly one of g_test_quick() and g_test_slow() is active in any run;
137  * there is no "medium speed".
138  *
139  * Returns: the opposite of g_test_quick()
140  */
141
142 /**
143  * g_test_thorough:
144  *
145  * Returns %TRUE if tests are run in thorough mode, equivalent to
146  * g_test_slow().
147  *
148  * Returns: the same thing as g_test_slow()
149  */
150
151 /**
152  * g_test_perf:
153  *
154  * Returns %TRUE if tests are run in performance mode.
155  *
156  * Returns: %TRUE if in performance mode
157  */
158
159 /**
160  * g_test_undefined:
161  *
162  * Returns %TRUE if tests may provoke assertions and other formally-undefined
163  * behaviour, to verify that appropriate warnings are given. It might, in some
164  * cases, be useful to turn this off if running tests under valgrind.
165  *
166  * Returns: %TRUE if tests may provoke programming errors
167  */
168
169 /**
170  * g_test_verbose:
171  *
172  * Returns %TRUE if tests are run in verbose mode.
173  * The default is neither g_test_verbose() nor g_test_quiet().
174  *
175  * Returns: %TRUE if in verbose mode
176  */
177
178 /**
179  * g_test_quiet:
180  *
181  * Returns %TRUE if tests are run in quiet mode.
182  * The default is neither g_test_verbose() nor g_test_quiet().
183  *
184  * Returns: %TRUE if in quiet mode
185  */
186
187 /**
188  * g_test_queue_unref:
189  * @gobject: the object to unref
190  *
191  * Enqueue an object to be released with g_object_unref() during
192  * the next teardown phase. This is equivalent to calling
193  * g_test_queue_destroy() with a destroy callback of g_object_unref().
194  *
195  * Since: 2.16
196  */
197
198 /**
199  * GTestTrapFlags:
200  * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
201  *     <filename>/dev/null</filename> so it cannot be observed on the
202  *     console during test runs. The actual output is still captured
203  *     though to allow later tests with g_test_trap_assert_stdout().
204  * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
205  *     <filename>/dev/null</filename> so it cannot be observed on the
206  *     console during test runs. The actual output is still captured
207  *     though to allow later tests with g_test_trap_assert_stderr().
208  * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
209  *     child process is shared with stdin of its parent process.
210  *     It is redirected to <filename>/dev/null</filename> otherwise.
211  *
212  * Test traps are guards around forked tests.
213  * These flags determine what traps to set.
214  *
215  * Deprecated: #GTestTrapFlags is used only with g_test_trap_fork(),
216  * which is deprecated. g_test_trap_subprocess() uses
217  * #GTestTrapSubprocessFlags.
218  */
219
220 /**
221  * GTestSubprocessFlags:
222  * @G_TEST_SUBPROCESS_INHERIT_STDIN: If this flag is given, the child
223  *     process will inherit the parent's stdin. Otherwise, the child's
224  *     stdin is redirected to <filename>/dev/null</filename>.
225  * @G_TEST_SUBPROCESS_INHERIT_STDOUT: If this flag is given, the child
226  *     process will inherit the parent's stdout. Otherwise, the child's
227  *     stdout will not be visible, but it will be captured to allow
228  *     later tests with g_test_trap_assert_stdout().
229  * @G_TEST_SUBPROCESS_INHERIT_STDERR: If this flag is given, the child
230  *     process will inherit the parent's stderr. Otherwise, the child's
231  *     stderr will not be visible, but it will be captured to allow
232  *     later tests with g_test_trap_assert_stderr().
233  *
234  * Flags to pass to g_test_trap_subprocess() to control input and output.
235  *
236  * Note that in contrast with g_test_trap_fork(), the default is to
237  * not show stdout and stderr.
238  */
239
240 /**
241  * g_test_trap_assert_passed:
242  *
243  * Assert that the last test subprocess passed.
244  * See g_test_trap_subprocess().
245  *
246  * Since: 2.16
247  */
248
249 /**
250  * g_test_trap_assert_failed:
251  *
252  * Assert that the last test subprocess failed.
253  * See g_test_trap_subprocess().
254  *
255  * This is sometimes used to test situations that are formally considered to
256  * be undefined behaviour, like inputs that fail a g_return_if_fail()
257  * check. In these situations you should skip the entire test, including the
258  * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
259  * to indicate that undefined behaviour may be tested.
260  *
261  * Since: 2.16
262  */
263
264 /**
265  * g_test_trap_assert_stdout:
266  * @soutpattern: a glob-style
267  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
268  *
269  * Assert that the stdout output of the last test subprocess matches
270  * @soutpattern. See g_test_trap_subprocess().
271  *
272  * Since: 2.16
273  */
274
275 /**
276  * g_test_trap_assert_stdout_unmatched:
277  * @soutpattern: a glob-style
278  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
279  *
280  * Assert that the stdout output of the last test subprocess
281  * does not match @soutpattern. See g_test_trap_subprocess().
282  *
283  * Since: 2.16
284  */
285
286 /**
287  * g_test_trap_assert_stderr:
288  * @serrpattern: a glob-style
289  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
290  *
291  * Assert that the stderr output of the last test subprocess
292  * matches @serrpattern. See  g_test_trap_subprocess().
293  *
294  * This is sometimes used to test situations that are formally
295  * considered to be undefined behaviour, like code that hits a
296  * g_assert() or g_error(). In these situations you should skip the
297  * entire test, including the call to g_test_trap_subprocess(), unless
298  * g_test_undefined() returns %TRUE to indicate that undefined
299  * behaviour may be tested.
300  *
301  * Since: 2.16
302  */
303
304 /**
305  * g_test_trap_assert_stderr_unmatched:
306  * @serrpattern: a glob-style
307  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
308  *
309  * Assert that the stderr output of the last test subprocess
310  * does not match @serrpattern. See g_test_trap_subprocess().
311  *
312  * Since: 2.16
313  */
314
315 /**
316  * g_test_rand_bit:
317  *
318  * Get a reproducible random bit (0 or 1), see g_test_rand_int()
319  * for details on test case random numbers.
320  *
321  * Since: 2.16
322  */
323
324 /**
325  * g_assert:
326  * @expr: the expression to check
327  *
328  * Debugging macro to terminate the application if the assertion
329  * fails. If the assertion fails (i.e. the expression is not true),
330  * an error message is logged and the application is terminated.
331  *
332  * The macro can be turned off in final releases of code by defining
333  * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
334  */
335
336 /**
337  * g_assert_not_reached:
338  *
339  * Debugging macro to terminate the application if it is ever
340  * reached. If it is reached, an error message is logged and the
341  * application is terminated.
342  *
343  * The macro can be turned off in final releases of code by defining
344  * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
345  */
346
347 /**
348  * g_assert_true:
349  * @expr: the expression to check
350  *
351  * Debugging macro to check that an expression is true.
352  *
353  * If the assertion fails (i.e. the expression is not true),
354  * an error message is logged and the application is either
355  * terminated or the testcase marked as failed.
356  *
357  * See g_test_set_nonfatal_assertions().
358  *
359  * Since: 2.38
360  */
361
362 /**
363  * g_assert_false:
364  * @expr: the expression to check
365  *
366  * Debugging macro to check an expression is false.
367  *
368  * If the assertion fails (i.e. the expression is not false),
369  * an error message is logged and the application is either
370  * terminated or the testcase marked as failed.
371  *
372  * See g_test_set_nonfatal_assertions().
373  *
374  * Since: 2.38
375  */
376
377 /**
378  * g_assert_null:
379  * @expr: the expression to check
380  *
381  * Debugging macro to check an expression is %NULL.
382  *
383  * If the assertion fails (i.e. the expression is not %NULL),
384  * an error message is logged and the application is either
385  * terminated or the testcase marked as failed.
386  *
387  * See g_test_set_nonfatal_assertions().
388  *
389  * Since: 2.38
390  */
391
392 /**
393  * g_assert_nonnull:
394  * @expr: the expression to check
395  *
396  * Debugging macro to check an expression is not %NULL.
397  *
398  * If the assertion fails (i.e. the expression is %NULL),
399  * an error message is logged and the application is either
400  * terminated or the testcase marked as failed.
401  *
402  * See g_test_set_nonfatal_assertions().
403  *
404  * Since: 2.40
405  */
406
407 /**
408  * g_assert_cmpstr:
409  * @s1: a string (may be %NULL)
410  * @cmp: The comparison operator to use.
411  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
412  * @s2: another string (may be %NULL)
413  *
414  * Debugging macro to compare two strings. If the comparison fails,
415  * an error message is logged and the application is either terminated
416  * or the testcase marked as failed.
417  * The strings are compared using g_strcmp0().
418  *
419  * The effect of <literal>g_assert_cmpstr (s1, op, s2)</literal> is
420  * the same as <literal>g_assert_true (g_strcmp0 (s1, s2) op 0)</literal>.
421  * The advantage of this macro is that it can produce a message that
422  * includes the actual values of @s1 and @s2.
423  *
424  * |[
425  *   g_assert_cmpstr (mystring, ==, "fubar");
426  * ]|
427  *
428  * Since: 2.16
429  */
430
431 /**
432  * g_assert_cmpint:
433  * @n1: an integer
434  * @cmp: The comparison operator to use.
435  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
436  * @n2: another integer
437  *
438  * Debugging macro to compare two integers.
439  *
440  * The effect of <literal>g_assert_cmpint (n1, op, n2)</literal> is
441  * the same as <literal>g_assert_true (n1 op n2)</literal>. The advantage
442  * of this macro is that it can produce a message that includes the
443  * actual values of @n1 and @n2.
444  *
445  * Since: 2.16
446  */
447
448 /**
449  * g_assert_cmpuint:
450  * @n1: an unsigned integer
451  * @cmp: The comparison operator to use.
452  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
453  * @n2: another unsigned integer
454  *
455  * Debugging macro to compare two unsigned integers.
456  *
457  * The effect of <literal>g_assert_cmpuint (n1, op, n2)</literal> is
458  * the same as <literal>g_assert_true (n1 op n2)</literal>. The advantage
459  * of this macro is that it can produce a message that includes the
460  * actual values of @n1 and @n2.
461  *
462  * Since: 2.16
463  */
464
465 /**
466  * g_assert_cmphex:
467  * @n1: an unsigned integer
468  * @cmp: The comparison operator to use.
469  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
470  * @n2: another unsigned integer
471  *
472  * Debugging macro to compare to unsigned integers.
473  *
474  * This is a variant of g_assert_cmpuint() that displays the numbers
475  * in hexadecimal notation in the message.
476  *
477  * Since: 2.16
478  */
479
480 /**
481  * g_assert_cmpfloat:
482  * @n1: an floating point number
483  * @cmp: The comparison operator to use.
484  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
485  * @n2: another floating point number
486  *
487  * Debugging macro to compare two floating point numbers.
488  *
489  * The effect of <literal>g_assert_cmpfloat (n1, op, n2)</literal> is
490  * the same as <literal>g_assert_true (n1 op n2)</literal>. The advantage
491  * of this macro is that it can produce a message that includes the
492  * actual values of @n1 and @n2.
493  *
494  * Since: 2.16
495  */
496
497 /**
498  * g_assert_no_error:
499  * @err: a #GError, possibly %NULL
500  *
501  * Debugging macro to check that a #GError is not set.
502  *
503  * The effect of <literal>g_assert_no_error (err)</literal> is
504  * the same as <literal>g_assert_true (err == NULL)</literal>. The advantage
505  * of this macro is that it can produce a message that includes
506  * the error message and code.
507  *
508  * Since: 2.20
509  */
510
511 /**
512  * g_assert_error:
513  * @err: a #GError, possibly %NULL
514  * @dom: the expected error domain (a #GQuark)
515  * @c: the expected error code
516  *
517  * Debugging macro to check that a method has returned
518  * the correct #GError.
519  *
520  * The effect of <literal>g_assert_error (err, dom, c)</literal> is
521  * the same as <literal>g_assert_true (err != NULL &amp;&amp; err->domain
522  * == dom &amp;&amp; err->code == c)</literal>. The advantage of this
523  * macro is that it can produce a message that includes the incorrect
524  * error message and code.
525  *
526  * This can only be used to test for a specific error. If you want to
527  * test that @err is set, but don't care what it's set to, just use
528  * <literal>g_assert (err != NULL)</literal>
529  *
530  * Since: 2.20
531  */
532
533 /**
534  * GTestCase:
535  *
536  * An opaque structure representing a test case.
537  */
538
539 /**
540  * GTestSuite:
541  *
542  * An opaque structure representing a test suite.
543  */
544
545
546 /* Global variable for storing assertion messages; this is the counterpart to
547  * glibc's (private) __abort_msg variable, and allows developers and crash
548  * analysis systems like Apport and ABRT to fish out assertion messages from
549  * core dumps, instead of having to catch them on screen output.
550  */
551 GLIB_VAR char *__glib_assert_msg;
552 char *__glib_assert_msg = NULL;
553
554 /* --- constants --- */
555 #define G_TEST_STATUS_TIMED_OUT 1024
556
557 /* --- structures --- */
558 struct GTestCase
559 {
560   gchar  *name;
561   guint   fixture_size;
562   void   (*fixture_setup)    (void*, gconstpointer);
563   void   (*fixture_test)     (void*, gconstpointer);
564   void   (*fixture_teardown) (void*, gconstpointer);
565   gpointer test_data;
566 };
567 struct GTestSuite
568 {
569   gchar  *name;
570   GSList *suites;
571   GSList *cases;
572 };
573 typedef struct DestroyEntry DestroyEntry;
574 struct DestroyEntry
575 {
576   DestroyEntry *next;
577   GDestroyNotify destroy_func;
578   gpointer       destroy_data;
579 };
580
581 /* --- prototypes --- */
582 static void     test_run_seed                   (const gchar *rseed);
583 static void     test_trap_clear                 (void);
584 static guint8*  g_test_log_dump                 (GTestLogMsg *msg,
585                                                  guint       *len);
586 static void     gtest_default_log_handler       (const gchar    *log_domain,
587                                                  GLogLevelFlags  log_level,
588                                                  const gchar    *message,
589                                                  gpointer        unused_data);
590
591
592 typedef enum {
593   G_TEST_RUN_SUCCESS,
594   G_TEST_RUN_SKIPPED,
595   G_TEST_RUN_FAILURE,
596   G_TEST_RUN_INCOMPLETE
597 } GTestResult;
598
599 /* --- variables --- */
600 static int         test_log_fd = -1;
601 static gboolean    test_mode_fatal = TRUE;
602 static gboolean    g_test_run_once = TRUE;
603 static gboolean    test_run_list = FALSE;
604 static gchar      *test_run_seedstr = NULL;
605 static GRand      *test_run_rand = NULL;
606 static gchar      *test_run_name = "";
607 static GSList    **test_filename_free_list;
608 static guint       test_run_forks = 0;
609 static guint       test_run_count = 0;
610 static guint       test_skipped_count = 0;
611 static GTestResult test_run_success = G_TEST_RUN_FAILURE;
612 static gchar      *test_run_msg = NULL;
613 static guint       test_startup_skip_count = 0;
614 static GTimer     *test_user_timer = NULL;
615 static double      test_user_stamp = 0;
616 static GSList     *test_paths = NULL;
617 static GSList     *test_paths_skipped = NULL;
618 static GTestSuite *test_suite_root = NULL;
619 static int         test_trap_last_status = 0;
620 static GPid        test_trap_last_pid = 0;
621 static char       *test_trap_last_subprocess = NULL;
622 static char       *test_trap_last_stdout = NULL;
623 static char       *test_trap_last_stderr = NULL;
624 static char       *test_uri_base = NULL;
625 static gboolean    test_debug_log = FALSE;
626 static gboolean    test_tap_log = FALSE;
627 static gboolean    test_nonfatal_assertions = FALSE;
628 static DestroyEntry *test_destroy_queue = NULL;
629 static char       *test_argv0 = NULL;
630 static char       *test_argv0_dirname;
631 static const char *test_disted_files_dir;
632 static const char *test_built_files_dir;
633 static char       *test_initial_cwd = NULL;
634 static gboolean    test_in_subprocess = FALSE;
635 static GTestConfig mutable_test_config_vars = {
636   FALSE,        /* test_initialized */
637   TRUE,         /* test_quick */
638   FALSE,        /* test_perf */
639   FALSE,        /* test_verbose */
640   FALSE,        /* test_quiet */
641   TRUE,         /* test_undefined */
642 };
643 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
644 static gboolean  no_g_set_prgname = FALSE;
645
646 /* --- functions --- */
647 const char*
648 g_test_log_type_name (GTestLogType log_type)
649 {
650   switch (log_type)
651     {
652     case G_TEST_LOG_NONE:               return "none";
653     case G_TEST_LOG_ERROR:              return "error";
654     case G_TEST_LOG_START_BINARY:       return "binary";
655     case G_TEST_LOG_LIST_CASE:          return "list";
656     case G_TEST_LOG_SKIP_CASE:          return "skip";
657     case G_TEST_LOG_START_CASE:         return "start";
658     case G_TEST_LOG_STOP_CASE:          return "stop";
659     case G_TEST_LOG_MIN_RESULT:         return "minperf";
660     case G_TEST_LOG_MAX_RESULT:         return "maxperf";
661     case G_TEST_LOG_MESSAGE:            return "message";
662     case G_TEST_LOG_START_SUITE:        return "start suite";
663     case G_TEST_LOG_STOP_SUITE:         return "stop suite";
664     }
665   return "???";
666 }
667
668 static void
669 g_test_log_send (guint         n_bytes,
670                  const guint8 *buffer)
671 {
672   if (test_log_fd >= 0)
673     {
674       int r;
675       do
676         r = write (test_log_fd, buffer, n_bytes);
677       while (r < 0 && errno == EINTR);
678     }
679   if (test_debug_log)
680     {
681       GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
682       GTestLogMsg *msg;
683       guint ui;
684       g_test_log_buffer_push (lbuffer, n_bytes, buffer);
685       msg = g_test_log_buffer_pop (lbuffer);
686       g_warn_if_fail (msg != NULL);
687       g_warn_if_fail (lbuffer->data->len == 0);
688       g_test_log_buffer_free (lbuffer);
689       /* print message */
690       g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
691       for (ui = 0; ui < msg->n_strings; ui++)
692         g_printerr (":{%s}", msg->strings[ui]);
693       if (msg->n_nums)
694         {
695           g_printerr (":(");
696           for (ui = 0; ui < msg->n_nums; ui++)
697             {
698               if ((long double) (long) msg->nums[ui] == msg->nums[ui])
699                 g_printerr ("%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
700               else
701                 g_printerr ("%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
702             }
703           g_printerr (")");
704         }
705       g_printerr (":LOG*}\n");
706       g_test_log_msg_free (msg);
707     }
708 }
709
710 static void
711 g_test_log (GTestLogType lbit,
712             const gchar *string1,
713             const gchar *string2,
714             guint        n_args,
715             long double *largs)
716 {
717   gboolean fail;
718   GTestLogMsg msg;
719   gchar *astrings[3] = { NULL, NULL, NULL };
720   guint8 *dbuffer;
721   guint32 dbufferlen;
722
723   switch (lbit)
724     {
725     case G_TEST_LOG_START_BINARY:
726       if (test_tap_log)
727         g_print ("# random seed: %s\n", string2);
728       else if (g_test_verbose())
729         g_print ("GTest: random seed: %s\n", string2);
730       break;
731     case G_TEST_LOG_START_SUITE:
732       if (test_tap_log)
733         {
734           if (string1[0] != 0)
735             g_print ("# Start of %s tests\n", string1);
736         }
737       break;
738     case G_TEST_LOG_STOP_SUITE:
739       if (test_tap_log)
740         {
741           if (string1[0] != 0)
742             g_print ("# End of %s tests\n", string1);
743           else
744             g_print ("1..%d\n", test_run_count);
745         }
746       break;
747     case G_TEST_LOG_STOP_CASE:
748       fail = largs[0] != G_TEST_RUN_SUCCESS && largs[0] != G_TEST_RUN_SKIPPED;
749       if (test_tap_log)
750         {
751           g_print ("%s %d %s", fail ? "not ok" : "ok", test_run_count, string1);
752           if (largs[0] == G_TEST_RUN_INCOMPLETE)
753             g_print (" # TODO %s\n", string2 ? string2 : "");
754           else if (largs[0] == G_TEST_RUN_SKIPPED)
755             g_print (" # SKIP %s\n", string2 ? string2 : "");
756           else
757             g_print ("\n");
758         }
759       else if (g_test_verbose())
760         g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
761       else if (!g_test_quiet())
762         g_print ("%s\n", fail ? "FAIL" : "OK");
763       if (fail && test_mode_fatal)
764         {
765           if (test_tap_log)
766             g_print ("Bail out!\n");
767           abort();
768         }
769       if (largs[0] == G_TEST_RUN_SKIPPED)
770         test_skipped_count++;
771       break;
772     case G_TEST_LOG_MIN_RESULT:
773       if (test_tap_log)
774         g_print ("# min perf: %s\n", string1);
775       else if (g_test_verbose())
776         g_print ("(MINPERF:%s)\n", string1);
777       break;
778     case G_TEST_LOG_MAX_RESULT:
779       if (test_tap_log)
780         g_print ("# max perf: %s\n", string1);
781       else if (g_test_verbose())
782         g_print ("(MAXPERF:%s)\n", string1);
783       break;
784     case G_TEST_LOG_MESSAGE:
785     case G_TEST_LOG_ERROR:
786       if (test_tap_log)
787         g_print ("# %s\n", string1);
788       else if (g_test_verbose())
789         g_print ("(MSG: %s)\n", string1);
790       break;
791     default: ;
792     }
793
794   msg.log_type = lbit;
795   msg.n_strings = (string1 != NULL) + (string1 && string2);
796   msg.strings = astrings;
797   astrings[0] = (gchar*) string1;
798   astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
799   msg.n_nums = n_args;
800   msg.nums = largs;
801   dbuffer = g_test_log_dump (&msg, &dbufferlen);
802   g_test_log_send (dbufferlen, dbuffer);
803   g_free (dbuffer);
804
805   switch (lbit)
806     {
807     case G_TEST_LOG_START_CASE:
808       if (test_tap_log)
809         ;
810       else if (g_test_verbose())
811         g_print ("GTest: run: %s\n", string1);
812       else if (!g_test_quiet())
813         g_print ("%s: ", string1);
814       break;
815     default: ;
816     }
817 }
818
819 /* We intentionally parse the command line without GOptionContext
820  * because otherwise you would never be able to test it.
821  */
822 static void
823 parse_args (gint    *argc_p,
824             gchar ***argv_p)
825 {
826   guint argc = *argc_p;
827   gchar **argv = *argv_p;
828   guint i, e;
829
830   test_argv0 = argv[0];
831   test_initial_cwd = g_get_current_dir ();
832
833   /* parse known args */
834   for (i = 1; i < argc; i++)
835     {
836       if (strcmp (argv[i], "--g-fatal-warnings") == 0)
837         {
838           GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
839           fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
840           g_log_set_always_fatal (fatal_mask);
841           argv[i] = NULL;
842         }
843       else if (strcmp (argv[i], "--keep-going") == 0 ||
844                strcmp (argv[i], "-k") == 0)
845         {
846           test_mode_fatal = FALSE;
847           argv[i] = NULL;
848         }
849       else if (strcmp (argv[i], "--debug-log") == 0)
850         {
851           test_debug_log = TRUE;
852           argv[i] = NULL;
853         }
854       else if (strcmp (argv[i], "--tap") == 0)
855         {
856           test_tap_log = TRUE;
857           argv[i] = NULL;
858         }
859       else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
860         {
861           gchar *equal = argv[i] + 12;
862           if (*equal == '=')
863             test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
864           else if (i + 1 < argc)
865             {
866               argv[i++] = NULL;
867               test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
868             }
869           argv[i] = NULL;
870         }
871       else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
872         {
873           gchar *equal = argv[i] + 16;
874           if (*equal == '=')
875             test_startup_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
876           else if (i + 1 < argc)
877             {
878               argv[i++] = NULL;
879               test_startup_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
880             }
881           argv[i] = NULL;
882         }
883       else if (strcmp ("--GTestSubprocess", argv[i]) == 0)
884         {
885           test_in_subprocess = TRUE;
886           /* We typically expect these child processes to crash, and some
887            * tests spawn a *lot* of them.  Avoid spamming system crash
888            * collection programs such as systemd-coredump and abrt.
889            */
890 #ifdef HAVE_SYS_RESOURCE_H
891           {
892             struct rlimit limit = { 0, 0 };
893             (void) setrlimit (RLIMIT_CORE, &limit);
894           }
895 #endif
896           argv[i] = NULL;
897         }
898       else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
899         {
900           gchar *equal = argv[i] + 2;
901           if (*equal == '=')
902             test_paths = g_slist_prepend (test_paths, equal + 1);
903           else if (i + 1 < argc)
904             {
905               argv[i++] = NULL;
906               test_paths = g_slist_prepend (test_paths, argv[i]);
907             }
908           argv[i] = NULL;
909         }
910       else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
911         {
912           gchar *equal = argv[i] + 2;
913           if (*equal == '=')
914             test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
915           else if (i + 1 < argc)
916             {
917               argv[i++] = NULL;
918               test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
919             }
920           argv[i] = NULL;
921         }
922       else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
923         {
924           gchar *equal = argv[i] + 2;
925           const gchar *mode = "";
926           if (*equal == '=')
927             mode = equal + 1;
928           else if (i + 1 < argc)
929             {
930               argv[i++] = NULL;
931               mode = argv[i];
932             }
933           if (strcmp (mode, "perf") == 0)
934             mutable_test_config_vars.test_perf = TRUE;
935           else if (strcmp (mode, "slow") == 0)
936             mutable_test_config_vars.test_quick = FALSE;
937           else if (strcmp (mode, "thorough") == 0)
938             mutable_test_config_vars.test_quick = FALSE;
939           else if (strcmp (mode, "quick") == 0)
940             {
941               mutable_test_config_vars.test_quick = TRUE;
942               mutable_test_config_vars.test_perf = FALSE;
943             }
944           else if (strcmp (mode, "undefined") == 0)
945             mutable_test_config_vars.test_undefined = TRUE;
946           else if (strcmp (mode, "no-undefined") == 0)
947             mutable_test_config_vars.test_undefined = FALSE;
948           else
949             g_error ("unknown test mode: -m %s", mode);
950           argv[i] = NULL;
951         }
952       else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
953         {
954           mutable_test_config_vars.test_quiet = TRUE;
955           mutable_test_config_vars.test_verbose = FALSE;
956           argv[i] = NULL;
957         }
958       else if (strcmp ("--verbose", argv[i]) == 0)
959         {
960           mutable_test_config_vars.test_quiet = FALSE;
961           mutable_test_config_vars.test_verbose = TRUE;
962           argv[i] = NULL;
963         }
964       else if (strcmp ("-l", argv[i]) == 0)
965         {
966           test_run_list = TRUE;
967           argv[i] = NULL;
968         }
969       else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
970         {
971           gchar *equal = argv[i] + 6;
972           if (*equal == '=')
973             test_run_seedstr = equal + 1;
974           else if (i + 1 < argc)
975             {
976               argv[i++] = NULL;
977               test_run_seedstr = argv[i];
978             }
979           argv[i] = NULL;
980         }
981       else if (strcmp ("-?", argv[i]) == 0 ||
982                strcmp ("-h", argv[i]) == 0 ||
983                strcmp ("--help", argv[i]) == 0)
984         {
985           printf ("Usage:\n"
986                   "  %s [OPTION...]\n\n"
987                   "Help Options:\n"
988                   "  -h, --help                     Show help options\n\n"
989                   "Test Options:\n"
990                   "  --g-fatal-warnings             Make all warnings fatal\n"
991                   "  -l                             List test cases available in a test executable\n"
992                   "  -m {perf|slow|thorough|quick}  Execute tests according to mode\n"
993                   "  -m {undefined|no-undefined}    Execute tests according to mode\n"
994                   "  -p TESTPATH                    Only start test cases matching TESTPATH\n"
995                   "  -s TESTPATH                    Skip all tests matching TESTPATH\n"
996                   "  -seed=SEEDSTRING               Start tests with random seed SEEDSTRING\n"
997                   "  --debug-log                    debug test logging output\n"
998                   "  -q, --quiet                    Run tests quietly\n"
999                   "  --verbose                      Run tests verbosely\n",
1000                   argv[0]);
1001           exit (0);
1002         }
1003     }
1004   /* collapse argv */
1005   e = 1;
1006   for (i = 1; i < argc; i++)
1007     if (argv[i])
1008       {
1009         argv[e++] = argv[i];
1010         if (i >= e)
1011           argv[i] = NULL;
1012       }
1013   *argc_p = e;
1014 }
1015
1016 /**
1017  * g_test_init:
1018  * @argc: Address of the @argc parameter of the main() function.
1019  *        Changed if any arguments were handled.
1020  * @argv: Address of the @argv parameter of main().
1021  *        Any parameters understood by g_test_init() stripped before return.
1022  * @...: %NULL-terminated list of special options. Currently the only
1023  *       defined option is <literal>"no_g_set_prgname"</literal>, which
1024  *       will cause g_test_init() to not call g_set_prgname().
1025  *
1026  * Initialize the GLib testing framework, e.g. by seeding the
1027  * test random number generator, the name for g_get_prgname()
1028  * and parsing test related command line args.
1029  * So far, the following arguments are understood:
1030  * <variablelist>
1031  *   <varlistentry>
1032  *     <term><option>-l</option></term>
1033  *     <listitem><para>
1034  *       List test cases available in a test executable.
1035  *     </para></listitem>
1036  *   </varlistentry>
1037  *   <varlistentry>
1038  *     <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
1039  *     <listitem><para>
1040  *       Provide a random seed to reproduce test runs using random numbers.
1041  *     </para></listitem>
1042  *     </varlistentry>
1043  *     <varlistentry>
1044  *       <term><option>--verbose</option></term>
1045  *       <listitem><para>Run tests verbosely.</para></listitem>
1046  *     </varlistentry>
1047  *     <varlistentry>
1048  *       <term><option>-q</option>, <option>--quiet</option></term>
1049  *       <listitem><para>Run tests quietly.</para></listitem>
1050  *     </varlistentry>
1051  *     <varlistentry>
1052  *       <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
1053  *       <listitem><para>
1054  *         Execute all tests matching <replaceable>TESTPATH</replaceable>.
1055  *         This can also be used to force a test to run that would otherwise
1056  *         be skipped (ie, a test whose name contains "/subprocess").
1057  *       </para></listitem>
1058  *     </varlistentry>
1059  *     <varlistentry>
1060  *       <term><option>-m {perf|slow|thorough|quick|undefined|no-undefined}</option></term>
1061  *       <listitem><para>
1062  *         Execute tests according to these test modes:
1063  *         <variablelist>
1064  *           <varlistentry>
1065  *             <term>perf</term>
1066  *             <listitem><para>
1067  *               Performance tests, may take long and report results.
1068  *             </para></listitem>
1069  *           </varlistentry>
1070  *           <varlistentry>
1071  *             <term>slow, thorough</term>
1072  *             <listitem><para>
1073  *               Slow and thorough tests, may take quite long and
1074  *               maximize coverage.
1075  *             </para></listitem>
1076  *           </varlistentry>
1077  *           <varlistentry>
1078  *             <term>quick</term>
1079  *             <listitem><para>
1080  *               Quick tests, should run really quickly and give good coverage.
1081  *             </para></listitem>
1082  *           </varlistentry>
1083  *           <varlistentry>
1084  *             <term>undefined</term>
1085  *             <listitem><para>
1086  *               Tests for undefined behaviour, may provoke programming errors
1087  *               under g_test_trap_subprocess() or g_test_expect_messages() to check
1088  *               that appropriate assertions or warnings are given
1089  *             </para></listitem>
1090  *           </varlistentry>
1091  *           <varlistentry>
1092  *             <term>no-undefined</term>
1093  *             <listitem><para>
1094  *               Avoid tests for undefined behaviour
1095  *             </para></listitem>
1096  *           </varlistentry>
1097  *         </variablelist>
1098  *       </para></listitem>
1099  *     </varlistentry>
1100  *     <varlistentry>
1101  *       <term><option>--debug-log</option></term>
1102  *       <listitem><para>Debug test logging output.</para></listitem>
1103  *     </varlistentry>
1104  *  </variablelist>
1105  *
1106  * Since: 2.16
1107  */
1108 void
1109 g_test_init (int    *argc,
1110              char ***argv,
1111              ...)
1112 {
1113   static char seedstr[4 + 4 * 8 + 1];
1114   va_list args;
1115   gpointer option;
1116   /* make warnings and criticals fatal for all test programs */
1117   GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1118
1119   fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1120   g_log_set_always_fatal (fatal_mask);
1121   /* check caller args */
1122   g_return_if_fail (argc != NULL);
1123   g_return_if_fail (argv != NULL);
1124   g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
1125   mutable_test_config_vars.test_initialized = TRUE;
1126
1127   va_start (args, argv);
1128   while ((option = va_arg (args, char *)))
1129     {
1130       if (g_strcmp0 (option, "no_g_set_prgname") == 0)
1131         no_g_set_prgname = TRUE;
1132     }
1133   va_end (args);
1134
1135   /* setup random seed string */
1136   g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
1137   test_run_seedstr = seedstr;
1138
1139   /* parse args, sets up mode, changes seed, etc. */
1140   parse_args (argc, argv);
1141
1142   if (!g_get_prgname() && !no_g_set_prgname)
1143     g_set_prgname ((*argv)[0]);
1144
1145   /* verify GRand reliability, needed for reliable seeds */
1146   if (1)
1147     {
1148       GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
1149       guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
1150       /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
1151       if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
1152         g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
1153       g_rand_free (rg);
1154     }
1155
1156   /* check rand seed */
1157   test_run_seed (test_run_seedstr);
1158
1159   /* report program start */
1160   g_log_set_default_handler (gtest_default_log_handler, NULL);
1161   g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
1162
1163   test_argv0_dirname = g_path_get_dirname (test_argv0);
1164
1165   /* Make sure we get the real dirname that the test was run from */
1166   if (g_str_has_suffix (test_argv0_dirname, "/.libs"))
1167     {
1168       gchar *tmp;
1169       tmp = g_path_get_dirname (test_argv0_dirname);
1170       g_free (test_argv0_dirname);
1171       test_argv0_dirname = tmp;
1172     }
1173
1174   test_disted_files_dir = g_getenv ("G_TEST_SRCDIR");
1175   if (!test_disted_files_dir)
1176     test_disted_files_dir = test_argv0_dirname;
1177
1178   test_built_files_dir = g_getenv ("G_TEST_BUILDDIR");
1179   if (!test_built_files_dir)
1180     test_built_files_dir = test_argv0_dirname;
1181 }
1182
1183 static void
1184 test_run_seed (const gchar *rseed)
1185 {
1186   guint seed_failed = 0;
1187   if (test_run_rand)
1188     g_rand_free (test_run_rand);
1189   test_run_rand = NULL;
1190   while (strchr (" \t\v\r\n\f", *rseed))
1191     rseed++;
1192   if (strncmp (rseed, "R02S", 4) == 0)  /* seed for random generator 02 (GRand-2.2) */
1193     {
1194       const char *s = rseed + 4;
1195       if (strlen (s) >= 32)             /* require 4 * 8 chars */
1196         {
1197           guint32 seedarray[4];
1198           gchar *p, hexbuf[9] = { 0, };
1199           memcpy (hexbuf, s + 0, 8);
1200           seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
1201           seed_failed += p != NULL && *p != 0;
1202           memcpy (hexbuf, s + 8, 8);
1203           seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
1204           seed_failed += p != NULL && *p != 0;
1205           memcpy (hexbuf, s + 16, 8);
1206           seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
1207           seed_failed += p != NULL && *p != 0;
1208           memcpy (hexbuf, s + 24, 8);
1209           seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
1210           seed_failed += p != NULL && *p != 0;
1211           if (!seed_failed)
1212             {
1213               test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
1214               return;
1215             }
1216         }
1217     }
1218   g_error ("Unknown or invalid random seed: %s", rseed);
1219 }
1220
1221 /**
1222  * g_test_rand_int:
1223  *
1224  * Get a reproducible random integer number.
1225  *
1226  * The random numbers generated by the g_test_rand_*() family of functions
1227  * change with every new test program start, unless the --seed option is
1228  * given when starting test programs.
1229  *
1230  * For individual test cases however, the random number generator is
1231  * reseeded, to avoid dependencies between tests and to make --seed
1232  * effective for all test cases.
1233  *
1234  * Returns: a random number from the seeded random number generator.
1235  *
1236  * Since: 2.16
1237  */
1238 gint32
1239 g_test_rand_int (void)
1240 {
1241   return g_rand_int (test_run_rand);
1242 }
1243
1244 /**
1245  * g_test_rand_int_range:
1246  * @begin: the minimum value returned by this function
1247  * @end:   the smallest value not to be returned by this function
1248  *
1249  * Get a reproducible random integer number out of a specified range,
1250  * see g_test_rand_int() for details on test case random numbers.
1251  *
1252  * Returns: a number with @begin <= number < @end.
1253  * 
1254  * Since: 2.16
1255  */
1256 gint32
1257 g_test_rand_int_range (gint32          begin,
1258                        gint32          end)
1259 {
1260   return g_rand_int_range (test_run_rand, begin, end);
1261 }
1262
1263 /**
1264  * g_test_rand_double:
1265  *
1266  * Get a reproducible random floating point number,
1267  * see g_test_rand_int() for details on test case random numbers.
1268  *
1269  * Returns: a random number from the seeded random number generator.
1270  *
1271  * Since: 2.16
1272  */
1273 double
1274 g_test_rand_double (void)
1275 {
1276   return g_rand_double (test_run_rand);
1277 }
1278
1279 /**
1280  * g_test_rand_double_range:
1281  * @range_start: the minimum value returned by this function
1282  * @range_end: the minimum value not returned by this function
1283  *
1284  * Get a reproducible random floating pointer number out of a specified range,
1285  * see g_test_rand_int() for details on test case random numbers.
1286  *
1287  * Returns: a number with @range_start <= number < @range_end.
1288  *
1289  * Since: 2.16
1290  */
1291 double
1292 g_test_rand_double_range (double          range_start,
1293                           double          range_end)
1294 {
1295   return g_rand_double_range (test_run_rand, range_start, range_end);
1296 }
1297
1298 /**
1299  * g_test_timer_start:
1300  *
1301  * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1302  * to be done. Call this function again to restart the timer.
1303  *
1304  * Since: 2.16
1305  */
1306 void
1307 g_test_timer_start (void)
1308 {
1309   if (!test_user_timer)
1310     test_user_timer = g_timer_new();
1311   test_user_stamp = 0;
1312   g_timer_start (test_user_timer);
1313 }
1314
1315 /**
1316  * g_test_timer_elapsed:
1317  *
1318  * Get the time since the last start of the timer with g_test_timer_start().
1319  *
1320  * Returns: the time since the last start of the timer, as a double
1321  *
1322  * Since: 2.16
1323  */
1324 double
1325 g_test_timer_elapsed (void)
1326 {
1327   test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1328   return test_user_stamp;
1329 }
1330
1331 /**
1332  * g_test_timer_last:
1333  *
1334  * Report the last result of g_test_timer_elapsed().
1335  *
1336  * Returns: the last result of g_test_timer_elapsed(), as a double
1337  *
1338  * Since: 2.16
1339  */
1340 double
1341 g_test_timer_last (void)
1342 {
1343   return test_user_stamp;
1344 }
1345
1346 /**
1347  * g_test_minimized_result:
1348  * @minimized_quantity: the reported value
1349  * @format: the format string of the report message
1350  * @...: arguments to pass to the printf() function
1351  *
1352  * Report the result of a performance or measurement test.
1353  * The test should generally strive to minimize the reported
1354  * quantities (smaller values are better than larger ones),
1355  * this and @minimized_quantity can determine sorting
1356  * order for test result reports.
1357  *
1358  * Since: 2.16
1359  */
1360 void
1361 g_test_minimized_result (double          minimized_quantity,
1362                          const char     *format,
1363                          ...)
1364 {
1365   long double largs = minimized_quantity;
1366   gchar *buffer;
1367   va_list args;
1368
1369   va_start (args, format);
1370   buffer = g_strdup_vprintf (format, args);
1371   va_end (args);
1372
1373   g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1374   g_free (buffer);
1375 }
1376
1377 /**
1378  * g_test_maximized_result:
1379  * @maximized_quantity: the reported value
1380  * @format: the format string of the report message
1381  * @...: arguments to pass to the printf() function
1382  *
1383  * Report the result of a performance or measurement test.
1384  * The test should generally strive to maximize the reported
1385  * quantities (larger values are better than smaller ones),
1386  * this and @maximized_quantity can determine sorting
1387  * order for test result reports.
1388  *
1389  * Since: 2.16
1390  */
1391 void
1392 g_test_maximized_result (double          maximized_quantity,
1393                          const char     *format,
1394                          ...)
1395 {
1396   long double largs = maximized_quantity;
1397   gchar *buffer;
1398   va_list args;
1399
1400   va_start (args, format);
1401   buffer = g_strdup_vprintf (format, args);
1402   va_end (args);
1403
1404   g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1405   g_free (buffer);
1406 }
1407
1408 /**
1409  * g_test_message:
1410  * @format: the format string
1411  * @...:    printf-like arguments to @format
1412  *
1413  * Add a message to the test report.
1414  *
1415  * Since: 2.16
1416  */
1417 void
1418 g_test_message (const char *format,
1419                 ...)
1420 {
1421   gchar *buffer;
1422   va_list args;
1423
1424   va_start (args, format);
1425   buffer = g_strdup_vprintf (format, args);
1426   va_end (args);
1427
1428   g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1429   g_free (buffer);
1430 }
1431
1432 /**
1433  * g_test_bug_base:
1434  * @uri_pattern: the base pattern for bug URIs
1435  *
1436  * Specify the base URI for bug reports.
1437  *
1438  * The base URI is used to construct bug report messages for
1439  * g_test_message() when g_test_bug() is called.
1440  * Calling this function outside of a test case sets the
1441  * default base URI for all test cases. Calling it from within
1442  * a test case changes the base URI for the scope of the test
1443  * case only.
1444  * Bug URIs are constructed by appending a bug specific URI
1445  * portion to @uri_pattern, or by replacing the special string
1446  * '\%s' within @uri_pattern if that is present.
1447  *
1448  * Since: 2.16
1449  */
1450 void
1451 g_test_bug_base (const char *uri_pattern)
1452 {
1453   g_free (test_uri_base);
1454   test_uri_base = g_strdup (uri_pattern);
1455 }
1456
1457 /**
1458  * g_test_bug:
1459  * @bug_uri_snippet: Bug specific bug tracker URI portion.
1460  *
1461  * This function adds a message to test reports that
1462  * associates a bug URI with a test case.
1463  * Bug URIs are constructed from a base URI set with g_test_bug_base()
1464  * and @bug_uri_snippet.
1465  *
1466  * Since: 2.16
1467  */
1468 void
1469 g_test_bug (const char *bug_uri_snippet)
1470 {
1471   char *c;
1472
1473   g_return_if_fail (test_uri_base != NULL);
1474   g_return_if_fail (bug_uri_snippet != NULL);
1475
1476   c = strstr (test_uri_base, "%s");
1477   if (c)
1478     {
1479       char *b = g_strndup (test_uri_base, c - test_uri_base);
1480       char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1481       g_free (b);
1482       g_test_message ("Bug Reference: %s", s);
1483       g_free (s);
1484     }
1485   else
1486     g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1487 }
1488
1489 /**
1490  * g_test_get_root:
1491  *
1492  * Get the toplevel test suite for the test path API.
1493  *
1494  * Returns: the toplevel #GTestSuite
1495  *
1496  * Since: 2.16
1497  */
1498 GTestSuite*
1499 g_test_get_root (void)
1500 {
1501   if (!test_suite_root)
1502     {
1503       test_suite_root = g_test_create_suite ("root");
1504       g_free (test_suite_root->name);
1505       test_suite_root->name = g_strdup ("");
1506     }
1507
1508   return test_suite_root;
1509 }
1510
1511 /**
1512  * g_test_run:
1513  *
1514  * Runs all tests under the toplevel suite which can be retrieved
1515  * with g_test_get_root(). Similar to g_test_run_suite(), the test
1516  * cases to be run are filtered according to
1517  * test path arguments (-p <replaceable>testpath</replaceable>) as 
1518  * parsed by g_test_init().
1519  * g_test_run_suite() or g_test_run() may only be called once
1520  * in a program.
1521  *
1522  * In general, the tests and sub-suites within each suite are run in
1523  * the order in which they are defined. However, note that prior to
1524  * GLib 2.36, there was a bug in the <literal>g_test_add_*</literal>
1525  * functions which caused them to create multiple suites with the same
1526  * name, meaning that if you created tests "/foo/simple",
1527  * "/bar/simple", and "/foo/using-bar" in that order, they would get
1528  * run in that order (since g_test_run() would run the first "/foo"
1529  * suite, then the "/bar" suite, then the second "/foo" suite). As of
1530  * 2.36, this bug is fixed, and adding the tests in that order would
1531  * result in a running order of "/foo/simple", "/foo/using-bar",
1532  * "/bar/simple". If this new ordering is sub-optimal (because it puts
1533  * more-complicated tests before simpler ones, making it harder to
1534  * figure out exactly what has failed), you can fix it by changing the
1535  * test paths to group tests by suite in a way that will result in the
1536  * desired running order. Eg, "/simple/foo", "/simple/bar",
1537  * "/complex/foo-using-bar".
1538  *
1539  * However, you should never make the actual result of a test depend
1540  * on the order that tests are run in. If you need to ensure that some
1541  * particular code runs before or after a given test case, use
1542  * g_test_add(), which lets you specify setup and teardown functions.
1543  *
1544  * Returns: 0 on success, 1 on failure (assuming it returns at all),
1545  *   77 if all tests were skipped with g_test_skip().
1546  *
1547  * Since: 2.16
1548  */
1549 int
1550 g_test_run (void)
1551 {
1552   if (g_test_run_suite (g_test_get_root()) != 0)
1553     return 1;
1554
1555   if (test_run_count > 0 && test_run_count == test_skipped_count)
1556     return 77;
1557   else
1558     return 0;
1559 }
1560
1561 /**
1562  * g_test_create_case:
1563  * @test_name:     the name for the test case
1564  * @data_size:     the size of the fixture data structure
1565  * @test_data:     test data argument for the test functions
1566  * @data_setup:    the function to set up the fixture data
1567  * @data_test:     the actual test function
1568  * @data_teardown: the function to teardown the fixture data
1569  *
1570  * Create a new #GTestCase, named @test_name, this API is fairly
1571  * low level, calling g_test_add() or g_test_add_func() is preferable.
1572  * When this test is executed, a fixture structure of size @data_size
1573  * will be allocated and filled with 0s. Then @data_setup is called
1574  * to initialize the fixture. After fixture setup, the actual test
1575  * function @data_test is called. Once the test run completed, the
1576  * fixture structure is torn down  by calling @data_teardown and
1577  * after that the memory is released.
1578  *
1579  * Splitting up a test run into fixture setup, test function and
1580  * fixture teardown is most usful if the same fixture is used for
1581  * multiple tests. In this cases, g_test_create_case() will be
1582  * called with the same fixture, but varying @test_name and
1583  * @data_test arguments.
1584  *
1585  * Returns: a newly allocated #GTestCase.
1586  *
1587  * Since: 2.16
1588  */
1589 GTestCase*
1590 g_test_create_case (const char       *test_name,
1591                     gsize             data_size,
1592                     gconstpointer     test_data,
1593                     GTestFixtureFunc  data_setup,
1594                     GTestFixtureFunc  data_test,
1595                     GTestFixtureFunc  data_teardown)
1596 {
1597   GTestCase *tc;
1598
1599   g_return_val_if_fail (test_name != NULL, NULL);
1600   g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1601   g_return_val_if_fail (test_name[0] != 0, NULL);
1602   g_return_val_if_fail (data_test != NULL, NULL);
1603
1604   tc = g_slice_new0 (GTestCase);
1605   tc->name = g_strdup (test_name);
1606   tc->test_data = (gpointer) test_data;
1607   tc->fixture_size = data_size;
1608   tc->fixture_setup = (void*) data_setup;
1609   tc->fixture_test = (void*) data_test;
1610   tc->fixture_teardown = (void*) data_teardown;
1611
1612   return tc;
1613 }
1614
1615 static gint
1616 find_suite (gconstpointer l, gconstpointer s)
1617 {
1618   const GTestSuite *suite = l;
1619   const gchar *str = s;
1620
1621   return strcmp (suite->name, str);
1622 }
1623
1624 /**
1625  * GTestFixtureFunc:
1626  * @fixture: the test fixture
1627  * @user_data: the data provided when registering the test
1628  *
1629  * The type used for functions that operate on test fixtures.  This is
1630  * used for the fixture setup and teardown functions as well as for the
1631  * testcases themselves.
1632  *
1633  * @user_data is a pointer to the data that was given when registering
1634  * the test case.
1635  *
1636  * @fixture will be a pointer to the area of memory allocated by the
1637  * test framework, of the size requested.  If the requested size was
1638  * zero then @fixture will be equal to @user_data.
1639  *
1640  * Since: 2.28
1641  */
1642 void
1643 g_test_add_vtable (const char       *testpath,
1644                    gsize             data_size,
1645                    gconstpointer     test_data,
1646                    GTestFixtureFunc  data_setup,
1647                    GTestFixtureFunc  fixture_test_func,
1648                    GTestFixtureFunc  data_teardown)
1649 {
1650   gchar **segments;
1651   guint ui;
1652   GTestSuite *suite;
1653
1654   g_return_if_fail (testpath != NULL);
1655   g_return_if_fail (g_path_is_absolute (testpath));
1656   g_return_if_fail (fixture_test_func != NULL);
1657
1658   if (g_slist_find_custom (test_paths_skipped, testpath, (GCompareFunc)g_strcmp0))
1659     return;
1660
1661   suite = g_test_get_root();
1662   segments = g_strsplit (testpath, "/", -1);
1663   for (ui = 0; segments[ui] != NULL; ui++)
1664     {
1665       const char *seg = segments[ui];
1666       gboolean islast = segments[ui + 1] == NULL;
1667       if (islast && !seg[0])
1668         g_error ("invalid test case path: %s", testpath);
1669       else if (!seg[0])
1670         continue;       /* initial or duplicate slash */
1671       else if (!islast)
1672         {
1673           GSList *l;
1674           GTestSuite *csuite;
1675           l = g_slist_find_custom (suite->suites, seg, find_suite);
1676           if (l)
1677             {
1678               csuite = l->data;
1679             }
1680           else
1681             {
1682               csuite = g_test_create_suite (seg);
1683               g_test_suite_add_suite (suite, csuite);
1684             }
1685           suite = csuite;
1686         }
1687       else /* islast */
1688         {
1689           GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1690           g_test_suite_add (suite, tc);
1691         }
1692     }
1693   g_strfreev (segments);
1694 }
1695
1696 /**
1697  * g_test_fail:
1698  *
1699  * Indicates that a test failed. This function can be called
1700  * multiple times from the same test. You can use this function
1701  * if your test failed in a recoverable way.
1702  * 
1703  * Do not use this function if the failure of a test could cause
1704  * other tests to malfunction.
1705  *
1706  * Calling this function will not stop the test from running, you
1707  * need to return from the test function yourself. So you can
1708  * produce additional diagnostic messages or even continue running
1709  * the test.
1710  *
1711  * If not called from inside a test, this function does nothing.
1712  *
1713  * Since: 2.30
1714  **/
1715 void
1716 g_test_fail (void)
1717 {
1718   test_run_success = G_TEST_RUN_FAILURE;
1719 }
1720
1721 /**
1722  * g_test_incomplete:
1723  * @msg: (allow-none): explanation
1724  *
1725  * Indicates that a test failed because of some incomplete
1726  * functionality. This function can be called multiple times
1727  * from the same test.
1728  *
1729  * Calling this function will not stop the test from running, you
1730  * need to return from the test function yourself. So you can
1731  * produce additional diagnostic messages or even continue running
1732  * the test.
1733  *
1734  * If not called from inside a test, this function does nothing.
1735  *
1736  * Since: 2.38
1737  */
1738 void
1739 g_test_incomplete (const gchar *msg)
1740 {
1741   test_run_success = G_TEST_RUN_INCOMPLETE;
1742   g_free (test_run_msg);
1743   test_run_msg = g_strdup (msg);
1744 }
1745
1746 /**
1747  * g_test_skip:
1748  * @msg: (allow-none): explanation
1749  *
1750  * Indicates that a test was skipped.
1751  *
1752  * Calling this function will not stop the test from running, you
1753  * need to return from the test function yourself. So you can
1754  * produce additional diagnostic messages or even continue running
1755  * the test.
1756  *
1757  * If not called from inside a test, this function does nothing.
1758  *
1759  * Since: 2.38
1760  */
1761 void
1762 g_test_skip (const gchar *msg)
1763 {
1764   test_run_success = G_TEST_RUN_SKIPPED;
1765   g_free (test_run_msg);
1766   test_run_msg = g_strdup (msg);
1767 }
1768
1769 /**
1770  * g_test_failed:
1771  *
1772  * Returns whether a test has already failed. This will
1773  * be the case when g_test_fail(), g_test_incomplete()
1774  * or g_test_skip() have been called, but also if an
1775  * assertion has failed.
1776  *
1777  * This can be useful to return early from a test if
1778  * continuing after a failed assertion might be harmful.
1779  *
1780  * The return value of this function is only meaningful
1781  * if it is called from inside a test function.
1782  *
1783  * Returns: %TRUE if the test has failed
1784  *
1785  * Since: 2.38
1786  */
1787 gboolean
1788 g_test_failed (void)
1789 {
1790   return test_run_success != G_TEST_RUN_SUCCESS;
1791 }
1792
1793 /**
1794  * g_test_set_nonfatal_assertions:
1795  *
1796  * Changes the behaviour of g_assert_cmpstr(), g_assert_cmpint(),
1797  * g_assert_cmpuint(), g_assert_cmphex(), g_assert_cmpfloat(),
1798  * g_assert_true(), g_assert_false(), g_assert_null(), g_assert_no_error(),
1799  * g_assert_error(), g_test_assert_expected_messages() and the various
1800  * g_test_trap_assert_*() macros to not abort to program, but instead
1801  * call g_test_fail() and continue. (This also changes the behavior of
1802  * g_test_fail() so that it will not cause the test program to abort
1803  * after completing the failed test.)
1804  *
1805  * Note that the g_assert_not_reached() and g_assert() are not
1806  * affected by this.
1807  *
1808  * This function can only be called after g_test_init().
1809  *
1810  * Since: 2.38
1811  */
1812 void
1813 g_test_set_nonfatal_assertions (void)
1814 {
1815   if (!g_test_config_vars->test_initialized)
1816     g_error ("g_test_set_nonfatal_assertions called without g_test_init");
1817   test_nonfatal_assertions = TRUE;
1818   test_mode_fatal = FALSE;
1819 }
1820
1821 /**
1822  * GTestFunc:
1823  *
1824  * The type used for test case functions.
1825  *
1826  * Since: 2.28
1827  */
1828
1829 /**
1830  * g_test_add_func:
1831  * @testpath:   /-separated test case path name for the test.
1832  * @test_func:  The test function to invoke for this test.
1833  *
1834  * Create a new test case, similar to g_test_create_case(). However
1835  * the test is assumed to use no fixture, and test suites are automatically
1836  * created on the fly and added to the root fixture, based on the
1837  * slash-separated portions of @testpath.
1838  *
1839  * If @testpath includes the component "subprocess" anywhere in it,
1840  * the test will be skipped by default, and only run if explicitly
1841  * required via the <option>-p</option> command-line option or
1842  * g_test_trap_subprocess().
1843  *
1844  * Since: 2.16
1845  */
1846 void
1847 g_test_add_func (const char *testpath,
1848                  GTestFunc   test_func)
1849 {
1850   g_return_if_fail (testpath != NULL);
1851   g_return_if_fail (testpath[0] == '/');
1852   g_return_if_fail (test_func != NULL);
1853   g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1854 }
1855
1856 /**
1857  * GTestDataFunc:
1858  * @user_data: the data provided when registering the test
1859  *
1860  * The type used for test case functions that take an extra pointer
1861  * argument.
1862  *
1863  * Since: 2.28
1864  */
1865
1866 /**
1867  * g_test_add_data_func:
1868  * @testpath:   /-separated test case path name for the test.
1869  * @test_data:  Test data argument for the test function.
1870  * @test_func:  The test function to invoke for this test.
1871  *
1872  * Create a new test case, similar to g_test_create_case(). However
1873  * the test is assumed to use no fixture, and test suites are automatically
1874  * created on the fly and added to the root fixture, based on the
1875  * slash-separated portions of @testpath. The @test_data argument
1876  * will be passed as first argument to @test_func.
1877  *
1878  * If @testpath includes the component "subprocess" anywhere in it,
1879  * the test will be skipped by default, and only run if explicitly
1880  * required via the <option>-p</option> command-line option or
1881  * g_test_trap_subprocess().
1882  *
1883  * Since: 2.16
1884  */
1885 void
1886 g_test_add_data_func (const char     *testpath,
1887                       gconstpointer   test_data,
1888                       GTestDataFunc   test_func)
1889 {
1890   g_return_if_fail (testpath != NULL);
1891   g_return_if_fail (testpath[0] == '/');
1892   g_return_if_fail (test_func != NULL);
1893
1894   g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1895 }
1896
1897 /**
1898  * g_test_add_data_func_full:
1899  * @testpath: /-separated test case path name for the test.
1900  * @test_data: Test data argument for the test function.
1901  * @test_func: The test function to invoke for this test.
1902  * @data_free_func: #GDestroyNotify for @test_data.
1903  *
1904  * Create a new test case, as with g_test_add_data_func(), but freeing
1905  * @test_data after the test run is complete.
1906  *
1907  * Since: 2.34
1908  */
1909 void
1910 g_test_add_data_func_full (const char     *testpath,
1911                            gpointer        test_data,
1912                            GTestDataFunc   test_func,
1913                            GDestroyNotify  data_free_func)
1914 {
1915   g_return_if_fail (testpath != NULL);
1916   g_return_if_fail (testpath[0] == '/');
1917   g_return_if_fail (test_func != NULL);
1918
1919   g_test_add_vtable (testpath, 0, test_data, NULL,
1920                      (GTestFixtureFunc) test_func,
1921                      (GTestFixtureFunc) data_free_func);
1922 }
1923
1924 static gboolean
1925 g_test_suite_case_exists (GTestSuite *suite,
1926                           const char *test_path)
1927 {
1928   GSList *iter;
1929   char *slash;
1930   GTestCase *tc;
1931
1932   test_path++;
1933   slash = strchr (test_path, '/');
1934
1935   if (slash)
1936     {
1937       for (iter = suite->suites; iter; iter = iter->next)
1938         {
1939           GTestSuite *child_suite = iter->data;
1940
1941           if (!strncmp (child_suite->name, test_path, slash - test_path))
1942             if (g_test_suite_case_exists (child_suite, slash))
1943               return TRUE;
1944         }
1945     }
1946   else
1947     {
1948       for (iter = suite->cases; iter; iter = iter->next)
1949         {
1950           tc = iter->data;
1951           if (!strcmp (tc->name, test_path))
1952             return TRUE;
1953         }
1954     }
1955
1956   return FALSE;
1957 }
1958
1959 /**
1960  * g_test_create_suite:
1961  * @suite_name: a name for the suite
1962  *
1963  * Create a new test suite with the name @suite_name.
1964  *
1965  * Returns: A newly allocated #GTestSuite instance.
1966  *
1967  * Since: 2.16
1968  */
1969 GTestSuite*
1970 g_test_create_suite (const char *suite_name)
1971 {
1972   GTestSuite *ts;
1973   g_return_val_if_fail (suite_name != NULL, NULL);
1974   g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1975   g_return_val_if_fail (suite_name[0] != 0, NULL);
1976   ts = g_slice_new0 (GTestSuite);
1977   ts->name = g_strdup (suite_name);
1978   return ts;
1979 }
1980
1981 /**
1982  * g_test_suite_add:
1983  * @suite: a #GTestSuite
1984  * @test_case: a #GTestCase
1985  *
1986  * Adds @test_case to @suite.
1987  *
1988  * Since: 2.16
1989  */
1990 void
1991 g_test_suite_add (GTestSuite     *suite,
1992                   GTestCase      *test_case)
1993 {
1994   g_return_if_fail (suite != NULL);
1995   g_return_if_fail (test_case != NULL);
1996
1997   suite->cases = g_slist_prepend (suite->cases, test_case);
1998 }
1999
2000 /**
2001  * g_test_suite_add_suite:
2002  * @suite:       a #GTestSuite
2003  * @nestedsuite: another #GTestSuite
2004  *
2005  * Adds @nestedsuite to @suite.
2006  *
2007  * Since: 2.16
2008  */
2009 void
2010 g_test_suite_add_suite (GTestSuite     *suite,
2011                         GTestSuite     *nestedsuite)
2012 {
2013   g_return_if_fail (suite != NULL);
2014   g_return_if_fail (nestedsuite != NULL);
2015
2016   suite->suites = g_slist_prepend (suite->suites, nestedsuite);
2017 }
2018
2019 /**
2020  * g_test_queue_free:
2021  * @gfree_pointer: the pointer to be stored.
2022  *
2023  * Enqueue a pointer to be released with g_free() during the next
2024  * teardown phase. This is equivalent to calling g_test_queue_destroy()
2025  * with a destroy callback of g_free().
2026  *
2027  * Since: 2.16
2028  */
2029 void
2030 g_test_queue_free (gpointer gfree_pointer)
2031 {
2032   if (gfree_pointer)
2033     g_test_queue_destroy (g_free, gfree_pointer);
2034 }
2035
2036 /**
2037  * g_test_queue_destroy:
2038  * @destroy_func:       Destroy callback for teardown phase.
2039  * @destroy_data:       Destroy callback data.
2040  *
2041  * This function enqueus a callback @destroy_func to be executed
2042  * during the next test case teardown phase. This is most useful
2043  * to auto destruct allocted test resources at the end of a test run.
2044  * Resources are released in reverse queue order, that means enqueueing
2045  * callback A before callback B will cause B() to be called before
2046  * A() during teardown.
2047  *
2048  * Since: 2.16
2049  */
2050 void
2051 g_test_queue_destroy (GDestroyNotify destroy_func,
2052                       gpointer       destroy_data)
2053 {
2054   DestroyEntry *dentry;
2055
2056   g_return_if_fail (destroy_func != NULL);
2057
2058   dentry = g_slice_new0 (DestroyEntry);
2059   dentry->destroy_func = destroy_func;
2060   dentry->destroy_data = destroy_data;
2061   dentry->next = test_destroy_queue;
2062   test_destroy_queue = dentry;
2063 }
2064
2065 static gboolean
2066 test_case_run (GTestCase *tc)
2067 {
2068   gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
2069   GSList **old_free_list, *filename_free_list = NULL;
2070   gboolean success = G_TEST_RUN_SUCCESS;
2071
2072   old_free_list = test_filename_free_list;
2073   test_filename_free_list = &filename_free_list;
2074
2075   test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
2076   if (strstr (test_run_name, "/subprocess"))
2077     {
2078       GSList *iter;
2079       gboolean found = FALSE;
2080
2081       for (iter = test_paths; iter; iter = iter->next)
2082         {
2083           if (!strcmp (test_run_name, iter->data))
2084             {
2085               found = TRUE;
2086               break;
2087             }
2088         }
2089
2090       if (!found)
2091         {
2092           if (g_test_verbose ())
2093             g_print ("GTest: skipping: %s\n", test_run_name);
2094           goto out;
2095         }
2096     }
2097
2098   if (++test_run_count <= test_startup_skip_count)
2099     g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
2100   else if (test_run_list)
2101     {
2102       g_print ("%s\n", test_run_name);
2103       g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
2104     }
2105   else
2106     {
2107       GTimer *test_run_timer = g_timer_new();
2108       long double largs[3];
2109       void *fixture;
2110       g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
2111       test_run_forks = 0;
2112       test_run_success = G_TEST_RUN_SUCCESS;
2113       g_clear_pointer (&test_run_msg, g_free);
2114       g_test_log_set_fatal_handler (NULL, NULL);
2115       g_timer_start (test_run_timer);
2116       fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
2117       test_run_seed (test_run_seedstr);
2118       if (tc->fixture_setup)
2119         tc->fixture_setup (fixture, tc->test_data);
2120       tc->fixture_test (fixture, tc->test_data);
2121       test_trap_clear();
2122       while (test_destroy_queue)
2123         {
2124           DestroyEntry *dentry = test_destroy_queue;
2125           test_destroy_queue = dentry->next;
2126           dentry->destroy_func (dentry->destroy_data);
2127           g_slice_free (DestroyEntry, dentry);
2128         }
2129       if (tc->fixture_teardown)
2130         tc->fixture_teardown (fixture, tc->test_data);
2131       if (tc->fixture_size)
2132         g_free (fixture);
2133       g_timer_stop (test_run_timer);
2134       success = test_run_success;
2135       test_run_success = G_TEST_RUN_FAILURE;
2136       largs[0] = success; /* OK */
2137       largs[1] = test_run_forks;
2138       largs[2] = g_timer_elapsed (test_run_timer, NULL);
2139       g_test_log (G_TEST_LOG_STOP_CASE, test_run_name, test_run_msg, G_N_ELEMENTS (largs), largs);
2140       g_clear_pointer (&test_run_msg, g_free);
2141       g_timer_destroy (test_run_timer);
2142     }
2143
2144  out:
2145   g_slist_free_full (filename_free_list, g_free);
2146   test_filename_free_list = old_free_list;
2147   g_free (test_run_name);
2148   test_run_name = old_name;
2149   g_free (test_uri_base);
2150   test_uri_base = old_base;
2151
2152   return (success == G_TEST_RUN_SUCCESS ||
2153           success == G_TEST_RUN_SKIPPED);
2154 }
2155
2156 static int
2157 g_test_run_suite_internal (GTestSuite *suite,
2158                            const char *path)
2159 {
2160   guint n_bad = 0, l;
2161   gchar *rest, *old_name = test_run_name;
2162   GSList *slist, *reversed;
2163
2164   g_return_val_if_fail (suite != NULL, -1);
2165
2166   g_test_log (G_TEST_LOG_START_SUITE, suite->name, NULL, 0, NULL);
2167
2168   while (path[0] == '/')
2169     path++;
2170   l = strlen (path);
2171   rest = strchr (path, '/');
2172   l = rest ? MIN (l, rest - path) : l;
2173   test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
2174   reversed = g_slist_reverse (g_slist_copy (suite->cases));
2175   for (slist = reversed; slist; slist = slist->next)
2176     {
2177       GTestCase *tc = slist->data;
2178       guint n = l ? strlen (tc->name) : 0;
2179       if (l == n && !rest && strncmp (path, tc->name, n) == 0)
2180         {
2181           if (!test_case_run (tc))
2182             n_bad++;
2183         }
2184     }
2185   g_slist_free (reversed);
2186   reversed = g_slist_reverse (g_slist_copy (suite->suites));
2187   for (slist = reversed; slist; slist = slist->next)
2188     {
2189       GTestSuite *ts = slist->data;
2190       guint n = l ? strlen (ts->name) : 0;
2191       if (l == n && strncmp (path, ts->name, n) == 0)
2192         n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
2193     }
2194   g_slist_free (reversed);
2195   g_free (test_run_name);
2196   test_run_name = old_name;
2197
2198   g_test_log (G_TEST_LOG_STOP_SUITE, suite->name, NULL, 0, NULL);
2199
2200   return n_bad;
2201 }
2202
2203 /**
2204  * g_test_run_suite:
2205  * @suite: a #GTestSuite
2206  *
2207  * Execute the tests within @suite and all nested #GTestSuites.
2208  * The test suites to be executed are filtered according to
2209  * test path arguments (-p <replaceable>testpath</replaceable>) 
2210  * as parsed by g_test_init(). See the g_test_run() documentation
2211  * for more information on the order that tests are run in.
2212  *
2213  * g_test_run_suite() or g_test_run() may only be called once
2214  * in a program.
2215  *
2216  * Returns: 0 on success
2217  *
2218  * Since: 2.16
2219  */
2220 int
2221 g_test_run_suite (GTestSuite *suite)
2222 {
2223   GSList *my_test_paths;
2224   guint n_bad = 0;
2225
2226   g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
2227   g_return_val_if_fail (g_test_run_once == TRUE, -1);
2228
2229   g_test_run_once = FALSE;
2230
2231   if (test_paths)
2232     my_test_paths = g_slist_copy (test_paths);
2233   else
2234     my_test_paths = g_slist_prepend (NULL, "");
2235
2236   while (my_test_paths)
2237     {
2238       const char *rest, *path = my_test_paths->data;
2239       guint l, n = strlen (suite->name);
2240       my_test_paths = g_slist_delete_link (my_test_paths, my_test_paths);
2241       while (path[0] == '/')
2242         path++;
2243       if (!n) /* root suite, run unconditionally */
2244         {
2245           n_bad += g_test_run_suite_internal (suite, path);
2246           continue;
2247         }
2248       /* regular suite, match path */
2249       rest = strchr (path, '/');
2250       l = strlen (path);
2251       l = rest ? MIN (l, rest - path) : l;
2252       if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
2253         n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
2254     }
2255
2256   return n_bad;
2257 }
2258
2259 static void
2260 gtest_default_log_handler (const gchar    *log_domain,
2261                            GLogLevelFlags  log_level,
2262                            const gchar    *message,
2263                            gpointer        unused_data)
2264 {
2265   const gchar *strv[16];
2266   gboolean fatal = FALSE;
2267   gchar *msg;
2268   guint i = 0;
2269
2270   if (log_domain)
2271     {
2272       strv[i++] = log_domain;
2273       strv[i++] = "-";
2274     }
2275   if (log_level & G_LOG_FLAG_FATAL)
2276     {
2277       strv[i++] = "FATAL-";
2278       fatal = TRUE;
2279     }
2280   if (log_level & G_LOG_FLAG_RECURSION)
2281     strv[i++] = "RECURSIVE-";
2282   if (log_level & G_LOG_LEVEL_ERROR)
2283     strv[i++] = "ERROR";
2284   if (log_level & G_LOG_LEVEL_CRITICAL)
2285     strv[i++] = "CRITICAL";
2286   if (log_level & G_LOG_LEVEL_WARNING)
2287     strv[i++] = "WARNING";
2288   if (log_level & G_LOG_LEVEL_MESSAGE)
2289     strv[i++] = "MESSAGE";
2290   if (log_level & G_LOG_LEVEL_INFO)
2291     strv[i++] = "INFO";
2292   if (log_level & G_LOG_LEVEL_DEBUG)
2293     strv[i++] = "DEBUG";
2294   strv[i++] = ": ";
2295   strv[i++] = message;
2296   strv[i++] = NULL;
2297
2298   msg = g_strjoinv ("", (gchar**) strv);
2299   g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
2300   g_log_default_handler (log_domain, log_level, message, unused_data);
2301
2302   g_free (msg);
2303 }
2304
2305 void
2306 g_assertion_message (const char     *domain,
2307                      const char     *file,
2308                      int             line,
2309                      const char     *func,
2310                      const char     *message)
2311 {
2312   char lstr[32];
2313   char *s;
2314
2315   if (!message)
2316     message = "code should not be reached";
2317   g_snprintf (lstr, 32, "%d", line);
2318   s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
2319                    "ERROR:", file, ":", lstr, ":",
2320                    func, func[0] ? ":" : "",
2321                    " ", message, NULL);
2322   g_printerr ("**\n%s\n", s);
2323
2324   g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
2325
2326   if (test_nonfatal_assertions)
2327     {
2328       g_free (s);
2329       g_test_fail ();
2330       return;
2331     }
2332
2333   /* store assertion message in global variable, so that it can be found in a
2334    * core dump */
2335   if (__glib_assert_msg != NULL)
2336     /* free the old one */
2337     free (__glib_assert_msg);
2338   __glib_assert_msg = (char*) malloc (strlen (s) + 1);
2339   strcpy (__glib_assert_msg, s);
2340
2341   g_free (s);
2342
2343   if (test_in_subprocess)
2344     {
2345       /* If this is a test case subprocess then it probably hit this
2346        * assertion on purpose, so just exit() rather than abort()ing,
2347        * to avoid triggering any system crash-reporting daemon.
2348        */
2349       _exit (1);
2350     }
2351   else
2352     abort ();
2353 }
2354
2355 void
2356 g_assertion_message_expr (const char     *domain,
2357                           const char     *file,
2358                           int             line,
2359                           const char     *func,
2360                           const char     *expr)
2361 {
2362   char *s;
2363   if (!expr)
2364     s = g_strdup ("code should not be reached");
2365   else
2366     s = g_strconcat ("assertion failed: (", expr, ")", NULL);
2367   g_assertion_message (domain, file, line, func, s);
2368   g_free (s);
2369
2370   /* Normally g_assertion_message() won't return, but we need this for
2371    * when test_nonfatal_assertions is set, since
2372    * g_assertion_message_expr() is used for always-fatal assertions.
2373    */
2374   if (test_in_subprocess)
2375     _exit (1);
2376   else
2377     abort ();
2378 }
2379
2380 void
2381 g_assertion_message_cmpnum (const char     *domain,
2382                             const char     *file,
2383                             int             line,
2384                             const char     *func,
2385                             const char     *expr,
2386                             long double     arg1,
2387                             const char     *cmp,
2388                             long double     arg2,
2389                             char            numtype)
2390 {
2391   char *s = NULL;
2392
2393   switch (numtype)
2394     {
2395     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;
2396     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;
2397     case 'f':   s = g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr, (double) arg1, cmp, (double) arg2); break;
2398       /* ideally use: floats=%.7g double=%.17g */
2399     }
2400   g_assertion_message (domain, file, line, func, s);
2401   g_free (s);
2402 }
2403
2404 void
2405 g_assertion_message_cmpstr (const char     *domain,
2406                             const char     *file,
2407                             int             line,
2408                             const char     *func,
2409                             const char     *expr,
2410                             const char     *arg1,
2411                             const char     *cmp,
2412                             const char     *arg2)
2413 {
2414   char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
2415   a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
2416   a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
2417   g_free (t1);
2418   g_free (t2);
2419   s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
2420   g_free (a1);
2421   g_free (a2);
2422   g_assertion_message (domain, file, line, func, s);
2423   g_free (s);
2424 }
2425
2426 void
2427 g_assertion_message_error (const char     *domain,
2428                            const char     *file,
2429                            int             line,
2430                            const char     *func,
2431                            const char     *expr,
2432                            const GError   *error,
2433                            GQuark          error_domain,
2434                            int             error_code)
2435 {
2436   GString *gstring;
2437
2438   /* This is used by both g_assert_error() and g_assert_no_error(), so there
2439    * are three cases: expected an error but got the wrong error, expected
2440    * an error but got no error, and expected no error but got an error.
2441    */
2442
2443   gstring = g_string_new ("assertion failed ");
2444   if (error_domain)
2445       g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
2446                               g_quark_to_string (error_domain), error_code);
2447   else
2448     g_string_append_printf (gstring, "(%s == NULL): ", expr);
2449
2450   if (error)
2451       g_string_append_printf (gstring, "%s (%s, %d)", error->message,
2452                               g_quark_to_string (error->domain), error->code);
2453   else
2454     g_string_append_printf (gstring, "%s is NULL", expr);
2455
2456   g_assertion_message (domain, file, line, func, gstring->str);
2457   g_string_free (gstring, TRUE);
2458 }
2459
2460 /**
2461  * g_strcmp0:
2462  * @str1: (allow-none): a C string or %NULL
2463  * @str2: (allow-none): another C string or %NULL
2464  *
2465  * Compares @str1 and @str2 like strcmp(). Handles %NULL
2466  * gracefully by sorting it before non-%NULL strings.
2467  * Comparing two %NULL pointers returns 0.
2468  *
2469  * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
2470  *
2471  * Since: 2.16
2472  */
2473 int
2474 g_strcmp0 (const char     *str1,
2475            const char     *str2)
2476 {
2477   if (!str1)
2478     return -(str1 != str2);
2479   if (!str2)
2480     return str1 != str2;
2481   return strcmp (str1, str2);
2482 }
2483
2484 static void
2485 test_trap_clear (void)
2486 {
2487   test_trap_last_status = 0;
2488   test_trap_last_pid = 0;
2489   g_clear_pointer (&test_trap_last_subprocess, g_free);
2490   g_clear_pointer (&test_trap_last_stdout, g_free);
2491   g_clear_pointer (&test_trap_last_stderr, g_free);
2492 }
2493
2494 #ifdef G_OS_UNIX
2495
2496 static int
2497 sane_dup2 (int fd1,
2498            int fd2)
2499 {
2500   int ret;
2501   do
2502     ret = dup2 (fd1, fd2);
2503   while (ret < 0 && errno == EINTR);
2504   return ret;
2505 }
2506
2507 #endif
2508
2509 typedef struct {
2510   GPid pid;
2511   GMainLoop *loop;
2512   int child_status;
2513
2514   GIOChannel *stdout_io;
2515   gboolean echo_stdout;
2516   GString *stdout_str;
2517
2518   GIOChannel *stderr_io;
2519   gboolean echo_stderr;
2520   GString *stderr_str;
2521 } WaitForChildData;
2522
2523 static void
2524 check_complete (WaitForChildData *data)
2525 {
2526   if (data->child_status != -1 && data->stdout_io == NULL && data->stderr_io == NULL)
2527     g_main_loop_quit (data->loop);
2528 }
2529
2530 static void
2531 child_exited (GPid     pid,
2532               gint     status,
2533               gpointer user_data)
2534 {
2535   WaitForChildData *data = user_data;
2536
2537 #ifdef G_OS_UNIX
2538   if (WIFEXITED (status)) /* normal exit */
2539     data->child_status = WEXITSTATUS (status); /* 0..255 */
2540   else if (WIFSIGNALED (status) && WTERMSIG (status) == SIGALRM)
2541     data->child_status = G_TEST_STATUS_TIMED_OUT;
2542   else if (WIFSIGNALED (status))
2543     data->child_status = (WTERMSIG (status) << 12); /* signalled */
2544   else /* WCOREDUMP (status) */
2545     data->child_status = 512; /* coredump */
2546 #else
2547   data->child_status = status;
2548 #endif
2549
2550   check_complete (data);
2551 }
2552
2553 static gboolean
2554 child_timeout (gpointer user_data)
2555 {
2556   WaitForChildData *data = user_data;
2557
2558 #ifdef G_OS_WIN32
2559   TerminateProcess (data->pid, G_TEST_STATUS_TIMED_OUT);
2560 #else
2561   kill (data->pid, SIGALRM);
2562 #endif
2563
2564   return FALSE;
2565 }
2566
2567 static gboolean
2568 child_read (GIOChannel *io, GIOCondition cond, gpointer user_data)
2569 {
2570   WaitForChildData *data = user_data;
2571   GIOStatus status;
2572   gsize nread, nwrote, total;
2573   gchar buf[4096];
2574   FILE *echo_file = NULL;
2575
2576   status = g_io_channel_read_chars (io, buf, sizeof (buf), &nread, NULL);
2577   if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF)
2578     {
2579       // FIXME data->error = (status == G_IO_STATUS_ERROR);
2580       if (io == data->stdout_io)
2581         g_clear_pointer (&data->stdout_io, g_io_channel_unref);
2582       else
2583         g_clear_pointer (&data->stderr_io, g_io_channel_unref);
2584
2585       check_complete (data);
2586       return FALSE;
2587     }
2588   else if (status == G_IO_STATUS_AGAIN)
2589     return TRUE;
2590
2591   if (io == data->stdout_io)
2592     {
2593       g_string_append_len (data->stdout_str, buf, nread);
2594       if (data->echo_stdout)
2595         echo_file = stdout;
2596     }
2597   else
2598     {
2599       g_string_append_len (data->stderr_str, buf, nread);
2600       if (data->echo_stderr)
2601         echo_file = stderr;
2602     }
2603
2604   if (echo_file)
2605     {
2606       for (total = 0; total < nread; total += nwrote)
2607         {
2608           nwrote = fwrite (buf + total, 1, nread - total, echo_file);
2609           if (nwrote == 0)
2610             g_error ("write failed: %s", g_strerror (errno));
2611         }
2612     }
2613
2614   return TRUE;
2615 }
2616
2617 static void
2618 wait_for_child (GPid pid,
2619                 int stdout_fd, gboolean echo_stdout,
2620                 int stderr_fd, gboolean echo_stderr,
2621                 guint64 timeout)
2622 {
2623   WaitForChildData data;
2624   GMainContext *context;
2625   GSource *source;
2626
2627   data.pid = pid;
2628   data.child_status = -1;
2629
2630   context = g_main_context_new ();
2631   data.loop = g_main_loop_new (context, FALSE);
2632
2633   source = g_child_watch_source_new (pid);
2634   g_source_set_callback (source, (GSourceFunc) child_exited, &data, NULL);
2635   g_source_attach (source, context);
2636   g_source_unref (source);
2637
2638   data.echo_stdout = echo_stdout;
2639   data.stdout_str = g_string_new (NULL);
2640   data.stdout_io = g_io_channel_unix_new (stdout_fd);
2641   g_io_channel_set_close_on_unref (data.stdout_io, TRUE);
2642   g_io_channel_set_encoding (data.stdout_io, NULL, NULL);
2643   g_io_channel_set_buffered (data.stdout_io, FALSE);
2644   source = g_io_create_watch (data.stdout_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2645   g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2646   g_source_attach (source, context);
2647   g_source_unref (source);
2648
2649   data.echo_stderr = echo_stderr;
2650   data.stderr_str = g_string_new (NULL);
2651   data.stderr_io = g_io_channel_unix_new (stderr_fd);
2652   g_io_channel_set_close_on_unref (data.stderr_io, TRUE);
2653   g_io_channel_set_encoding (data.stderr_io, NULL, NULL);
2654   g_io_channel_set_buffered (data.stderr_io, FALSE);
2655   source = g_io_create_watch (data.stderr_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2656   g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2657   g_source_attach (source, context);
2658   g_source_unref (source);
2659
2660   if (timeout)
2661     {
2662       source = g_timeout_source_new (0);
2663       g_source_set_ready_time (source, g_get_monotonic_time () + timeout);
2664       g_source_set_callback (source, (GSourceFunc) child_timeout, &data, NULL);
2665       g_source_attach (source, context);
2666       g_source_unref (source);
2667     }
2668
2669   g_main_loop_run (data.loop);
2670   g_main_loop_unref (data.loop);
2671   g_main_context_unref (context);
2672
2673   test_trap_last_pid = pid;
2674   test_trap_last_status = data.child_status;
2675   test_trap_last_stdout = g_string_free (data.stdout_str, FALSE);
2676   test_trap_last_stderr = g_string_free (data.stderr_str, FALSE);
2677
2678   g_clear_pointer (&data.stdout_io, g_io_channel_unref);
2679   g_clear_pointer (&data.stderr_io, g_io_channel_unref);
2680 }
2681
2682 /**
2683  * g_test_trap_fork:
2684  * @usec_timeout:    Timeout for the forked test in micro seconds.
2685  * @test_trap_flags: Flags to modify forking behaviour.
2686  *
2687  * Fork the current test program to execute a test case that might
2688  * not return or that might abort.
2689  *
2690  * If @usec_timeout is non-0, the forked test case is aborted and
2691  * considered failing if its run time exceeds it.
2692  *
2693  * The forking behavior can be configured with the #GTestTrapFlags flags.
2694  *
2695  * In the following example, the test code forks, the forked child
2696  * process produces some sample output and exits successfully.
2697  * The forking parent process then asserts successful child program
2698  * termination and validates child program outputs.
2699  *
2700  * |[
2701  *   static void
2702  *   test_fork_patterns (void)
2703  *   {
2704  *     if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2705  *       {
2706  *         g_print ("some stdout text: somagic17\n");
2707  *         g_printerr ("some stderr text: semagic43\n");
2708  *         exit (0); /&ast; successful test run &ast;/
2709  *       }
2710  *     g_test_trap_assert_passed ();
2711  *     g_test_trap_assert_stdout ("*somagic17*");
2712  *     g_test_trap_assert_stderr ("*semagic43*");
2713  *   }
2714  * ]|
2715  *
2716  * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2717  *
2718  * Since: 2.16
2719  *
2720  * Deprecated: This function is implemented only on Unix platforms,
2721  * and is not always reliable due to problems inherent in
2722  * fork-without-exec. Use g_test_trap_subprocess() instead.
2723  */
2724 gboolean
2725 g_test_trap_fork (guint64        usec_timeout,
2726                   GTestTrapFlags test_trap_flags)
2727 {
2728 #ifdef G_OS_UNIX
2729   int stdout_pipe[2] = { -1, -1 };
2730   int stderr_pipe[2] = { -1, -1 };
2731
2732   test_trap_clear();
2733   if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0)
2734     g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
2735   test_trap_last_pid = fork ();
2736   if (test_trap_last_pid < 0)
2737     g_error ("failed to fork test program: %s", g_strerror (errno));
2738   if (test_trap_last_pid == 0)  /* child */
2739     {
2740       int fd0 = -1;
2741       close (stdout_pipe[0]);
2742       close (stderr_pipe[0]);
2743       if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2744         fd0 = g_open ("/dev/null", O_RDONLY, 0);
2745       if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2746         g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
2747       if (fd0 >= 3)
2748         close (fd0);
2749       if (stdout_pipe[1] >= 3)
2750         close (stdout_pipe[1]);
2751       if (stderr_pipe[1] >= 3)
2752         close (stderr_pipe[1]);
2753       return TRUE;
2754     }
2755   else                          /* parent */
2756     {
2757       test_run_forks++;
2758       close (stdout_pipe[1]);
2759       close (stderr_pipe[1]);
2760
2761       wait_for_child (test_trap_last_pid,
2762                       stdout_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT),
2763                       stderr_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR),
2764                       usec_timeout);
2765       return FALSE;
2766     }
2767 #else
2768   g_message ("Not implemented: g_test_trap_fork");
2769
2770   return FALSE;
2771 #endif
2772 }
2773
2774 /**
2775  * g_test_trap_subprocess:
2776  * @test_path: (allow-none): Test to run in a subprocess
2777  * @usec_timeout: Timeout for the subprocess test in micro seconds.
2778  * @test_flags:   Flags to modify subprocess behaviour.
2779  *
2780  * Respawns the test program to run only @test_path in a subprocess.
2781  * This can be used for a test case that might not return, or that
2782  * might abort.
2783  *
2784  * If @test_path is %NULL then the same test is re-run in a subprocess.
2785  * You can use g_test_subprocess() to determine whether the test is in
2786  * a subprocess or not.
2787  *
2788  * @test_path can also be the name of the parent
2789  * test, followed by "<literal>/subprocess/</literal>" and then a name
2790  * for the specific subtest (or just ending with
2791  * "<literal>/subprocess</literal>" if the test only has one child
2792  * test); tests with names of this form will automatically be skipped
2793  * in the parent process.
2794  *
2795  * If @usec_timeout is non-0, the test subprocess is aborted and
2796  * considered failing if its run time exceeds it.
2797  *
2798  * The subprocess behavior can be configured with the
2799  * #GTestSubprocessFlags flags.
2800  *
2801  * You can use methods such as g_test_trap_assert_passed(),
2802  * g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to
2803  * check the results of the subprocess. (But note that
2804  * g_test_trap_assert_stdout() and g_test_trap_assert_stderr()
2805  * cannot be used if @test_flags specifies that the child should
2806  * inherit the parent stdout/stderr.) 
2807  *
2808  * If your <literal>main ()</literal> needs to behave differently in
2809  * the subprocess, you can call g_test_subprocess() (after calling
2810  * g_test_init()) to see whether you are in a subprocess.
2811  *
2812  * The following example tests that calling
2813  * <literal>my_object_new(1000000)</literal> will abort with an error
2814  * message.
2815  *
2816  * |[
2817  *   static void
2818  *   test_create_large_object_subprocess (void)
2819  *   {
2820  *     if (g_test_subprocess ())
2821  *       {
2822  *         my_object_new (1000000);
2823  *         return;
2824  *       }
2825  *
2826  *     /&ast; Reruns this same test in a subprocess &ast;/
2827  *     g_test_trap_subprocess (NULL, 0, 0);
2828  *     g_test_trap_assert_failed ();
2829  *     g_test_trap_assert_stderr ("*ERROR*too large*");
2830  *   }
2831  *
2832  *   int
2833  *   main (int argc, char **argv)
2834  *   {
2835  *     g_test_init (&argc, &argv, NULL);
2836  *
2837  *     g_test_add_func ("/myobject/create_large_object",
2838  *                      test_create_large_object);
2839  *     return g_test_run ();
2840  *   }
2841  * ]|
2842  *
2843  * Since: 2.38
2844  */
2845 void
2846 g_test_trap_subprocess (const char           *test_path,
2847                         guint64               usec_timeout,
2848                         GTestSubprocessFlags  test_flags)
2849 {
2850   GError *error = NULL;
2851   GPtrArray *argv;
2852   GSpawnFlags flags;
2853   int stdout_fd, stderr_fd;
2854   GPid pid;
2855
2856   /* Sanity check that they used GTestSubprocessFlags, not GTestTrapFlags */
2857   g_assert ((test_flags & (G_TEST_TRAP_INHERIT_STDIN | G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR)) == 0);
2858
2859   if (test_path)
2860     {
2861       if (!g_test_suite_case_exists (g_test_get_root (), test_path))
2862         g_error ("g_test_trap_subprocess: test does not exist: %s", test_path);
2863     }
2864   else
2865     {
2866       test_path = test_run_name;
2867     }
2868
2869   if (g_test_verbose ())
2870     g_print ("GTest: subprocess: %s\n", test_path);
2871
2872   test_trap_clear ();
2873   test_trap_last_subprocess = g_strdup (test_path);
2874
2875   argv = g_ptr_array_new ();
2876   g_ptr_array_add (argv, test_argv0);
2877   g_ptr_array_add (argv, "-q");
2878   g_ptr_array_add (argv, "-p");
2879   g_ptr_array_add (argv, (char *)test_path);
2880   g_ptr_array_add (argv, "--GTestSubprocess");
2881   if (test_log_fd != -1)
2882     {
2883       char log_fd_buf[128];
2884
2885       g_ptr_array_add (argv, "--GTestLogFD");
2886       g_snprintf (log_fd_buf, sizeof (log_fd_buf), "%d", test_log_fd);
2887       g_ptr_array_add (argv, log_fd_buf);
2888     }
2889   g_ptr_array_add (argv, NULL);
2890
2891   flags = G_SPAWN_DO_NOT_REAP_CHILD;
2892   if (test_flags & G_TEST_TRAP_INHERIT_STDIN)
2893     flags |= G_SPAWN_CHILD_INHERITS_STDIN;
2894
2895   if (!g_spawn_async_with_pipes (test_initial_cwd,
2896                                  (char **)argv->pdata,
2897                                  NULL, flags,
2898                                  NULL, NULL,
2899                                  &pid, NULL, &stdout_fd, &stderr_fd,
2900                                  &error))
2901     {
2902       g_error ("g_test_trap_subprocess() failed: %s\n",
2903                error->message);
2904     }
2905   g_ptr_array_free (argv, TRUE);
2906
2907   wait_for_child (pid,
2908                   stdout_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDOUT),
2909                   stderr_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDERR),
2910                   usec_timeout);
2911 }
2912
2913 /**
2914  * g_test_subprocess:
2915  *
2916  * Returns %TRUE (after g_test_init() has been called) if the test
2917  * program is running under g_test_trap_subprocess().
2918  *
2919  * Returns: %TRUE if the test program is running under
2920  * g_test_trap_subprocess().
2921  *
2922  * Since: 2.38
2923  */
2924 gboolean
2925 g_test_subprocess (void)
2926 {
2927   return test_in_subprocess;
2928 }
2929
2930 /**
2931  * g_test_trap_has_passed:
2932  *
2933  * Check the result of the last g_test_trap_subprocess() call.
2934  *
2935  * Returns: %TRUE if the last test subprocess terminated successfully.
2936  *
2937  * Since: 2.16
2938  */
2939 gboolean
2940 g_test_trap_has_passed (void)
2941 {
2942   return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
2943 }
2944
2945 /**
2946  * g_test_trap_reached_timeout:
2947  *
2948  * Check the result of the last g_test_trap_subprocess() call.
2949  *
2950  * Returns: %TRUE if the last test subprocess got killed due to a timeout.
2951  *
2952  * Since: 2.16
2953  */
2954 gboolean
2955 g_test_trap_reached_timeout (void)
2956 {
2957   return test_trap_last_status == G_TEST_STATUS_TIMED_OUT;
2958 }
2959
2960 void
2961 g_test_trap_assertions (const char     *domain,
2962                         const char     *file,
2963                         int             line,
2964                         const char     *func,
2965                         guint64         assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
2966                         const char     *pattern)
2967 {
2968   gboolean must_pass = assertion_flags == 0;
2969   gboolean must_fail = assertion_flags == 1;
2970   gboolean match_result = 0 == (assertion_flags & 1);
2971   const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
2972   const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
2973   const char *match_error = match_result ? "failed to match" : "contains invalid match";
2974   char *process_id;
2975
2976 #ifdef G_OS_UNIX
2977   if (test_trap_last_subprocess != NULL)
2978     {
2979       process_id = g_strdup_printf ("%s [%d]", test_trap_last_subprocess,
2980                                     test_trap_last_pid);
2981     }
2982   else if (test_trap_last_pid != 0)
2983     process_id = g_strdup_printf ("%d", test_trap_last_pid);
2984 #else
2985   if (test_trap_last_subprocess != NULL)
2986     process_id = g_strdup (test_trap_last_subprocess);
2987 #endif
2988   else
2989     g_error ("g_test_trap_ assertion with no trapped test");
2990
2991   if (must_pass && !g_test_trap_has_passed())
2992     {
2993       char *msg = g_strdup_printf ("child process (%s) failed unexpectedly", process_id);
2994       g_assertion_message (domain, file, line, func, msg);
2995       g_free (msg);
2996     }
2997   if (must_fail && g_test_trap_has_passed())
2998     {
2999       char *msg = g_strdup_printf ("child process (%s) did not fail as expected", process_id);
3000       g_assertion_message (domain, file, line, func, msg);
3001       g_free (msg);
3002     }
3003   if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
3004     {
3005       char *msg = g_strdup_printf ("stdout of child process (%s) %s: %s", process_id, match_error, stdout_pattern);
3006       g_assertion_message (domain, file, line, func, msg);
3007       g_free (msg);
3008     }
3009   if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
3010     {
3011       char *msg = g_strdup_printf ("stderr of child process (%s) %s: %s", process_id, match_error, stderr_pattern);
3012       g_assertion_message (domain, file, line, func, msg);
3013       g_free (msg);
3014     }
3015   g_free (process_id);
3016 }
3017
3018 static void
3019 gstring_overwrite_int (GString *gstring,
3020                        guint    pos,
3021                        guint32  vuint)
3022 {
3023   vuint = g_htonl (vuint);
3024   g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
3025 }
3026
3027 static void
3028 gstring_append_int (GString *gstring,
3029                     guint32  vuint)
3030 {
3031   vuint = g_htonl (vuint);
3032   g_string_append_len (gstring, (const gchar*) &vuint, 4);
3033 }
3034
3035 static void
3036 gstring_append_double (GString *gstring,
3037                        double   vdouble)
3038 {
3039   union { double vdouble; guint64 vuint64; } u;
3040   u.vdouble = vdouble;
3041   u.vuint64 = GUINT64_TO_BE (u.vuint64);
3042   g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
3043 }
3044
3045 static guint8*
3046 g_test_log_dump (GTestLogMsg *msg,
3047                  guint       *len)
3048 {
3049   GString *gstring = g_string_sized_new (1024);
3050   guint ui;
3051   gstring_append_int (gstring, 0);              /* message length */
3052   gstring_append_int (gstring, msg->log_type);
3053   gstring_append_int (gstring, msg->n_strings);
3054   gstring_append_int (gstring, msg->n_nums);
3055   gstring_append_int (gstring, 0);      /* reserved */
3056   for (ui = 0; ui < msg->n_strings; ui++)
3057     {
3058       guint l = strlen (msg->strings[ui]);
3059       gstring_append_int (gstring, l);
3060       g_string_append_len (gstring, msg->strings[ui], l);
3061     }
3062   for (ui = 0; ui < msg->n_nums; ui++)
3063     gstring_append_double (gstring, msg->nums[ui]);
3064   *len = gstring->len;
3065   gstring_overwrite_int (gstring, 0, *len);     /* message length */
3066   return (guint8*) g_string_free (gstring, FALSE);
3067 }
3068
3069 static inline long double
3070 net_double (const gchar **ipointer)
3071 {
3072   union { guint64 vuint64; double vdouble; } u;
3073   guint64 aligned_int64;
3074   memcpy (&aligned_int64, *ipointer, 8);
3075   *ipointer += 8;
3076   u.vuint64 = GUINT64_FROM_BE (aligned_int64);
3077   return u.vdouble;
3078 }
3079
3080 static inline guint32
3081 net_int (const gchar **ipointer)
3082 {
3083   guint32 aligned_int;
3084   memcpy (&aligned_int, *ipointer, 4);
3085   *ipointer += 4;
3086   return g_ntohl (aligned_int);
3087 }
3088
3089 static gboolean
3090 g_test_log_extract (GTestLogBuffer *tbuffer)
3091 {
3092   const gchar *p = tbuffer->data->str;
3093   GTestLogMsg msg;
3094   guint mlength;
3095   if (tbuffer->data->len < 4 * 5)
3096     return FALSE;
3097   mlength = net_int (&p);
3098   if (tbuffer->data->len < mlength)
3099     return FALSE;
3100   msg.log_type = net_int (&p);
3101   msg.n_strings = net_int (&p);
3102   msg.n_nums = net_int (&p);
3103   if (net_int (&p) == 0)
3104     {
3105       guint ui;
3106       msg.strings = g_new0 (gchar*, msg.n_strings + 1);
3107       msg.nums = g_new0 (long double, msg.n_nums);
3108       for (ui = 0; ui < msg.n_strings; ui++)
3109         {
3110           guint sl = net_int (&p);
3111           msg.strings[ui] = g_strndup (p, sl);
3112           p += sl;
3113         }
3114       for (ui = 0; ui < msg.n_nums; ui++)
3115         msg.nums[ui] = net_double (&p);
3116       if (p <= tbuffer->data->str + mlength)
3117         {
3118           g_string_erase (tbuffer->data, 0, mlength);
3119           tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
3120           return TRUE;
3121         }
3122     }
3123   g_free (msg.nums);
3124   g_strfreev (msg.strings);
3125   g_error ("corrupt log stream from test program");
3126   return FALSE;
3127 }
3128
3129 /**
3130  * g_test_log_buffer_new:
3131  *
3132  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3133  */
3134 GTestLogBuffer*
3135 g_test_log_buffer_new (void)
3136 {
3137   GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
3138   tb->data = g_string_sized_new (1024);
3139   return tb;
3140 }
3141
3142 /**
3143  * g_test_log_buffer_free:
3144  *
3145  * Internal function for gtester to free test log messages, no ABI guarantees provided.
3146  */
3147 void
3148 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
3149 {
3150   g_return_if_fail (tbuffer != NULL);
3151   while (tbuffer->msgs)
3152     g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
3153   g_string_free (tbuffer->data, TRUE);
3154   g_free (tbuffer);
3155 }
3156
3157 /**
3158  * g_test_log_buffer_push:
3159  *
3160  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3161  */
3162 void
3163 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
3164                         guint           n_bytes,
3165                         const guint8   *bytes)
3166 {
3167   g_return_if_fail (tbuffer != NULL);
3168   if (n_bytes)
3169     {
3170       gboolean more_messages;
3171       g_return_if_fail (bytes != NULL);
3172       g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
3173       do
3174         more_messages = g_test_log_extract (tbuffer);
3175       while (more_messages);
3176     }
3177 }
3178
3179 /**
3180  * g_test_log_buffer_pop:
3181  *
3182  * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
3183  */
3184 GTestLogMsg*
3185 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
3186 {
3187   GTestLogMsg *msg = NULL;
3188   g_return_val_if_fail (tbuffer != NULL, NULL);
3189   if (tbuffer->msgs)
3190     {
3191       GSList *slist = g_slist_last (tbuffer->msgs);
3192       msg = slist->data;
3193       tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
3194     }
3195   return msg;
3196 }
3197
3198 /**
3199  * g_test_log_msg_free:
3200  *
3201  * Internal function for gtester to free test log messages, no ABI guarantees provided.
3202  */
3203 void
3204 g_test_log_msg_free (GTestLogMsg *tmsg)
3205 {
3206   g_return_if_fail (tmsg != NULL);
3207   g_strfreev (tmsg->strings);
3208   g_free (tmsg->nums);
3209   g_free (tmsg);
3210 }
3211
3212 static gchar *
3213 g_test_build_filename_va (GTestFileType  file_type,
3214                           const gchar   *first_path,
3215                           va_list        ap)
3216 {
3217   const gchar *pathv[16];
3218   gint num_path_segments;
3219
3220   if (file_type == G_TEST_DIST)
3221     pathv[0] = test_disted_files_dir;
3222   else if (file_type == G_TEST_BUILT)
3223     pathv[0] = test_built_files_dir;
3224   else
3225     g_assert_not_reached ();
3226
3227   pathv[1] = first_path;
3228
3229   for (num_path_segments = 2; num_path_segments < G_N_ELEMENTS (pathv); num_path_segments++)
3230     {
3231       pathv[num_path_segments] = va_arg (ap, const char *);
3232       if (pathv[num_path_segments] == NULL)
3233         break;
3234     }
3235
3236   g_assert_cmpint (num_path_segments, <, G_N_ELEMENTS (pathv));
3237
3238   return g_build_filenamev ((gchar **) pathv);
3239 }
3240
3241 /**
3242  * g_test_build_filename:
3243  * @file_type: the type of file (built vs. distributed)
3244  * @first_path: the first segment of the pathname
3245  * @...: %NULL-terminated additional path segments
3246  *
3247  * Creates the pathname to a data file that is required for a test.
3248  *
3249  * This function is conceptually similar to g_build_filename() except
3250  * that the first argument has been replaced with a #GTestFileType
3251  * argument.
3252  *
3253  * The data file should either have been distributed with the module
3254  * containing the test (%G_TEST_DIST) or built as part of the build
3255  * system of that module (%G_TEST_BUILT).
3256  *
3257  * In order for this function to work in srcdir != builddir situations,
3258  * the G_TEST_SRCDIR and G_TEST_BUILDDIR environment variables need to
3259  * have been defined.  As of 2.38, this is done by the glib.mk
3260  * included in GLib.  Please ensure that your copy is up to date before
3261  * using this function.
3262  *
3263  * In case neither variable is set, this function will fall back to
3264  * using the dirname portion of argv[0], possibly removing ".libs".
3265  * This allows for casual running of tests directly from the commandline
3266  * in the srcdir == builddir case and should also support running of
3267  * installed tests, assuming the data files have been installed in the
3268  * same relative path as the test binary.
3269  *
3270  * Returns: the path of the file, to be freed using g_free()
3271  *
3272  * Since: 2.38
3273  **/
3274 /**
3275  * GTestFileType:
3276  * @G_TEST_DIST: a file that was included in the distribution tarball
3277  * @G_TEST_BUILT: a file that was built on the compiling machine
3278  *
3279  * The type of file to return the filename for, when used with
3280  * g_test_build_filename().
3281  *
3282  * These two options correspond rather directly to the 'dist' and
3283  * 'built' terminology that automake uses and are explicitly used to
3284  * distinguish between the 'srcdir' and 'builddir' being separate.  All
3285  * files in your project should either be dist (in the
3286  * <literal>DIST_EXTRA</literal> or <literal>dist_schema_DATA</literal>
3287  * sense, in which case they will always be in the srcdir) or built (in
3288  * the <literal>BUILT_SOURCES</literal> sense, in which case they will
3289  * always be in the builddir).
3290  *
3291  * Note: as a general rule of automake, files that are generated only as
3292  * part of the build-from-git process (but then are distributed with the
3293  * tarball) always go in srcdir (even if doing a srcdir != builddir
3294  * build from git) and are considered as distributed files.
3295  *
3296  * Since: 2.38
3297  **/
3298 gchar *
3299 g_test_build_filename (GTestFileType  file_type,
3300                        const gchar   *first_path,
3301                        ...)
3302 {
3303   gchar *result;
3304   va_list ap;
3305
3306   g_assert (g_test_initialized ());
3307
3308   va_start (ap, first_path);
3309   result = g_test_build_filename_va (file_type, first_path, ap);
3310   va_end (ap);
3311
3312   return result;
3313 }
3314
3315 /**
3316  * g_test_get_dir:
3317  * @file_type: the type of file (built vs. distributed)
3318  *
3319  * Gets the pathname of the directory containing test files of the type
3320  * specified by @file_type.
3321  *
3322  * This is approximately the same as calling g_test_build_filename("."),
3323  * but you don't need to free the return value.
3324  *
3325  * Returns: the path of the directory, owned by GLib
3326  *
3327  * Since: 2.38
3328  **/
3329 const gchar *
3330 g_test_get_dir (GTestFileType file_type)
3331 {
3332   g_assert (g_test_initialized ());
3333
3334   if (file_type == G_TEST_DIST)
3335     return test_disted_files_dir;
3336   else if (file_type == G_TEST_BUILT)
3337     return test_built_files_dir;
3338
3339   g_assert_not_reached ();
3340 }
3341
3342 /**
3343  * g_test_get_filename:
3344  * @file_type: the type of file (built vs. distributed)
3345  * @first_path: the first segment of the pathname
3346  * @...: %NULL-terminated additional path segments
3347  *
3348  * Gets the pathname to a data file that is required for a test.
3349  *
3350  * This is the same as g_test_build_filename() with two differences.
3351  * The first difference is that must only use this function from within
3352  * a testcase function.  The second difference is that you need not free
3353  * the return value -- it will be automatically freed when the testcase
3354  * finishes running.
3355  *
3356  * It is safe to use this function from a thread inside of a testcase
3357  * but you must ensure that all such uses occur before the main testcase
3358  * function returns (ie: it is best to ensure that all threads have been
3359  * joined).
3360  *
3361  * Returns: the path, automatically freed at the end of the testcase
3362  *
3363  * Since: 2.38
3364  **/
3365 const gchar *
3366 g_test_get_filename (GTestFileType  file_type,
3367                      const gchar   *first_path,
3368                      ...)
3369 {
3370   gchar *result;
3371   GSList *node;
3372   va_list ap;
3373
3374   g_assert (g_test_initialized ());
3375   if (test_filename_free_list == NULL)
3376     g_error ("g_test_get_filename() can only be used within testcase functions");
3377
3378   va_start (ap, first_path);
3379   result = g_test_build_filename_va (file_type, first_path, ap);
3380   va_end (ap);
3381
3382   node = g_slist_prepend (NULL, result);
3383   do
3384     node->next = *test_filename_free_list;
3385   while (!g_atomic_pointer_compare_and_exchange (test_filename_free_list, node->next, node));
3386
3387   return result;
3388 }
3389
3390 /* --- macros docs START --- */
3391 /**
3392  * g_test_add:
3393  * @testpath:  The test path for a new test case.
3394  * @Fixture:   The type of a fixture data structure.
3395  * @tdata:     Data argument for the test functions.
3396  * @fsetup:    The function to set up the fixture data.
3397  * @ftest:     The actual test function.
3398  * @fteardown: The function to tear down the fixture data.
3399  *
3400  * Hook up a new test case at @testpath, similar to g_test_add_func().
3401  * A fixture data structure with setup and teardown function may be provided
3402  * though, similar to g_test_create_case().
3403  * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
3404  * fteardown() callbacks can expect a @Fixture pointer as first argument in
3405  * a type safe manner.
3406  *
3407  * Since: 2.16
3408  **/
3409 /* --- macros docs END --- */