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