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