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