GTest: Improve --help output
[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   g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1514 }
1515
1516 /**
1517  * g_test_create_suite:
1518  * @suite_name: a name for the suite
1519  *
1520  * Create a new test suite with the name @suite_name.
1521  *
1522  * Returns: A newly allocated #GTestSuite instance.
1523  *
1524  * Since: 2.16
1525  */
1526 GTestSuite*
1527 g_test_create_suite (const char *suite_name)
1528 {
1529   GTestSuite *ts;
1530   g_return_val_if_fail (suite_name != NULL, NULL);
1531   g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1532   g_return_val_if_fail (suite_name[0] != 0, NULL);
1533   ts = g_slice_new0 (GTestSuite);
1534   ts->name = g_strdup (suite_name);
1535   return ts;
1536 }
1537
1538 /**
1539  * g_test_suite_add:
1540  * @suite: a #GTestSuite
1541  * @test_case: a #GTestCase
1542  *
1543  * Adds @test_case to @suite.
1544  *
1545  * Since: 2.16
1546  */
1547 void
1548 g_test_suite_add (GTestSuite     *suite,
1549                   GTestCase      *test_case)
1550 {
1551   g_return_if_fail (suite != NULL);
1552   g_return_if_fail (test_case != NULL);
1553
1554   suite->cases = g_slist_prepend (suite->cases, test_case);
1555 }
1556
1557 /**
1558  * g_test_suite_add_suite:
1559  * @suite:       a #GTestSuite
1560  * @nestedsuite: another #GTestSuite
1561  *
1562  * Adds @nestedsuite to @suite.
1563  *
1564  * Since: 2.16
1565  */
1566 void
1567 g_test_suite_add_suite (GTestSuite     *suite,
1568                         GTestSuite     *nestedsuite)
1569 {
1570   g_return_if_fail (suite != NULL);
1571   g_return_if_fail (nestedsuite != NULL);
1572
1573   suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1574 }
1575
1576 /**
1577  * g_test_queue_free:
1578  * @gfree_pointer: the pointer to be stored.
1579  *
1580  * Enqueue a pointer to be released with g_free() during the next
1581  * teardown phase. This is equivalent to calling g_test_queue_destroy()
1582  * with a destroy callback of g_free().
1583  *
1584  * Since: 2.16
1585  */
1586 void
1587 g_test_queue_free (gpointer gfree_pointer)
1588 {
1589   if (gfree_pointer)
1590     g_test_queue_destroy (g_free, gfree_pointer);
1591 }
1592
1593 /**
1594  * g_test_queue_destroy:
1595  * @destroy_func:       Destroy callback for teardown phase.
1596  * @destroy_data:       Destroy callback data.
1597  *
1598  * This function enqueus a callback @destroy_func to be executed
1599  * during the next test case teardown phase. This is most useful
1600  * to auto destruct allocted test resources at the end of a test run.
1601  * Resources are released in reverse queue order, that means enqueueing
1602  * callback A before callback B will cause B() to be called before
1603  * A() during teardown.
1604  *
1605  * Since: 2.16
1606  */
1607 void
1608 g_test_queue_destroy (GDestroyNotify destroy_func,
1609                       gpointer       destroy_data)
1610 {
1611   DestroyEntry *dentry;
1612
1613   g_return_if_fail (destroy_func != NULL);
1614
1615   dentry = g_slice_new0 (DestroyEntry);
1616   dentry->destroy_func = destroy_func;
1617   dentry->destroy_data = destroy_data;
1618   dentry->next = test_destroy_queue;
1619   test_destroy_queue = dentry;
1620 }
1621
1622 static gboolean
1623 test_case_run (GTestCase *tc)
1624 {
1625   gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1626   gboolean success = TRUE;
1627
1628   test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1629   if (++test_run_count <= test_skip_count)
1630     g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1631   else if (test_run_list)
1632     {
1633       g_print ("%s\n", test_run_name);
1634       g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1635     }
1636   else
1637     {
1638       GTimer *test_run_timer = g_timer_new();
1639       long double largs[3];
1640       void *fixture;
1641       g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1642       test_run_forks = 0;
1643       test_run_success = TRUE;
1644       g_test_log_set_fatal_handler (NULL, NULL);
1645       g_timer_start (test_run_timer);
1646       fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1647       test_run_seed (test_run_seedstr);
1648       if (tc->fixture_setup)
1649         tc->fixture_setup (fixture, tc->test_data);
1650       tc->fixture_test (fixture, tc->test_data);
1651       test_trap_clear();
1652       while (test_destroy_queue)
1653         {
1654           DestroyEntry *dentry = test_destroy_queue;
1655           test_destroy_queue = dentry->next;
1656           dentry->destroy_func (dentry->destroy_data);
1657           g_slice_free (DestroyEntry, dentry);
1658         }
1659       if (tc->fixture_teardown)
1660         tc->fixture_teardown (fixture, tc->test_data);
1661       if (tc->fixture_size)
1662         g_free (fixture);
1663       g_timer_stop (test_run_timer);
1664       success = test_run_success;
1665       test_run_success = FALSE;
1666       largs[0] = success ? 0 : 1; /* OK */
1667       largs[1] = test_run_forks;
1668       largs[2] = g_timer_elapsed (test_run_timer, NULL);
1669       g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1670       g_timer_destroy (test_run_timer);
1671     }
1672   g_free (test_run_name);
1673   test_run_name = old_name;
1674   g_free (test_uri_base);
1675   test_uri_base = old_base;
1676
1677   return success;
1678 }
1679
1680 static int
1681 g_test_run_suite_internal (GTestSuite *suite,
1682                            const char *path)
1683 {
1684   guint n_bad = 0, l;
1685   gchar *rest, *old_name = test_run_name;
1686   GSList *slist, *reversed;
1687
1688   g_return_val_if_fail (suite != NULL, -1);
1689
1690   while (path[0] == '/')
1691     path++;
1692   l = strlen (path);
1693   rest = strchr (path, '/');
1694   l = rest ? MIN (l, rest - path) : l;
1695   test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1696   reversed = g_slist_reverse (g_slist_copy (suite->cases));
1697   for (slist = reversed; slist; slist = slist->next)
1698     {
1699       GTestCase *tc = slist->data;
1700       guint n = l ? strlen (tc->name) : 0;
1701       if (l == n && strncmp (path, tc->name, n) == 0)
1702         {
1703           if (!test_case_run (tc))
1704             n_bad++;
1705         }
1706     }
1707   g_slist_free (reversed);
1708   reversed = g_slist_reverse (g_slist_copy (suite->suites));
1709   for (slist = reversed; slist; slist = slist->next)
1710     {
1711       GTestSuite *ts = slist->data;
1712       guint n = l ? strlen (ts->name) : 0;
1713       if (l == n && strncmp (path, ts->name, n) == 0)
1714         n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
1715     }
1716   g_slist_free (reversed);
1717   g_free (test_run_name);
1718   test_run_name = old_name;
1719
1720   return n_bad;
1721 }
1722
1723 /**
1724  * g_test_run_suite:
1725  * @suite: a #GTestSuite
1726  *
1727  * Execute the tests within @suite and all nested #GTestSuites.
1728  * The test suites to be executed are filtered according to
1729  * test path arguments (-p <replaceable>testpath</replaceable>) 
1730  * as parsed by g_test_init().
1731  * g_test_run_suite() or g_test_run() may only be called once
1732  * in a program.
1733  *
1734  * Returns: 0 on success
1735  *
1736  * Since: 2.16
1737  */
1738 int
1739 g_test_run_suite (GTestSuite *suite)
1740 {
1741   guint n_bad = 0;
1742
1743   g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1744   g_return_val_if_fail (g_test_run_once == TRUE, -1);
1745
1746   g_test_run_once = FALSE;
1747
1748   if (!test_paths)
1749     test_paths = g_slist_prepend (test_paths, "");
1750   while (test_paths)
1751     {
1752       const char *rest, *path = test_paths->data;
1753       guint l, n = strlen (suite->name);
1754       test_paths = g_slist_delete_link (test_paths, test_paths);
1755       while (path[0] == '/')
1756         path++;
1757       if (!n) /* root suite, run unconditionally */
1758         {
1759           n_bad += g_test_run_suite_internal (suite, path);
1760           continue;
1761         }
1762       /* regular suite, match path */
1763       rest = strchr (path, '/');
1764       l = strlen (path);
1765       l = rest ? MIN (l, rest - path) : l;
1766       if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1767         n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
1768     }
1769
1770   return n_bad;
1771 }
1772
1773 static void
1774 gtest_default_log_handler (const gchar    *log_domain,
1775                            GLogLevelFlags  log_level,
1776                            const gchar    *message,
1777                            gpointer        unused_data)
1778 {
1779   const gchar *strv[16];
1780   gboolean fatal = FALSE;
1781   gchar *msg;
1782   guint i = 0;
1783
1784   if (log_domain)
1785     {
1786       strv[i++] = log_domain;
1787       strv[i++] = "-";
1788     }
1789   if (log_level & G_LOG_FLAG_FATAL)
1790     {
1791       strv[i++] = "FATAL-";
1792       fatal = TRUE;
1793     }
1794   if (log_level & G_LOG_FLAG_RECURSION)
1795     strv[i++] = "RECURSIVE-";
1796   if (log_level & G_LOG_LEVEL_ERROR)
1797     strv[i++] = "ERROR";
1798   if (log_level & G_LOG_LEVEL_CRITICAL)
1799     strv[i++] = "CRITICAL";
1800   if (log_level & G_LOG_LEVEL_WARNING)
1801     strv[i++] = "WARNING";
1802   if (log_level & G_LOG_LEVEL_MESSAGE)
1803     strv[i++] = "MESSAGE";
1804   if (log_level & G_LOG_LEVEL_INFO)
1805     strv[i++] = "INFO";
1806   if (log_level & G_LOG_LEVEL_DEBUG)
1807     strv[i++] = "DEBUG";
1808   strv[i++] = ": ";
1809   strv[i++] = message;
1810   strv[i++] = NULL;
1811
1812   msg = g_strjoinv ("", (gchar**) strv);
1813   g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
1814   g_log_default_handler (log_domain, log_level, message, unused_data);
1815
1816   g_free (msg);
1817 }
1818
1819 void
1820 g_assertion_message (const char     *domain,
1821                      const char     *file,
1822                      int             line,
1823                      const char     *func,
1824                      const char     *message)
1825 {
1826   char lstr[32];
1827   char *s;
1828
1829   if (!message)
1830     message = "code should not be reached";
1831   g_snprintf (lstr, 32, "%d", line);
1832   s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1833                    "ERROR:", file, ":", lstr, ":",
1834                    func, func[0] ? ":" : "",
1835                    " ", message, NULL);
1836   g_printerr ("**\n%s\n", s);
1837
1838   /* store assertion message in global variable, so that it can be found in a
1839    * core dump */
1840   if (__glib_assert_msg != NULL)
1841       /* free the old one */
1842       free (__glib_assert_msg);
1843   __glib_assert_msg = (char*) malloc (strlen (s) + 1);
1844   strcpy (__glib_assert_msg, s);
1845
1846   g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
1847   g_free (s);
1848   abort();
1849 }
1850
1851 void
1852 g_assertion_message_expr (const char     *domain,
1853                           const char     *file,
1854                           int             line,
1855                           const char     *func,
1856                           const char     *expr)
1857 {
1858   char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1859   g_assertion_message (domain, file, line, func, s);
1860   g_free (s);
1861 }
1862
1863 void
1864 g_assertion_message_cmpnum (const char     *domain,
1865                             const char     *file,
1866                             int             line,
1867                             const char     *func,
1868                             const char     *expr,
1869                             long double     arg1,
1870                             const char     *cmp,
1871                             long double     arg2,
1872                             char            numtype)
1873 {
1874   char *s = NULL;
1875   switch (numtype)
1876     {
1877     case 'i':   s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
1878     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;
1879     case 'f':   s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
1880       /* ideally use: floats=%.7g double=%.17g */
1881     }
1882   g_assertion_message (domain, file, line, func, s);
1883   g_free (s);
1884 }
1885
1886 void
1887 g_assertion_message_cmpstr (const char     *domain,
1888                             const char     *file,
1889                             int             line,
1890                             const char     *func,
1891                             const char     *expr,
1892                             const char     *arg1,
1893                             const char     *cmp,
1894                             const char     *arg2)
1895 {
1896   char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1897   a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1898   a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1899   g_free (t1);
1900   g_free (t2);
1901   s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1902   g_free (a1);
1903   g_free (a2);
1904   g_assertion_message (domain, file, line, func, s);
1905   g_free (s);
1906 }
1907
1908 void
1909 g_assertion_message_error (const char     *domain,
1910                            const char     *file,
1911                            int             line,
1912                            const char     *func,
1913                            const char     *expr,
1914                            const GError   *error,
1915                            GQuark          error_domain,
1916                            int             error_code)
1917 {
1918   GString *gstring;
1919
1920   /* This is used by both g_assert_error() and g_assert_no_error(), so there
1921    * are three cases: expected an error but got the wrong error, expected
1922    * an error but got no error, and expected no error but got an error.
1923    */
1924
1925   gstring = g_string_new ("assertion failed ");
1926   if (error_domain)
1927       g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
1928                               g_quark_to_string (error_domain), error_code);
1929   else
1930     g_string_append_printf (gstring, "(%s == NULL): ", expr);
1931
1932   if (error)
1933       g_string_append_printf (gstring, "%s (%s, %d)", error->message,
1934                               g_quark_to_string (error->domain), error->code);
1935   else
1936     g_string_append_printf (gstring, "%s is NULL", expr);
1937
1938   g_assertion_message (domain, file, line, func, gstring->str);
1939   g_string_free (gstring, TRUE);
1940 }
1941
1942 /**
1943  * g_strcmp0:
1944  * @str1: (allow-none): a C string or %NULL
1945  * @str2: (allow-none): another C string or %NULL
1946  *
1947  * Compares @str1 and @str2 like strcmp(). Handles %NULL 
1948  * gracefully by sorting it before non-%NULL strings.
1949  * Comparing two %NULL pointers returns 0.
1950  *
1951  * Returns: -1, 0 or 1, if @str1 is <, == or > than @str2.
1952  *
1953  * Since: 2.16
1954  */
1955 int
1956 g_strcmp0 (const char     *str1,
1957            const char     *str2)
1958 {
1959   if (!str1)
1960     return -(str1 != str2);
1961   if (!str2)
1962     return str1 != str2;
1963   return strcmp (str1, str2);
1964 }
1965
1966 #ifdef G_OS_UNIX
1967 static int /* 0 on success */
1968 kill_child (int  pid,
1969             int *status,
1970             int  patience)
1971 {
1972   int wr;
1973   if (patience >= 3)    /* try graceful reap */
1974     {
1975       if (waitpid (pid, status, WNOHANG) > 0)
1976         return 0;
1977     }
1978   if (patience >= 2)    /* try SIGHUP */
1979     {
1980       kill (pid, SIGHUP);
1981       if (waitpid (pid, status, WNOHANG) > 0)
1982         return 0;
1983       g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1984       if (waitpid (pid, status, WNOHANG) > 0)
1985         return 0;
1986       g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
1987       if (waitpid (pid, status, WNOHANG) > 0)
1988         return 0;
1989       g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
1990       if (waitpid (pid, status, WNOHANG) > 0)
1991         return 0;
1992     }
1993   if (patience >= 1)    /* try SIGTERM */
1994     {
1995       kill (pid, SIGTERM);
1996       if (waitpid (pid, status, WNOHANG) > 0)
1997         return 0;
1998       g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
1999       if (waitpid (pid, status, WNOHANG) > 0)
2000         return 0;
2001       g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
2002       if (waitpid (pid, status, WNOHANG) > 0)
2003         return 0;
2004     }
2005   /* finish it off */
2006   kill (pid, SIGKILL);
2007   do
2008     wr = waitpid (pid, status, 0);
2009   while (wr < 0 && errno == EINTR);
2010   return wr;
2011 }
2012 #endif
2013
2014 static inline int
2015 g_string_must_read (GString *gstring,
2016                     int      fd)
2017 {
2018 #define STRING_BUFFER_SIZE     4096
2019   char buf[STRING_BUFFER_SIZE];
2020   gssize bytes;
2021  again:
2022   bytes = read (fd, buf, sizeof (buf));
2023   if (bytes == 0)
2024     return 0; /* EOF, calling this function assumes data is available */
2025   else if (bytes > 0)
2026     {
2027       g_string_append_len (gstring, buf, bytes);
2028       return 1;
2029     }
2030   else if (bytes < 0 && errno == EINTR)
2031     goto again;
2032   else /* bytes < 0 */
2033     {
2034       g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2035       return 1; /* ignore error after warning */
2036     }
2037 }
2038
2039 static inline void
2040 g_string_write_out (GString *gstring,
2041                     int      outfd,
2042                     int     *stringpos)
2043 {
2044   if (*stringpos < gstring->len)
2045     {
2046       int r;
2047       do
2048         r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
2049       while (r < 0 && errno == EINTR);
2050       *stringpos += MAX (r, 0);
2051     }
2052 }
2053
2054 static void
2055 test_trap_clear (void)
2056 {
2057   test_trap_last_status = 0;
2058   test_trap_last_pid = 0;
2059   g_free (test_trap_last_stdout);
2060   test_trap_last_stdout = NULL;
2061   g_free (test_trap_last_stderr);
2062   test_trap_last_stderr = NULL;
2063 }
2064
2065 #ifdef G_OS_UNIX
2066
2067 static int
2068 sane_dup2 (int fd1,
2069            int fd2)
2070 {
2071   int ret;
2072   do
2073     ret = dup2 (fd1, fd2);
2074   while (ret < 0 && errno == EINTR);
2075   return ret;
2076 }
2077
2078 static guint64
2079 test_time_stamp (void)
2080 {
2081   GTimeVal tv;
2082   guint64 stamp;
2083   g_get_current_time (&tv);
2084   stamp = tv.tv_sec;
2085   stamp = stamp * 1000000 + tv.tv_usec;
2086   return stamp;
2087 }
2088
2089 #endif
2090
2091 /**
2092  * g_test_trap_fork:
2093  * @usec_timeout:    Timeout for the forked test in micro seconds.
2094  * @test_trap_flags: Flags to modify forking behaviour.
2095  *
2096  * Fork the current test program to execute a test case that might
2097  * not return or that might abort. The forked test case is aborted
2098  * and considered failing if its run time exceeds @usec_timeout.
2099  *
2100  * The forking behavior can be configured with the #GTestTrapFlags flags.
2101  *
2102  * In the following example, the test code forks, the forked child
2103  * process produces some sample output and exits successfully.
2104  * The forking parent process then asserts successful child program
2105  * termination and validates child program outputs.
2106  *
2107  * |[
2108  *   static void
2109  *   test_fork_patterns (void)
2110  *   {
2111  *     if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2112  *       {
2113  *         g_print ("some stdout text: somagic17\n");
2114  *         g_printerr ("some stderr text: semagic43\n");
2115  *         exit (0); /&ast; successful test run &ast;/
2116  *       }
2117  *     g_test_trap_assert_passed();
2118  *     g_test_trap_assert_stdout ("*somagic17*");
2119  *     g_test_trap_assert_stderr ("*semagic43*");
2120  *   }
2121  * ]|
2122  *
2123  * This function is implemented only on Unix platforms.
2124  *
2125  * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2126  *
2127  * Since: 2.16
2128  */
2129 gboolean
2130 g_test_trap_fork (guint64        usec_timeout,
2131                   GTestTrapFlags test_trap_flags)
2132 {
2133 #ifdef G_OS_UNIX
2134   gboolean pass_on_forked_log = FALSE;
2135   int stdout_pipe[2] = { -1, -1 };
2136   int stderr_pipe[2] = { -1, -1 };
2137   int stdtst_pipe[2] = { -1, -1 };
2138   test_trap_clear();
2139   if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
2140     g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
2141   signal (SIGCHLD, SIG_DFL);
2142   test_trap_last_pid = fork ();
2143   if (test_trap_last_pid < 0)
2144     g_error ("failed to fork test program: %s", g_strerror (errno));
2145   if (test_trap_last_pid == 0)  /* child */
2146     {
2147       int fd0 = -1;
2148       close (stdout_pipe[0]);
2149       close (stderr_pipe[0]);
2150       close (stdtst_pipe[0]);
2151       if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2152         fd0 = open ("/dev/null", O_RDONLY);
2153       if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2154         g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
2155       if (fd0 >= 3)
2156         close (fd0);
2157       if (stdout_pipe[1] >= 3)
2158         close (stdout_pipe[1]);
2159       if (stderr_pipe[1] >= 3)
2160         close (stderr_pipe[1]);
2161       test_log_fd = stdtst_pipe[1];
2162       return TRUE;
2163     }
2164   else                          /* parent */
2165     {
2166       GString *sout = g_string_new (NULL);
2167       GString *serr = g_string_new (NULL);
2168       guint64 sstamp;
2169       int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
2170       test_run_forks++;
2171       close (stdout_pipe[1]);
2172       close (stderr_pipe[1]);
2173       close (stdtst_pipe[1]);
2174       sstamp = test_time_stamp();
2175       /* read data until we get EOF on all pipes */
2176       while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
2177         {
2178           fd_set fds;
2179           struct timeval tv;
2180           int ret;
2181           FD_ZERO (&fds);
2182           if (stdout_pipe[0] >= 0)
2183             FD_SET (stdout_pipe[0], &fds);
2184           if (stderr_pipe[0] >= 0)
2185             FD_SET (stderr_pipe[0], &fds);
2186           if (stdtst_pipe[0] >= 0)
2187             FD_SET (stdtst_pipe[0], &fds);
2188           tv.tv_sec = 0;
2189           tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
2190           ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
2191           if (ret < 0 && errno != EINTR)
2192             {
2193               g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
2194               break;
2195             }
2196           if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
2197               g_string_must_read (sout, stdout_pipe[0]) == 0)
2198             {
2199               close (stdout_pipe[0]);
2200               stdout_pipe[0] = -1;
2201             }
2202           if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
2203               g_string_must_read (serr, stderr_pipe[0]) == 0)
2204             {
2205               close (stderr_pipe[0]);
2206               stderr_pipe[0] = -1;
2207             }
2208           if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
2209             {
2210               guint8 buffer[4096];
2211               gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
2212               if (r > 0 && test_log_fd > 0)
2213                 do
2214                   l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
2215                 while (l < 0 && errno == EINTR);
2216               if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
2217                 {
2218                   close (stdtst_pipe[0]);
2219                   stdtst_pipe[0] = -1;
2220                 }
2221             }
2222           if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
2223             g_string_write_out (sout, 1, &soutpos);
2224           if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
2225             g_string_write_out (serr, 2, &serrpos);
2226           if (usec_timeout)
2227             {
2228               guint64 nstamp = test_time_stamp();
2229               int status = 0;
2230               sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
2231               if (usec_timeout < nstamp - sstamp)
2232                 {
2233                   /* timeout reached, need to abort the child now */
2234                   kill_child (test_trap_last_pid, &status, 3);
2235                   test_trap_last_status = 1024; /* timeout */
2236                   if (0 && WIFSIGNALED (status))
2237                     g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
2238                   need_wait = FALSE;
2239                   break;
2240                 }
2241             }
2242         }
2243       if (stdout_pipe[0] != -1)
2244         close (stdout_pipe[0]);
2245       if (stderr_pipe[0] != -1)
2246         close (stderr_pipe[0]);
2247       if (stdtst_pipe[0] != -1)
2248         close (stdtst_pipe[0]);
2249       if (need_wait)
2250         {
2251           int status = 0;
2252           do
2253             wr = waitpid (test_trap_last_pid, &status, 0);
2254           while (wr < 0 && errno == EINTR);
2255           if (WIFEXITED (status)) /* normal exit */
2256             test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
2257           else if (WIFSIGNALED (status))
2258             test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
2259           else /* WCOREDUMP (status) */
2260             test_trap_last_status = 512; /* coredump */
2261         }
2262       test_trap_last_stdout = g_string_free (sout, FALSE);
2263       test_trap_last_stderr = g_string_free (serr, FALSE);
2264       return FALSE;
2265     }
2266 #else
2267   g_message ("Not implemented: g_test_trap_fork");
2268
2269   return FALSE;
2270 #endif
2271 }
2272
2273 /**
2274  * g_test_trap_has_passed:
2275  *
2276  * Check the result of the last g_test_trap_fork() call.
2277  *
2278  * Returns: %TRUE if the last forked child terminated successfully.
2279  *
2280  * Since: 2.16
2281  */
2282 gboolean
2283 g_test_trap_has_passed (void)
2284 {
2285   return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
2286 }
2287
2288 /**
2289  * g_test_trap_reached_timeout:
2290  *
2291  * Check the result of the last g_test_trap_fork() call.
2292  *
2293  * Returns: %TRUE if the last forked child got killed due to a fork timeout.
2294  *
2295  * Since: 2.16
2296  */
2297 gboolean
2298 g_test_trap_reached_timeout (void)
2299 {
2300   return 0 != (test_trap_last_status & 1024); /* timeout flag */
2301 }
2302
2303 void
2304 g_test_trap_assertions (const char     *domain,
2305                         const char     *file,
2306                         int             line,
2307                         const char     *func,
2308                         guint64         assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
2309                         const char     *pattern)
2310 {
2311 #ifdef G_OS_UNIX
2312   gboolean must_pass = assertion_flags == 0;
2313   gboolean must_fail = assertion_flags == 1;
2314   gboolean match_result = 0 == (assertion_flags & 1);
2315   const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
2316   const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
2317   const char *match_error = match_result ? "failed to match" : "contains invalid match";
2318   if (test_trap_last_pid == 0)
2319     g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
2320   if (must_pass && !g_test_trap_has_passed())
2321     {
2322       char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
2323       g_assertion_message (domain, file, line, func, msg);
2324       g_free (msg);
2325     }
2326   if (must_fail && g_test_trap_has_passed())
2327     {
2328       char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
2329       g_assertion_message (domain, file, line, func, msg);
2330       g_free (msg);
2331     }
2332   if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
2333     {
2334       char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
2335       g_assertion_message (domain, file, line, func, msg);
2336       g_free (msg);
2337     }
2338   if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
2339     {
2340       char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
2341       g_assertion_message (domain, file, line, func, msg);
2342       g_free (msg);
2343     }
2344 #endif
2345 }
2346
2347 static void
2348 gstring_overwrite_int (GString *gstring,
2349                        guint    pos,
2350                        guint32  vuint)
2351 {
2352   vuint = g_htonl (vuint);
2353   g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
2354 }
2355
2356 static void
2357 gstring_append_int (GString *gstring,
2358                     guint32  vuint)
2359 {
2360   vuint = g_htonl (vuint);
2361   g_string_append_len (gstring, (const gchar*) &vuint, 4);
2362 }
2363
2364 static void
2365 gstring_append_double (GString *gstring,
2366                        double   vdouble)
2367 {
2368   union { double vdouble; guint64 vuint64; } u;
2369   u.vdouble = vdouble;
2370   u.vuint64 = GUINT64_TO_BE (u.vuint64);
2371   g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
2372 }
2373
2374 static guint8*
2375 g_test_log_dump (GTestLogMsg *msg,
2376                  guint       *len)
2377 {
2378   GString *gstring = g_string_sized_new (1024);
2379   guint ui;
2380   gstring_append_int (gstring, 0);              /* message length */
2381   gstring_append_int (gstring, msg->log_type);
2382   gstring_append_int (gstring, msg->n_strings);
2383   gstring_append_int (gstring, msg->n_nums);
2384   gstring_append_int (gstring, 0);      /* reserved */
2385   for (ui = 0; ui < msg->n_strings; ui++)
2386     {
2387       guint l = strlen (msg->strings[ui]);
2388       gstring_append_int (gstring, l);
2389       g_string_append_len (gstring, msg->strings[ui], l);
2390     }
2391   for (ui = 0; ui < msg->n_nums; ui++)
2392     gstring_append_double (gstring, msg->nums[ui]);
2393   *len = gstring->len;
2394   gstring_overwrite_int (gstring, 0, *len);     /* message length */
2395   return (guint8*) g_string_free (gstring, FALSE);
2396 }
2397
2398 static inline long double
2399 net_double (const gchar **ipointer)
2400 {
2401   union { guint64 vuint64; double vdouble; } u;
2402   guint64 aligned_int64;
2403   memcpy (&aligned_int64, *ipointer, 8);
2404   *ipointer += 8;
2405   u.vuint64 = GUINT64_FROM_BE (aligned_int64);
2406   return u.vdouble;
2407 }
2408
2409 static inline guint32
2410 net_int (const gchar **ipointer)
2411 {
2412   guint32 aligned_int;
2413   memcpy (&aligned_int, *ipointer, 4);
2414   *ipointer += 4;
2415   return g_ntohl (aligned_int);
2416 }
2417
2418 static gboolean
2419 g_test_log_extract (GTestLogBuffer *tbuffer)
2420 {
2421   const gchar *p = tbuffer->data->str;
2422   GTestLogMsg msg;
2423   guint mlength;
2424   if (tbuffer->data->len < 4 * 5)
2425     return FALSE;
2426   mlength = net_int (&p);
2427   if (tbuffer->data->len < mlength)
2428     return FALSE;
2429   msg.log_type = net_int (&p);
2430   msg.n_strings = net_int (&p);
2431   msg.n_nums = net_int (&p);
2432   if (net_int (&p) == 0)
2433     {
2434       guint ui;
2435       msg.strings = g_new0 (gchar*, msg.n_strings + 1);
2436       msg.nums = g_new0 (long double, msg.n_nums);
2437       for (ui = 0; ui < msg.n_strings; ui++)
2438         {
2439           guint sl = net_int (&p);
2440           msg.strings[ui] = g_strndup (p, sl);
2441           p += sl;
2442         }
2443       for (ui = 0; ui < msg.n_nums; ui++)
2444         msg.nums[ui] = net_double (&p);
2445       if (p <= tbuffer->data->str + mlength)
2446         {
2447           g_string_erase (tbuffer->data, 0, mlength);
2448           tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
2449           return TRUE;
2450         }
2451     }
2452   g_free (msg.nums);
2453   g_strfreev (msg.strings);
2454   g_error ("corrupt log stream from test program");
2455   return FALSE;
2456 }
2457
2458 /**
2459  * g_test_log_buffer_new:
2460  *
2461  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2462  */
2463 GTestLogBuffer*
2464 g_test_log_buffer_new (void)
2465 {
2466   GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
2467   tb->data = g_string_sized_new (1024);
2468   return tb;
2469 }
2470
2471 /**
2472  * g_test_log_buffer_free:
2473  *
2474  * Internal function for gtester to free test log messages, no ABI guarantees provided.
2475  */
2476 void
2477 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
2478 {
2479   g_return_if_fail (tbuffer != NULL);
2480   while (tbuffer->msgs)
2481     g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
2482   g_string_free (tbuffer->data, TRUE);
2483   g_free (tbuffer);
2484 }
2485
2486 /**
2487  * g_test_log_buffer_push:
2488  *
2489  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
2490  */
2491 void
2492 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
2493                         guint           n_bytes,
2494                         const guint8   *bytes)
2495 {
2496   g_return_if_fail (tbuffer != NULL);
2497   if (n_bytes)
2498     {
2499       gboolean more_messages;
2500       g_return_if_fail (bytes != NULL);
2501       g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
2502       do
2503         more_messages = g_test_log_extract (tbuffer);
2504       while (more_messages);
2505     }
2506 }
2507
2508 /**
2509  * g_test_log_buffer_pop:
2510  *
2511  * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
2512  */
2513 GTestLogMsg*
2514 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
2515 {
2516   GTestLogMsg *msg = NULL;
2517   g_return_val_if_fail (tbuffer != NULL, NULL);
2518   if (tbuffer->msgs)
2519     {
2520       GSList *slist = g_slist_last (tbuffer->msgs);
2521       msg = slist->data;
2522       tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
2523     }
2524   return msg;
2525 }
2526
2527 /**
2528  * g_test_log_msg_free:
2529  *
2530  * Internal function for gtester to free test log messages, no ABI guarantees provided.
2531  */
2532 void
2533 g_test_log_msg_free (GTestLogMsg *tmsg)
2534 {
2535   g_return_if_fail (tmsg != NULL);
2536   g_strfreev (tmsg->strings);
2537   g_free (tmsg->nums);
2538   g_free (tmsg);
2539 }
2540
2541 /* --- macros docs START --- */
2542 /**
2543  * g_test_add:
2544  * @testpath:  The test path for a new test case.
2545  * @Fixture:   The type of a fixture data structure.
2546  * @tdata:     Data argument for the test functions.
2547  * @fsetup:    The function to set up the fixture data.
2548  * @ftest:     The actual test function.
2549  * @fteardown: The function to tear down the fixture data.
2550  *
2551  * Hook up a new test case at @testpath, similar to g_test_add_func().
2552  * A fixture data structure with setup and teardown function may be provided
2553  * though, similar to g_test_create_case().
2554  * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2555  * fteardown() callbacks can expect a @Fixture pointer as first argument in
2556  * a type safe manner.
2557  *
2558  * Since: 2.16
2559  **/
2560 /* --- macros docs END --- */