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