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