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