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