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