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