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