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