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