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