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