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