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