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