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