c9c0a4ef9137dd5d5e17f3c441ca1b5126c715b3
[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, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include "config.h"
20
21 #include "gtestutils.h"
22 #include "gfileutils.h"
23
24 #include <sys/types.h>
25 #ifdef G_OS_UNIX
26 #include <sys/wait.h>
27 #include <sys/time.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <glib/gstdio.h>
31 #endif
32 #include <string.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #ifdef HAVE_SYS_RESOURCE_H
36 #include <sys/resource.h>
37 #endif
38 #ifdef G_OS_WIN32
39 #include <io.h>
40 #include <windows.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 #include "gspawn.h"
55 #include "glib-private.h"
56
57
58 /**
59  * SECTION:testing
60  * @title: Testing
61  * @short_description: a test framework
62  * @see_also: <link linkend="gtester">gtester</link>,
63  *            <link linkend="gtester-report">gtester-report</link>
64  *
65  * GLib provides a framework for writing and maintaining unit tests
66  * in parallel to the code they are testing. The API is designed according
67  * to established concepts found in the other test frameworks (JUnit, NUnit,
68  * RUnit), which in turn is based on smalltalk unit testing concepts.
69  *
70  * - Test case: Tests (test methods) are grouped together with their
71  *   fixture into test cases.
72  *
73  * - Fixture: A test fixture consists of fixture data and setup and
74  *   teardown methods to establish the environment for the test
75  *   functions. We use fresh fixtures, i.e. fixtures are newly set
76  *   up and torn down around each test invocation to avoid dependencies
77  *   between tests.
78  *
79  * - Test suite: Test cases can be grouped into test suites, to allow
80  *   subsets of the available tests to be run. Test suites can be
81  *   grouped into other test suites as well.
82  *
83  * The API is designed to handle creation and registration of test suites
84  * and test cases implicitly. A simple call like
85  * |[<!-- language="C" --> 
86  *   g_test_add_func ("/misc/assertions", test_assertions);
87  * ]|
88  * creates a test suite called "misc" with a single test case named
89  * "assertions", which consists of running the test_assertions function.
90  *
91  * In addition to the traditional g_assert(), the test framework provides
92  * an extended set of assertions for string and numerical comparisons:
93  * g_assert_cmpfloat(), g_assert_cmpint(), g_assert_cmpuint(),
94  * g_assert_cmphex(), g_assert_cmpstr(). The advantage of these variants
95  * over plain g_assert() is that the assertion messages can be more
96  * elaborate, and include the values of the compared entities.
97  *
98  * GLib ships with two utilities called gtester and gtester-report to
99  * facilitate running tests and producing nicely formatted test reports.
100  */
101
102 /**
103  * g_test_initialized:
104  *
105  * Returns %TRUE if g_test_init() has been called.
106  *
107  * Returns: %TRUE if g_test_init() has been called.
108  *
109  * Since: 2.36
110  */
111
112 /**
113  * g_test_quick:
114  *
115  * Returns %TRUE if tests are run in quick mode.
116  * Exactly one of g_test_quick() and g_test_slow() is active in any run;
117  * there is no "medium speed".
118  *
119  * Returns: %TRUE if in quick mode
120  */
121
122 /**
123  * g_test_slow:
124  *
125  * Returns %TRUE if tests are run in slow mode.
126  * Exactly one of g_test_quick() and g_test_slow() is active in any run;
127  * there is no "medium speed".
128  *
129  * Returns: the opposite of g_test_quick()
130  */
131
132 /**
133  * g_test_thorough:
134  *
135  * Returns %TRUE if tests are run in thorough mode, equivalent to
136  * g_test_slow().
137  *
138  * Returns: the same thing as g_test_slow()
139  */
140
141 /**
142  * g_test_perf:
143  *
144  * Returns %TRUE if tests are run in performance mode.
145  *
146  * Returns: %TRUE if in performance mode
147  */
148
149 /**
150  * g_test_undefined:
151  *
152  * Returns %TRUE if tests may provoke assertions and other formally-undefined
153  * behaviour, to verify that appropriate warnings are given. It might, in some
154  * cases, be useful to turn this off if running tests under valgrind.
155  *
156  * Returns: %TRUE if tests may provoke programming errors
157  */
158
159 /**
160  * g_test_verbose:
161  *
162  * Returns %TRUE if tests are run in verbose mode.
163  * The default is neither g_test_verbose() nor g_test_quiet().
164  *
165  * Returns: %TRUE if in verbose mode
166  */
167
168 /**
169  * g_test_quiet:
170  *
171  * Returns %TRUE if tests are run in quiet mode.
172  * The default is neither g_test_verbose() nor g_test_quiet().
173  *
174  * Returns: %TRUE if in quiet mode
175  */
176
177 /**
178  * g_test_queue_unref:
179  * @gobject: the object to unref
180  *
181  * Enqueue an object to be released with g_object_unref() during
182  * the next teardown phase. This is equivalent to calling
183  * g_test_queue_destroy() with a destroy callback of g_object_unref().
184  *
185  * Since: 2.16
186  */
187
188 /**
189  * GTestTrapFlags:
190  * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
191  *     `/dev/null` so it cannot be observed on the console during test
192  *     runs. The actual output is still captured though to allow later
193  *     tests with g_test_trap_assert_stdout().
194  * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
195  *     `/dev/null` so it cannot be observed on the console during test
196  *     runs. The actual output is still captured though to allow later
197  *     tests with g_test_trap_assert_stderr().
198  * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
199  *     child process is shared with stdin of its parent process.
200  *     It is redirected to `/dev/null` otherwise.
201  *
202  * Test traps are guards around forked tests.
203  * These flags determine what traps to set.
204  *
205  * Deprecated: #GTestTrapFlags is used only with g_test_trap_fork(),
206  * which is deprecated. g_test_trap_subprocess() uses
207  * #GTestTrapSubprocessFlags.
208  */
209
210 /**
211  * GTestSubprocessFlags:
212  * @G_TEST_SUBPROCESS_INHERIT_STDIN: If this flag is given, the child
213  *     process will inherit the parent's stdin. Otherwise, the child's
214  *     stdin is redirected to `/dev/null`.
215  * @G_TEST_SUBPROCESS_INHERIT_STDOUT: If this flag is given, the child
216  *     process will inherit the parent's stdout. Otherwise, the child's
217  *     stdout will not be visible, but it will be captured to allow
218  *     later tests with g_test_trap_assert_stdout().
219  * @G_TEST_SUBPROCESS_INHERIT_STDERR: If this flag is given, the child
220  *     process will inherit the parent's stderr. Otherwise, the child's
221  *     stderr will not be visible, but it will be captured to allow
222  *     later tests with g_test_trap_assert_stderr().
223  *
224  * Flags to pass to g_test_trap_subprocess() to control input and output.
225  *
226  * Note that in contrast with g_test_trap_fork(), the default is to
227  * not show stdout and stderr.
228  */
229
230 /**
231  * g_test_trap_assert_passed:
232  *
233  * Assert that the last test subprocess passed.
234  * See g_test_trap_subprocess().
235  *
236  * Since: 2.16
237  */
238
239 /**
240  * g_test_trap_assert_failed:
241  *
242  * Assert that the last test subprocess failed.
243  * See g_test_trap_subprocess().
244  *
245  * This is sometimes used to test situations that are formally considered to
246  * be undefined behaviour, like inputs that fail a g_return_if_fail()
247  * check. In these situations you should skip the entire test, including the
248  * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
249  * to indicate that undefined behaviour may be tested.
250  *
251  * Since: 2.16
252  */
253
254 /**
255  * g_test_trap_assert_stdout:
256  * @soutpattern: a glob-style
257  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
258  *
259  * Assert that the stdout output of the last test subprocess matches
260  * @soutpattern. See g_test_trap_subprocess().
261  *
262  * Since: 2.16
263  */
264
265 /**
266  * g_test_trap_assert_stdout_unmatched:
267  * @soutpattern: a glob-style
268  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
269  *
270  * Assert that the stdout output of the last test subprocess
271  * does not match @soutpattern. See g_test_trap_subprocess().
272  *
273  * Since: 2.16
274  */
275
276 /**
277  * g_test_trap_assert_stderr:
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 test subprocess
282  * matches @serrpattern. See  g_test_trap_subprocess().
283  *
284  * This is sometimes used to test situations that are formally
285  * considered to be undefined behaviour, like code that hits a
286  * g_assert() or g_error(). In these situations you should skip the
287  * entire test, including the call to g_test_trap_subprocess(), unless
288  * g_test_undefined() returns %TRUE to indicate that undefined
289  * behaviour may be tested.
290  *
291  * Since: 2.16
292  */
293
294 /**
295  * g_test_trap_assert_stderr_unmatched:
296  * @serrpattern: a glob-style
297  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
298  *
299  * Assert that the stderr output of the last test subprocess
300  * does not match @serrpattern. See g_test_trap_subprocess().
301  *
302  * Since: 2.16
303  */
304
305 /**
306  * g_test_rand_bit:
307  *
308  * Get a reproducible random bit (0 or 1), see g_test_rand_int()
309  * for details on test case random numbers.
310  *
311  * Since: 2.16
312  */
313
314 /**
315  * g_assert:
316  * @expr: the expression to check
317  *
318  * Debugging macro to terminate the application if the assertion
319  * fails. If the assertion fails (i.e. the expression is not true),
320  * an error message is logged and the application is terminated.
321  *
322  * The macro can be turned off in final releases of code by defining
323  * `G_DISABLE_ASSERT` when compiling the application.
324  */
325
326 /**
327  * g_assert_not_reached:
328  *
329  * Debugging macro to terminate the application if it is ever
330  * reached. If it is reached, an error message is logged and the
331  * application is terminated.
332  *
333  * The macro can be turned off in final releases of code by defining
334  * `G_DISABLE_ASSERT` when compiling the application.
335  */
336
337 /**
338  * g_assert_true:
339  * @expr: the expression to check
340  *
341  * Debugging macro to check that an expression is true.
342  *
343  * If the assertion fails (i.e. the expression is not true),
344  * an error message is logged and the application is either
345  * terminated or the testcase marked as failed.
346  *
347  * See g_test_set_nonfatal_assertions().
348  *
349  * Since: 2.38
350  */
351
352 /**
353  * g_assert_false:
354  * @expr: the expression to check
355  *
356  * Debugging macro to check an expression is false.
357  *
358  * If the assertion fails (i.e. the expression is not false),
359  * an error message is logged and the application is either
360  * terminated or the testcase marked as failed.
361  *
362  * See g_test_set_nonfatal_assertions().
363  *
364  * Since: 2.38
365  */
366
367 /**
368  * g_assert_null:
369  * @expr: the expression to check
370  *
371  * Debugging macro to check an expression is %NULL.
372  *
373  * If the assertion fails (i.e. the expression is not %NULL),
374  * an error message is logged and the application is either
375  * terminated or the testcase marked as failed.
376  *
377  * See g_test_set_nonfatal_assertions().
378  *
379  * Since: 2.38
380  */
381
382 /**
383  * g_assert_nonnull:
384  * @expr: the expression to check
385  *
386  * Debugging macro to check an expression is not %NULL.
387  *
388  * If the assertion fails (i.e. the expression is %NULL),
389  * an error message is logged and the application is either
390  * terminated or the testcase marked as failed.
391  *
392  * See g_test_set_nonfatal_assertions().
393  *
394  * Since: 2.40
395  */
396
397 /**
398  * g_assert_cmpstr:
399  * @s1: a string (may be %NULL)
400  * @cmp: The comparison operator to use.
401  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
402  * @s2: another string (may be %NULL)
403  *
404  * Debugging macro to compare two strings. If the comparison fails,
405  * an error message is logged and the application is either terminated
406  * or the testcase marked as failed.
407  * The strings are compared using g_strcmp0().
408  *
409  * The effect of <literal>g_assert_cmpstr (s1, op, s2)</literal> is
410  * the same as <literal>g_assert_true (g_strcmp0 (s1, s2) op 0)</literal>.
411  * The advantage of this macro is that it can produce a message that
412  * includes the actual values of @s1 and @s2.
413  *
414  * |[<!-- language="C" --> 
415  *   g_assert_cmpstr (mystring, ==, "fubar");
416  * ]|
417  *
418  * Since: 2.16
419  */
420
421 /**
422  * g_assert_cmpint:
423  * @n1: an integer
424  * @cmp: The comparison operator to use.
425  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
426  * @n2: another integer
427  *
428  * Debugging macro to compare two integers.
429  *
430  * The effect of <literal>g_assert_cmpint (n1, op, n2)</literal> is
431  * the same as <literal>g_assert_true (n1 op n2)</literal>. The advantage
432  * of this macro is that it can produce a message that includes the
433  * actual values of @n1 and @n2.
434  *
435  * Since: 2.16
436  */
437
438 /**
439  * g_assert_cmpuint:
440  * @n1: an unsigned integer
441  * @cmp: The comparison operator to use.
442  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
443  * @n2: another unsigned integer
444  *
445  * Debugging macro to compare two unsigned integers.
446  *
447  * The effect of <literal>g_assert_cmpuint (n1, op, n2)</literal> is
448  * the same as <literal>g_assert_true (n1 op n2)</literal>. The advantage
449  * of this macro is that it can produce a message that includes the
450  * actual values of @n1 and @n2.
451  *
452  * Since: 2.16
453  */
454
455 /**
456  * g_assert_cmphex:
457  * @n1: an unsigned integer
458  * @cmp: The comparison operator to use.
459  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
460  * @n2: another unsigned integer
461  *
462  * Debugging macro to compare to unsigned integers.
463  *
464  * This is a variant of g_assert_cmpuint() that displays the numbers
465  * in hexadecimal notation in the message.
466  *
467  * Since: 2.16
468  */
469
470 /**
471  * g_assert_cmpfloat:
472  * @n1: an floating point number
473  * @cmp: The comparison operator to use.
474  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
475  * @n2: another floating point number
476  *
477  * Debugging macro to compare two floating point numbers.
478  *
479  * The effect of <literal>g_assert_cmpfloat (n1, op, n2)</literal> is
480  * the same as <literal>g_assert_true (n1 op n2)</literal>. The advantage
481  * of this macro is that it can produce a message that includes the
482  * actual values of @n1 and @n2.
483  *
484  * Since: 2.16
485  */
486
487 /**
488  * g_assert_no_error:
489  * @err: a #GError, possibly %NULL
490  *
491  * Debugging macro to check that a #GError is not set.
492  *
493  * The effect of <literal>g_assert_no_error (err)</literal> is
494  * the same as <literal>g_assert_true (err == NULL)</literal>. The advantage
495  * of this macro is that it can produce a message that includes
496  * the error message and code.
497  *
498  * Since: 2.20
499  */
500
501 /**
502  * g_assert_error:
503  * @err: a #GError, possibly %NULL
504  * @dom: the expected error domain (a #GQuark)
505  * @c: the expected error code
506  *
507  * Debugging macro to check that a method has returned
508  * the correct #GError.
509  *
510  * The effect of <literal>g_assert_error (err, dom, c)</literal> is
511  * the same as <literal>g_assert_true (err != NULL &amp;&amp; err->domain
512  * == dom &amp;&amp; err->code == c)</literal>. The advantage of this
513  * macro is that it can produce a message that includes the incorrect
514  * error message and code.
515  *
516  * This can only be used to test for a specific error. If you want to
517  * test that @err is set, but don't care what it's set to, just use
518  * <literal>g_assert (err != NULL)</literal>
519  *
520  * Since: 2.20
521  */
522
523 /**
524  * GTestCase:
525  *
526  * An opaque structure representing a test case.
527  */
528
529 /**
530  * GTestSuite:
531  *
532  * An opaque structure representing a test suite.
533  */
534
535
536 /* Global variable for storing assertion messages; this is the counterpart to
537  * glibc's (private) __abort_msg variable, and allows developers and crash
538  * analysis systems like Apport and ABRT to fish out assertion messages from
539  * core dumps, instead of having to catch them on screen output.
540  */
541 GLIB_VAR char *__glib_assert_msg;
542 char *__glib_assert_msg = NULL;
543
544 /* --- constants --- */
545 #define G_TEST_STATUS_TIMED_OUT 1024
546
547 /* --- structures --- */
548 struct GTestCase
549 {
550   gchar  *name;
551   guint   fixture_size;
552   void   (*fixture_setup)    (void*, gconstpointer);
553   void   (*fixture_test)     (void*, gconstpointer);
554   void   (*fixture_teardown) (void*, gconstpointer);
555   gpointer test_data;
556 };
557 struct GTestSuite
558 {
559   gchar  *name;
560   GSList *suites;
561   GSList *cases;
562 };
563 typedef struct DestroyEntry DestroyEntry;
564 struct DestroyEntry
565 {
566   DestroyEntry *next;
567   GDestroyNotify destroy_func;
568   gpointer       destroy_data;
569 };
570
571 /* --- prototypes --- */
572 static void     test_run_seed                   (const gchar *rseed);
573 static void     test_trap_clear                 (void);
574 static guint8*  g_test_log_dump                 (GTestLogMsg *msg,
575                                                  guint       *len);
576 static void     gtest_default_log_handler       (const gchar    *log_domain,
577                                                  GLogLevelFlags  log_level,
578                                                  const gchar    *message,
579                                                  gpointer        unused_data);
580
581
582 typedef enum {
583   G_TEST_RUN_SUCCESS,
584   G_TEST_RUN_SKIPPED,
585   G_TEST_RUN_FAILURE,
586   G_TEST_RUN_INCOMPLETE
587 } GTestResult;
588
589 /* --- variables --- */
590 static int         test_log_fd = -1;
591 static gboolean    test_mode_fatal = TRUE;
592 static gboolean    g_test_run_once = TRUE;
593 static gboolean    test_run_list = FALSE;
594 static gchar      *test_run_seedstr = NULL;
595 static GRand      *test_run_rand = NULL;
596 static gchar      *test_run_name = "";
597 static GSList    **test_filename_free_list;
598 static guint       test_run_forks = 0;
599 static guint       test_run_count = 0;
600 static guint       test_skipped_count = 0;
601 static GTestResult test_run_success = G_TEST_RUN_FAILURE;
602 static gchar      *test_run_msg = NULL;
603 static guint       test_startup_skip_count = 0;
604 static GTimer     *test_user_timer = NULL;
605 static double      test_user_stamp = 0;
606 static GSList     *test_paths = NULL;
607 static GSList     *test_paths_skipped = NULL;
608 static GTestSuite *test_suite_root = NULL;
609 static int         test_trap_last_status = 0;
610 static GPid        test_trap_last_pid = 0;
611 static char       *test_trap_last_subprocess = NULL;
612 static char       *test_trap_last_stdout = NULL;
613 static char       *test_trap_last_stderr = NULL;
614 static char       *test_uri_base = NULL;
615 static gboolean    test_debug_log = FALSE;
616 static gboolean    test_tap_log = FALSE;
617 static gboolean    test_nonfatal_assertions = FALSE;
618 static DestroyEntry *test_destroy_queue = NULL;
619 static char       *test_argv0 = NULL;
620 static char       *test_argv0_dirname;
621 static const char *test_disted_files_dir;
622 static const char *test_built_files_dir;
623 static char       *test_initial_cwd = NULL;
624 static gboolean    test_in_subprocess = FALSE;
625 static GTestConfig mutable_test_config_vars = {
626   FALSE,        /* test_initialized */
627   TRUE,         /* test_quick */
628   FALSE,        /* test_perf */
629   FALSE,        /* test_verbose */
630   FALSE,        /* test_quiet */
631   TRUE,         /* test_undefined */
632 };
633 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
634 static gboolean  no_g_set_prgname = FALSE;
635
636 /* --- functions --- */
637 const char*
638 g_test_log_type_name (GTestLogType log_type)
639 {
640   switch (log_type)
641     {
642     case G_TEST_LOG_NONE:               return "none";
643     case G_TEST_LOG_ERROR:              return "error";
644     case G_TEST_LOG_START_BINARY:       return "binary";
645     case G_TEST_LOG_LIST_CASE:          return "list";
646     case G_TEST_LOG_SKIP_CASE:          return "skip";
647     case G_TEST_LOG_START_CASE:         return "start";
648     case G_TEST_LOG_STOP_CASE:          return "stop";
649     case G_TEST_LOG_MIN_RESULT:         return "minperf";
650     case G_TEST_LOG_MAX_RESULT:         return "maxperf";
651     case G_TEST_LOG_MESSAGE:            return "message";
652     case G_TEST_LOG_START_SUITE:        return "start suite";
653     case G_TEST_LOG_STOP_SUITE:         return "stop suite";
654     }
655   return "???";
656 }
657
658 static void
659 g_test_log_send (guint         n_bytes,
660                  const guint8 *buffer)
661 {
662   if (test_log_fd >= 0)
663     {
664       int r;
665       do
666         r = write (test_log_fd, buffer, n_bytes);
667       while (r < 0 && errno == EINTR);
668     }
669   if (test_debug_log)
670     {
671       GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
672       GTestLogMsg *msg;
673       guint ui;
674       g_test_log_buffer_push (lbuffer, n_bytes, buffer);
675       msg = g_test_log_buffer_pop (lbuffer);
676       g_warn_if_fail (msg != NULL);
677       g_warn_if_fail (lbuffer->data->len == 0);
678       g_test_log_buffer_free (lbuffer);
679       /* print message */
680       g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
681       for (ui = 0; ui < msg->n_strings; ui++)
682         g_printerr (":{%s}", msg->strings[ui]);
683       if (msg->n_nums)
684         {
685           g_printerr (":(");
686           for (ui = 0; ui < msg->n_nums; ui++)
687             {
688               if ((long double) (long) msg->nums[ui] == msg->nums[ui])
689                 g_printerr ("%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
690               else
691                 g_printerr ("%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
692             }
693           g_printerr (")");
694         }
695       g_printerr (":LOG*}\n");
696       g_test_log_msg_free (msg);
697     }
698 }
699
700 static void
701 g_test_log (GTestLogType lbit,
702             const gchar *string1,
703             const gchar *string2,
704             guint        n_args,
705             long double *largs)
706 {
707   gboolean fail;
708   GTestLogMsg msg;
709   gchar *astrings[3] = { NULL, NULL, NULL };
710   guint8 *dbuffer;
711   guint32 dbufferlen;
712
713   switch (lbit)
714     {
715     case G_TEST_LOG_START_BINARY:
716       if (test_tap_log)
717         g_print ("# random seed: %s\n", string2);
718       else if (g_test_verbose())
719         g_print ("GTest: random seed: %s\n", string2);
720       break;
721     case G_TEST_LOG_START_SUITE:
722       if (test_tap_log)
723         {
724           if (string1[0] != 0)
725             g_print ("# Start of %s tests\n", string1);
726         }
727       break;
728     case G_TEST_LOG_STOP_SUITE:
729       if (test_tap_log)
730         {
731           if (string1[0] != 0)
732             g_print ("# End of %s tests\n", string1);
733           else
734             g_print ("1..%d\n", test_run_count);
735         }
736       break;
737     case G_TEST_LOG_STOP_CASE:
738       fail = largs[0] != G_TEST_RUN_SUCCESS && largs[0] != G_TEST_RUN_SKIPPED;
739       if (test_tap_log)
740         {
741           g_print ("%s %d %s", fail ? "not ok" : "ok", test_run_count, string1);
742           if (largs[0] == G_TEST_RUN_INCOMPLETE)
743             g_print (" # TODO %s\n", string2 ? string2 : "");
744           else if (largs[0] == G_TEST_RUN_SKIPPED)
745             g_print (" # SKIP %s\n", string2 ? string2 : "");
746           else
747             g_print ("\n");
748         }
749       else if (g_test_verbose())
750         g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
751       else if (!g_test_quiet())
752         g_print ("%s\n", fail ? "FAIL" : "OK");
753       if (fail && test_mode_fatal)
754         {
755           if (test_tap_log)
756             g_print ("Bail out!\n");
757           abort();
758         }
759       if (largs[0] == G_TEST_RUN_SKIPPED)
760         test_skipped_count++;
761       break;
762     case G_TEST_LOG_MIN_RESULT:
763       if (test_tap_log)
764         g_print ("# min perf: %s\n", string1);
765       else if (g_test_verbose())
766         g_print ("(MINPERF:%s)\n", string1);
767       break;
768     case G_TEST_LOG_MAX_RESULT:
769       if (test_tap_log)
770         g_print ("# max perf: %s\n", string1);
771       else if (g_test_verbose())
772         g_print ("(MAXPERF:%s)\n", string1);
773       break;
774     case G_TEST_LOG_MESSAGE:
775     case G_TEST_LOG_ERROR:
776       if (test_tap_log)
777         g_print ("# %s\n", string1);
778       else if (g_test_verbose())
779         g_print ("(MSG: %s)\n", string1);
780       break;
781     default: ;
782     }
783
784   msg.log_type = lbit;
785   msg.n_strings = (string1 != NULL) + (string1 && string2);
786   msg.strings = astrings;
787   astrings[0] = (gchar*) string1;
788   astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
789   msg.n_nums = n_args;
790   msg.nums = largs;
791   dbuffer = g_test_log_dump (&msg, &dbufferlen);
792   g_test_log_send (dbufferlen, dbuffer);
793   g_free (dbuffer);
794
795   switch (lbit)
796     {
797     case G_TEST_LOG_START_CASE:
798       if (test_tap_log)
799         ;
800       else if (g_test_verbose())
801         g_print ("GTest: run: %s\n", string1);
802       else if (!g_test_quiet())
803         g_print ("%s: ", string1);
804       break;
805     default: ;
806     }
807 }
808
809 /* We intentionally parse the command line without GOptionContext
810  * because otherwise you would never be able to test it.
811  */
812 static void
813 parse_args (gint    *argc_p,
814             gchar ***argv_p)
815 {
816   guint argc = *argc_p;
817   gchar **argv = *argv_p;
818   guint i, e;
819
820   test_argv0 = argv[0];
821   test_initial_cwd = g_get_current_dir ();
822
823   /* parse known args */
824   for (i = 1; i < argc; i++)
825     {
826       if (strcmp (argv[i], "--g-fatal-warnings") == 0)
827         {
828           GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
829           fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
830           g_log_set_always_fatal (fatal_mask);
831           argv[i] = NULL;
832         }
833       else if (strcmp (argv[i], "--keep-going") == 0 ||
834                strcmp (argv[i], "-k") == 0)
835         {
836           test_mode_fatal = FALSE;
837           argv[i] = NULL;
838         }
839       else if (strcmp (argv[i], "--debug-log") == 0)
840         {
841           test_debug_log = TRUE;
842           argv[i] = NULL;
843         }
844       else if (strcmp (argv[i], "--tap") == 0)
845         {
846           test_tap_log = TRUE;
847           argv[i] = NULL;
848         }
849       else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
850         {
851           gchar *equal = argv[i] + 12;
852           if (*equal == '=')
853             test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
854           else if (i + 1 < argc)
855             {
856               argv[i++] = NULL;
857               test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
858             }
859           argv[i] = NULL;
860         }
861       else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
862         {
863           gchar *equal = argv[i] + 16;
864           if (*equal == '=')
865             test_startup_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
866           else if (i + 1 < argc)
867             {
868               argv[i++] = NULL;
869               test_startup_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
870             }
871           argv[i] = NULL;
872         }
873       else if (strcmp ("--GTestSubprocess", argv[i]) == 0)
874         {
875           test_in_subprocess = TRUE;
876           /* We typically expect these child processes to crash, and some
877            * tests spawn a *lot* of them.  Avoid spamming system crash
878            * collection programs such as systemd-coredump and abrt.
879            */
880 #ifdef HAVE_SYS_RESOURCE_H
881           {
882             struct rlimit limit = { 0, 0 };
883             (void) setrlimit (RLIMIT_CORE, &limit);
884           }
885 #endif
886           argv[i] = NULL;
887         }
888       else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
889         {
890           gchar *equal = argv[i] + 2;
891           if (*equal == '=')
892             test_paths = g_slist_prepend (test_paths, equal + 1);
893           else if (i + 1 < argc)
894             {
895               argv[i++] = NULL;
896               test_paths = g_slist_prepend (test_paths, argv[i]);
897             }
898           argv[i] = NULL;
899         }
900       else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
901         {
902           gchar *equal = argv[i] + 2;
903           if (*equal == '=')
904             test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
905           else if (i + 1 < argc)
906             {
907               argv[i++] = NULL;
908               test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
909             }
910           argv[i] = NULL;
911         }
912       else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
913         {
914           gchar *equal = argv[i] + 2;
915           const gchar *mode = "";
916           if (*equal == '=')
917             mode = equal + 1;
918           else if (i + 1 < argc)
919             {
920               argv[i++] = NULL;
921               mode = argv[i];
922             }
923           if (strcmp (mode, "perf") == 0)
924             mutable_test_config_vars.test_perf = TRUE;
925           else if (strcmp (mode, "slow") == 0)
926             mutable_test_config_vars.test_quick = FALSE;
927           else if (strcmp (mode, "thorough") == 0)
928             mutable_test_config_vars.test_quick = FALSE;
929           else if (strcmp (mode, "quick") == 0)
930             {
931               mutable_test_config_vars.test_quick = TRUE;
932               mutable_test_config_vars.test_perf = FALSE;
933             }
934           else if (strcmp (mode, "undefined") == 0)
935             mutable_test_config_vars.test_undefined = TRUE;
936           else if (strcmp (mode, "no-undefined") == 0)
937             mutable_test_config_vars.test_undefined = FALSE;
938           else
939             g_error ("unknown test mode: -m %s", mode);
940           argv[i] = NULL;
941         }
942       else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
943         {
944           mutable_test_config_vars.test_quiet = TRUE;
945           mutable_test_config_vars.test_verbose = FALSE;
946           argv[i] = NULL;
947         }
948       else if (strcmp ("--verbose", argv[i]) == 0)
949         {
950           mutable_test_config_vars.test_quiet = FALSE;
951           mutable_test_config_vars.test_verbose = TRUE;
952           argv[i] = NULL;
953         }
954       else if (strcmp ("-l", argv[i]) == 0)
955         {
956           test_run_list = TRUE;
957           argv[i] = NULL;
958         }
959       else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
960         {
961           gchar *equal = argv[i] + 6;
962           if (*equal == '=')
963             test_run_seedstr = equal + 1;
964           else if (i + 1 < argc)
965             {
966               argv[i++] = NULL;
967               test_run_seedstr = argv[i];
968             }
969           argv[i] = NULL;
970         }
971       else if (strcmp ("-?", argv[i]) == 0 ||
972                strcmp ("-h", argv[i]) == 0 ||
973                strcmp ("--help", argv[i]) == 0)
974         {
975           printf ("Usage:\n"
976                   "  %s [OPTION...]\n\n"
977                   "Help Options:\n"
978                   "  -h, --help                     Show help options\n\n"
979                   "Test Options:\n"
980                   "  --g-fatal-warnings             Make all warnings fatal\n"
981                   "  -l                             List test cases available in a test executable\n"
982                   "  -m {perf|slow|thorough|quick}  Execute tests according to mode\n"
983                   "  -m {undefined|no-undefined}    Execute tests according to mode\n"
984                   "  -p TESTPATH                    Only start test cases matching TESTPATH\n"
985                   "  -s TESTPATH                    Skip all tests matching TESTPATH\n"
986                   "  -seed=SEEDSTRING               Start tests with random seed SEEDSTRING\n"
987                   "  --debug-log                    debug test logging output\n"
988                   "  -q, --quiet                    Run tests quietly\n"
989                   "  --verbose                      Run tests verbosely\n",
990                   argv[0]);
991           exit (0);
992         }
993     }
994   /* collapse argv */
995   e = 1;
996   for (i = 1; i < argc; i++)
997     if (argv[i])
998       {
999         argv[e++] = argv[i];
1000         if (i >= e)
1001           argv[i] = NULL;
1002       }
1003   *argc_p = e;
1004 }
1005
1006 /**
1007  * g_test_init:
1008  * @argc: Address of the @argc parameter of the main() function.
1009  *        Changed if any arguments were handled.
1010  * @argv: Address of the @argv parameter of main().
1011  *        Any parameters understood by g_test_init() stripped before return.
1012  * @...: %NULL-terminated list of special options. Currently the only
1013  *       defined option is <literal>"no_g_set_prgname"</literal>, which
1014  *       will cause g_test_init() to not call g_set_prgname().
1015  *
1016  * Initialize the GLib testing framework, e.g. by seeding the
1017  * test random number generator, the name for g_get_prgname()
1018  * and parsing test related command line args.
1019  *
1020  * So far, the following arguments are understood:
1021  *
1022  * - <option>-l</option>: List test cases available in a test executable.
1023  * - <option>--seed=SEED</option>: Provide a random seed to reproduce test
1024  *   runs using random numbers.
1025  * - <option>--verbose</option>: Run tests verbosely.
1026  * - <option>-q</option>, <option>--quiet</option>: Run tests quietly.
1027  * - <option>-p PATH</option>: Execute all tests matching the given path.
1028  *   This can also be used to force a test to run that would otherwise
1029  *   be skipped (ie, a test whose name contains "/subprocess").
1030  * - <option>-m {perf|slow|thorough|quick|undefined|no-undefined}</option>: Execute tests according to these test modes:
1031  *
1032  *   <option>perf</option>: Performance tests, may take long and report results.
1033  *
1034  *   <option>slow</option>, <option>thorough</option>: Slow and thorough tests, may take quite long and maximize coverage.
1035  *
1036  *   <option>quick</option>: Quick tests, should run really quickly and give good coverage.
1037  *
1038  *   <option>undefined</option>: Tests for undefined behaviour, may provoke programming errors
1039  *   under g_test_trap_subprocess() or g_test_expect_messages() to check
1040  *   that appropriate assertions or warnings are given
1041  *
1042  *   <option>no-undefined</option>: Avoid tests for undefined behaviour
1043  *
1044  * - <option>--debug-log</option>: Debug test logging output.
1045  *
1046  * Since: 2.16
1047  */
1048 void
1049 g_test_init (int    *argc,
1050              char ***argv,
1051              ...)
1052 {
1053   static char seedstr[4 + 4 * 8 + 1];
1054   va_list args;
1055   gpointer option;
1056   /* make warnings and criticals fatal for all test programs */
1057   GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1058
1059   fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1060   g_log_set_always_fatal (fatal_mask);
1061   /* check caller args */
1062   g_return_if_fail (argc != NULL);
1063   g_return_if_fail (argv != NULL);
1064   g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
1065   mutable_test_config_vars.test_initialized = TRUE;
1066
1067   va_start (args, argv);
1068   while ((option = va_arg (args, char *)))
1069     {
1070       if (g_strcmp0 (option, "no_g_set_prgname") == 0)
1071         no_g_set_prgname = TRUE;
1072     }
1073   va_end (args);
1074
1075   /* setup random seed string */
1076   g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
1077   test_run_seedstr = seedstr;
1078
1079   /* parse args, sets up mode, changes seed, etc. */
1080   parse_args (argc, argv);
1081
1082   if (!g_get_prgname() && !no_g_set_prgname)
1083     g_set_prgname ((*argv)[0]);
1084
1085   /* verify GRand reliability, needed for reliable seeds */
1086   if (1)
1087     {
1088       GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
1089       guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
1090       /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
1091       if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
1092         g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
1093       g_rand_free (rg);
1094     }
1095
1096   /* check rand seed */
1097   test_run_seed (test_run_seedstr);
1098
1099   /* report program start */
1100   g_log_set_default_handler (gtest_default_log_handler, NULL);
1101   g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
1102
1103   test_argv0_dirname = g_path_get_dirname (test_argv0);
1104
1105   /* Make sure we get the real dirname that the test was run from */
1106   if (g_str_has_suffix (test_argv0_dirname, "/.libs"))
1107     {
1108       gchar *tmp;
1109       tmp = g_path_get_dirname (test_argv0_dirname);
1110       g_free (test_argv0_dirname);
1111       test_argv0_dirname = tmp;
1112     }
1113
1114   test_disted_files_dir = g_getenv ("G_TEST_SRCDIR");
1115   if (!test_disted_files_dir)
1116     test_disted_files_dir = test_argv0_dirname;
1117
1118   test_built_files_dir = g_getenv ("G_TEST_BUILDDIR");
1119   if (!test_built_files_dir)
1120     test_built_files_dir = test_argv0_dirname;
1121 }
1122
1123 static void
1124 test_run_seed (const gchar *rseed)
1125 {
1126   guint seed_failed = 0;
1127   if (test_run_rand)
1128     g_rand_free (test_run_rand);
1129   test_run_rand = NULL;
1130   while (strchr (" \t\v\r\n\f", *rseed))
1131     rseed++;
1132   if (strncmp (rseed, "R02S", 4) == 0)  /* seed for random generator 02 (GRand-2.2) */
1133     {
1134       const char *s = rseed + 4;
1135       if (strlen (s) >= 32)             /* require 4 * 8 chars */
1136         {
1137           guint32 seedarray[4];
1138           gchar *p, hexbuf[9] = { 0, };
1139           memcpy (hexbuf, s + 0, 8);
1140           seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
1141           seed_failed += p != NULL && *p != 0;
1142           memcpy (hexbuf, s + 8, 8);
1143           seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
1144           seed_failed += p != NULL && *p != 0;
1145           memcpy (hexbuf, s + 16, 8);
1146           seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
1147           seed_failed += p != NULL && *p != 0;
1148           memcpy (hexbuf, s + 24, 8);
1149           seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
1150           seed_failed += p != NULL && *p != 0;
1151           if (!seed_failed)
1152             {
1153               test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
1154               return;
1155             }
1156         }
1157     }
1158   g_error ("Unknown or invalid random seed: %s", rseed);
1159 }
1160
1161 /**
1162  * g_test_rand_int:
1163  *
1164  * Get a reproducible random integer number.
1165  *
1166  * The random numbers generated by the g_test_rand_*() family of functions
1167  * change with every new test program start, unless the --seed option is
1168  * given when starting test programs.
1169  *
1170  * For individual test cases however, the random number generator is
1171  * reseeded, to avoid dependencies between tests and to make --seed
1172  * effective for all test cases.
1173  *
1174  * Returns: a random number from the seeded random number generator.
1175  *
1176  * Since: 2.16
1177  */
1178 gint32
1179 g_test_rand_int (void)
1180 {
1181   return g_rand_int (test_run_rand);
1182 }
1183
1184 /**
1185  * g_test_rand_int_range:
1186  * @begin: the minimum value returned by this function
1187  * @end:   the smallest value not to be returned by this function
1188  *
1189  * Get a reproducible random integer number out of a specified range,
1190  * see g_test_rand_int() for details on test case random numbers.
1191  *
1192  * Returns: a number with @begin <= number < @end.
1193  * 
1194  * Since: 2.16
1195  */
1196 gint32
1197 g_test_rand_int_range (gint32          begin,
1198                        gint32          end)
1199 {
1200   return g_rand_int_range (test_run_rand, begin, end);
1201 }
1202
1203 /**
1204  * g_test_rand_double:
1205  *
1206  * Get a reproducible random floating point number,
1207  * see g_test_rand_int() for details on test case random numbers.
1208  *
1209  * Returns: a random number from the seeded random number generator.
1210  *
1211  * Since: 2.16
1212  */
1213 double
1214 g_test_rand_double (void)
1215 {
1216   return g_rand_double (test_run_rand);
1217 }
1218
1219 /**
1220  * g_test_rand_double_range:
1221  * @range_start: the minimum value returned by this function
1222  * @range_end: the minimum value not returned by this function
1223  *
1224  * Get a reproducible random floating pointer number out of a specified range,
1225  * see g_test_rand_int() for details on test case random numbers.
1226  *
1227  * Returns: a number with @range_start <= number < @range_end.
1228  *
1229  * Since: 2.16
1230  */
1231 double
1232 g_test_rand_double_range (double          range_start,
1233                           double          range_end)
1234 {
1235   return g_rand_double_range (test_run_rand, range_start, range_end);
1236 }
1237
1238 /**
1239  * g_test_timer_start:
1240  *
1241  * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1242  * to be done. Call this function again to restart the timer.
1243  *
1244  * Since: 2.16
1245  */
1246 void
1247 g_test_timer_start (void)
1248 {
1249   if (!test_user_timer)
1250     test_user_timer = g_timer_new();
1251   test_user_stamp = 0;
1252   g_timer_start (test_user_timer);
1253 }
1254
1255 /**
1256  * g_test_timer_elapsed:
1257  *
1258  * Get the time since the last start of the timer with g_test_timer_start().
1259  *
1260  * Returns: the time since the last start of the timer, as a double
1261  *
1262  * Since: 2.16
1263  */
1264 double
1265 g_test_timer_elapsed (void)
1266 {
1267   test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1268   return test_user_stamp;
1269 }
1270
1271 /**
1272  * g_test_timer_last:
1273  *
1274  * Report the last result of g_test_timer_elapsed().
1275  *
1276  * Returns: the last result of g_test_timer_elapsed(), as a double
1277  *
1278  * Since: 2.16
1279  */
1280 double
1281 g_test_timer_last (void)
1282 {
1283   return test_user_stamp;
1284 }
1285
1286 /**
1287  * g_test_minimized_result:
1288  * @minimized_quantity: the reported value
1289  * @format: the format string of the report message
1290  * @...: arguments to pass to the printf() function
1291  *
1292  * Report the result of a performance or measurement test.
1293  * The test should generally strive to minimize the reported
1294  * quantities (smaller values are better than larger ones),
1295  * this and @minimized_quantity can determine sorting
1296  * order for test result reports.
1297  *
1298  * Since: 2.16
1299  */
1300 void
1301 g_test_minimized_result (double          minimized_quantity,
1302                          const char     *format,
1303                          ...)
1304 {
1305   long double largs = minimized_quantity;
1306   gchar *buffer;
1307   va_list args;
1308
1309   va_start (args, format);
1310   buffer = g_strdup_vprintf (format, args);
1311   va_end (args);
1312
1313   g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1314   g_free (buffer);
1315 }
1316
1317 /**
1318  * g_test_maximized_result:
1319  * @maximized_quantity: the reported value
1320  * @format: the format string of the report message
1321  * @...: arguments to pass to the printf() function
1322  *
1323  * Report the result of a performance or measurement test.
1324  * The test should generally strive to maximize the reported
1325  * quantities (larger values are better than smaller ones),
1326  * this and @maximized_quantity can determine sorting
1327  * order for test result reports.
1328  *
1329  * Since: 2.16
1330  */
1331 void
1332 g_test_maximized_result (double          maximized_quantity,
1333                          const char     *format,
1334                          ...)
1335 {
1336   long double largs = maximized_quantity;
1337   gchar *buffer;
1338   va_list args;
1339
1340   va_start (args, format);
1341   buffer = g_strdup_vprintf (format, args);
1342   va_end (args);
1343
1344   g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1345   g_free (buffer);
1346 }
1347
1348 /**
1349  * g_test_message:
1350  * @format: the format string
1351  * @...:    printf-like arguments to @format
1352  *
1353  * Add a message to the test report.
1354  *
1355  * Since: 2.16
1356  */
1357 void
1358 g_test_message (const char *format,
1359                 ...)
1360 {
1361   gchar *buffer;
1362   va_list args;
1363
1364   va_start (args, format);
1365   buffer = g_strdup_vprintf (format, args);
1366   va_end (args);
1367
1368   g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1369   g_free (buffer);
1370 }
1371
1372 /**
1373  * g_test_bug_base:
1374  * @uri_pattern: the base pattern for bug URIs
1375  *
1376  * Specify the base URI for bug reports.
1377  *
1378  * The base URI is used to construct bug report messages for
1379  * g_test_message() when g_test_bug() is called.
1380  * Calling this function outside of a test case sets the
1381  * default base URI for all test cases. Calling it from within
1382  * a test case changes the base URI for the scope of the test
1383  * case only.
1384  * Bug URIs are constructed by appending a bug specific URI
1385  * portion to @uri_pattern, or by replacing the special string
1386  * '\%s' within @uri_pattern if that is present.
1387  *
1388  * Since: 2.16
1389  */
1390 void
1391 g_test_bug_base (const char *uri_pattern)
1392 {
1393   g_free (test_uri_base);
1394   test_uri_base = g_strdup (uri_pattern);
1395 }
1396
1397 /**
1398  * g_test_bug:
1399  * @bug_uri_snippet: Bug specific bug tracker URI portion.
1400  *
1401  * This function adds a message to test reports that
1402  * associates a bug URI with a test case.
1403  * Bug URIs are constructed from a base URI set with g_test_bug_base()
1404  * and @bug_uri_snippet.
1405  *
1406  * Since: 2.16
1407  */
1408 void
1409 g_test_bug (const char *bug_uri_snippet)
1410 {
1411   char *c;
1412
1413   g_return_if_fail (test_uri_base != NULL);
1414   g_return_if_fail (bug_uri_snippet != NULL);
1415
1416   c = strstr (test_uri_base, "%s");
1417   if (c)
1418     {
1419       char *b = g_strndup (test_uri_base, c - test_uri_base);
1420       char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1421       g_free (b);
1422       g_test_message ("Bug Reference: %s", s);
1423       g_free (s);
1424     }
1425   else
1426     g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1427 }
1428
1429 /**
1430  * g_test_get_root:
1431  *
1432  * Get the toplevel test suite for the test path API.
1433  *
1434  * Returns: the toplevel #GTestSuite
1435  *
1436  * Since: 2.16
1437  */
1438 GTestSuite*
1439 g_test_get_root (void)
1440 {
1441   if (!test_suite_root)
1442     {
1443       test_suite_root = g_test_create_suite ("root");
1444       g_free (test_suite_root->name);
1445       test_suite_root->name = g_strdup ("");
1446     }
1447
1448   return test_suite_root;
1449 }
1450
1451 /**
1452  * g_test_run:
1453  *
1454  * Runs all tests under the toplevel suite which can be retrieved
1455  * with g_test_get_root(). Similar to g_test_run_suite(), the test
1456  * cases to be run are filtered according to
1457  * test path arguments (-p <replaceable>testpath</replaceable>) as 
1458  * parsed by g_test_init().
1459  * g_test_run_suite() or g_test_run() may only be called once
1460  * in a program.
1461  *
1462  * In general, the tests and sub-suites within each suite are run in
1463  * the order in which they are defined. However, note that prior to
1464  * GLib 2.36, there was a bug in the <literal>g_test_add_*</literal>
1465  * functions which caused them to create multiple suites with the same
1466  * name, meaning that if you created tests "/foo/simple",
1467  * "/bar/simple", and "/foo/using-bar" in that order, they would get
1468  * run in that order (since g_test_run() would run the first "/foo"
1469  * suite, then the "/bar" suite, then the second "/foo" suite). As of
1470  * 2.36, this bug is fixed, and adding the tests in that order would
1471  * result in a running order of "/foo/simple", "/foo/using-bar",
1472  * "/bar/simple". If this new ordering is sub-optimal (because it puts
1473  * more-complicated tests before simpler ones, making it harder to
1474  * figure out exactly what has failed), you can fix it by changing the
1475  * test paths to group tests by suite in a way that will result in the
1476  * desired running order. Eg, "/simple/foo", "/simple/bar",
1477  * "/complex/foo-using-bar".
1478  *
1479  * However, you should never make the actual result of a test depend
1480  * on the order that tests are run in. If you need to ensure that some
1481  * particular code runs before or after a given test case, use
1482  * g_test_add(), which lets you specify setup and teardown functions.
1483  *
1484  * Returns: 0 on success, 1 on failure (assuming it returns at all),
1485  *   77 if all tests were skipped with g_test_skip().
1486  *
1487  * Since: 2.16
1488  */
1489 int
1490 g_test_run (void)
1491 {
1492   if (g_test_run_suite (g_test_get_root()) != 0)
1493     return 1;
1494
1495   if (test_run_count > 0 && test_run_count == test_skipped_count)
1496     return 77;
1497   else
1498     return 0;
1499 }
1500
1501 /**
1502  * g_test_create_case:
1503  * @test_name:     the name for the test case
1504  * @data_size:     the size of the fixture data structure
1505  * @test_data:     test data argument for the test functions
1506  * @data_setup:    the function to set up the fixture data
1507  * @data_test:     the actual test function
1508  * @data_teardown: the function to teardown the fixture data
1509  *
1510  * Create a new #GTestCase, named @test_name, this API is fairly
1511  * low level, calling g_test_add() or g_test_add_func() is preferable.
1512  * When this test is executed, a fixture structure of size @data_size
1513  * will be allocated and filled with 0s. Then @data_setup is called
1514  * to initialize the fixture. After fixture setup, the actual test
1515  * function @data_test is called. Once the test run completed, the
1516  * fixture structure is torn down  by calling @data_teardown and
1517  * after that the memory is released.
1518  *
1519  * Splitting up a test run into fixture setup, test function and
1520  * fixture teardown is most usful if the same fixture is used for
1521  * multiple tests. In this cases, g_test_create_case() will be
1522  * called with the same fixture, but varying @test_name and
1523  * @data_test arguments.
1524  *
1525  * Returns: a newly allocated #GTestCase.
1526  *
1527  * Since: 2.16
1528  */
1529 GTestCase*
1530 g_test_create_case (const char       *test_name,
1531                     gsize             data_size,
1532                     gconstpointer     test_data,
1533                     GTestFixtureFunc  data_setup,
1534                     GTestFixtureFunc  data_test,
1535                     GTestFixtureFunc  data_teardown)
1536 {
1537   GTestCase *tc;
1538
1539   g_return_val_if_fail (test_name != NULL, NULL);
1540   g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1541   g_return_val_if_fail (test_name[0] != 0, NULL);
1542   g_return_val_if_fail (data_test != NULL, NULL);
1543
1544   tc = g_slice_new0 (GTestCase);
1545   tc->name = g_strdup (test_name);
1546   tc->test_data = (gpointer) test_data;
1547   tc->fixture_size = data_size;
1548   tc->fixture_setup = (void*) data_setup;
1549   tc->fixture_test = (void*) data_test;
1550   tc->fixture_teardown = (void*) data_teardown;
1551
1552   return tc;
1553 }
1554
1555 static gint
1556 find_suite (gconstpointer l, gconstpointer s)
1557 {
1558   const GTestSuite *suite = l;
1559   const gchar *str = s;
1560
1561   return strcmp (suite->name, str);
1562 }
1563
1564 /**
1565  * GTestFixtureFunc:
1566  * @fixture: the test fixture
1567  * @user_data: the data provided when registering the test
1568  *
1569  * The type used for functions that operate on test fixtures.  This is
1570  * used for the fixture setup and teardown functions as well as for the
1571  * testcases themselves.
1572  *
1573  * @user_data is a pointer to the data that was given when registering
1574  * the test case.
1575  *
1576  * @fixture will be a pointer to the area of memory allocated by the
1577  * test framework, of the size requested.  If the requested size was
1578  * zero then @fixture will be equal to @user_data.
1579  *
1580  * Since: 2.28
1581  */
1582 void
1583 g_test_add_vtable (const char       *testpath,
1584                    gsize             data_size,
1585                    gconstpointer     test_data,
1586                    GTestFixtureFunc  data_setup,
1587                    GTestFixtureFunc  fixture_test_func,
1588                    GTestFixtureFunc  data_teardown)
1589 {
1590   gchar **segments;
1591   guint ui;
1592   GTestSuite *suite;
1593
1594   g_return_if_fail (testpath != NULL);
1595   g_return_if_fail (g_path_is_absolute (testpath));
1596   g_return_if_fail (fixture_test_func != NULL);
1597
1598   if (g_slist_find_custom (test_paths_skipped, testpath, (GCompareFunc)g_strcmp0))
1599     return;
1600
1601   suite = g_test_get_root();
1602   segments = g_strsplit (testpath, "/", -1);
1603   for (ui = 0; segments[ui] != NULL; ui++)
1604     {
1605       const char *seg = segments[ui];
1606       gboolean islast = segments[ui + 1] == NULL;
1607       if (islast && !seg[0])
1608         g_error ("invalid test case path: %s", testpath);
1609       else if (!seg[0])
1610         continue;       /* initial or duplicate slash */
1611       else if (!islast)
1612         {
1613           GSList *l;
1614           GTestSuite *csuite;
1615           l = g_slist_find_custom (suite->suites, seg, find_suite);
1616           if (l)
1617             {
1618               csuite = l->data;
1619             }
1620           else
1621             {
1622               csuite = g_test_create_suite (seg);
1623               g_test_suite_add_suite (suite, csuite);
1624             }
1625           suite = csuite;
1626         }
1627       else /* islast */
1628         {
1629           GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1630           g_test_suite_add (suite, tc);
1631         }
1632     }
1633   g_strfreev (segments);
1634 }
1635
1636 /**
1637  * g_test_fail:
1638  *
1639  * Indicates that a test failed. This function can be called
1640  * multiple times from the same test. You can use this function
1641  * if your test failed in a recoverable way.
1642  * 
1643  * Do not use this function if the failure of a test could cause
1644  * other tests to malfunction.
1645  *
1646  * Calling this function will not stop the test from running, you
1647  * need to return from the test function yourself. So you can
1648  * produce additional diagnostic messages or even continue running
1649  * the test.
1650  *
1651  * If not called from inside a test, this function does nothing.
1652  *
1653  * Since: 2.30
1654  **/
1655 void
1656 g_test_fail (void)
1657 {
1658   test_run_success = G_TEST_RUN_FAILURE;
1659 }
1660
1661 /**
1662  * g_test_incomplete:
1663  * @msg: (allow-none): explanation
1664  *
1665  * Indicates that a test failed because of some incomplete
1666  * functionality. This function can be called multiple times
1667  * from the same test.
1668  *
1669  * Calling this function will not stop the test from running, you
1670  * need to return from the test function yourself. So you can
1671  * produce additional diagnostic messages or even continue running
1672  * the test.
1673  *
1674  * If not called from inside a test, this function does nothing.
1675  *
1676  * Since: 2.38
1677  */
1678 void
1679 g_test_incomplete (const gchar *msg)
1680 {
1681   test_run_success = G_TEST_RUN_INCOMPLETE;
1682   g_free (test_run_msg);
1683   test_run_msg = g_strdup (msg);
1684 }
1685
1686 /**
1687  * g_test_skip:
1688  * @msg: (allow-none): explanation
1689  *
1690  * Indicates that a test was skipped.
1691  *
1692  * Calling this function will not stop the test from running, you
1693  * need to return from the test function yourself. So you can
1694  * produce additional diagnostic messages or even continue running
1695  * the test.
1696  *
1697  * If not called from inside a test, this function does nothing.
1698  *
1699  * Since: 2.38
1700  */
1701 void
1702 g_test_skip (const gchar *msg)
1703 {
1704   test_run_success = G_TEST_RUN_SKIPPED;
1705   g_free (test_run_msg);
1706   test_run_msg = g_strdup (msg);
1707 }
1708
1709 /**
1710  * g_test_failed:
1711  *
1712  * Returns whether a test has already failed. This will
1713  * be the case when g_test_fail(), g_test_incomplete()
1714  * or g_test_skip() have been called, but also if an
1715  * assertion has failed.
1716  *
1717  * This can be useful to return early from a test if
1718  * continuing after a failed assertion might be harmful.
1719  *
1720  * The return value of this function is only meaningful
1721  * if it is called from inside a test function.
1722  *
1723  * Returns: %TRUE if the test has failed
1724  *
1725  * Since: 2.38
1726  */
1727 gboolean
1728 g_test_failed (void)
1729 {
1730   return test_run_success != G_TEST_RUN_SUCCESS;
1731 }
1732
1733 /**
1734  * g_test_set_nonfatal_assertions:
1735  *
1736  * Changes the behaviour of g_assert_cmpstr(), g_assert_cmpint(),
1737  * g_assert_cmpuint(), g_assert_cmphex(), g_assert_cmpfloat(),
1738  * g_assert_true(), g_assert_false(), g_assert_null(), g_assert_no_error(),
1739  * g_assert_error(), g_test_assert_expected_messages() and the various
1740  * g_test_trap_assert_*() macros to not abort to program, but instead
1741  * call g_test_fail() and continue. (This also changes the behavior of
1742  * g_test_fail() so that it will not cause the test program to abort
1743  * after completing the failed test.)
1744  *
1745  * Note that the g_assert_not_reached() and g_assert() are not
1746  * affected by this.
1747  *
1748  * This function can only be called after g_test_init().
1749  *
1750  * Since: 2.38
1751  */
1752 void
1753 g_test_set_nonfatal_assertions (void)
1754 {
1755   if (!g_test_config_vars->test_initialized)
1756     g_error ("g_test_set_nonfatal_assertions called without g_test_init");
1757   test_nonfatal_assertions = TRUE;
1758   test_mode_fatal = FALSE;
1759 }
1760
1761 /**
1762  * GTestFunc:
1763  *
1764  * The type used for test case functions.
1765  *
1766  * Since: 2.28
1767  */
1768
1769 /**
1770  * g_test_add_func:
1771  * @testpath:   /-separated test case path name for the test.
1772  * @test_func:  The test function to invoke for this test.
1773  *
1774  * Create a new test case, similar to g_test_create_case(). However
1775  * the test is assumed to use no fixture, and test suites are automatically
1776  * created on the fly and added to the root fixture, based on the
1777  * slash-separated portions of @testpath.
1778  *
1779  * If @testpath includes the component "subprocess" anywhere in it,
1780  * the test will be skipped by default, and only run if explicitly
1781  * required via the <option>-p</option> command-line option or
1782  * g_test_trap_subprocess().
1783  *
1784  * Since: 2.16
1785  */
1786 void
1787 g_test_add_func (const char *testpath,
1788                  GTestFunc   test_func)
1789 {
1790   g_return_if_fail (testpath != NULL);
1791   g_return_if_fail (testpath[0] == '/');
1792   g_return_if_fail (test_func != NULL);
1793   g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1794 }
1795
1796 /**
1797  * GTestDataFunc:
1798  * @user_data: the data provided when registering the test
1799  *
1800  * The type used for test case functions that take an extra pointer
1801  * argument.
1802  *
1803  * Since: 2.28
1804  */
1805
1806 /**
1807  * g_test_add_data_func:
1808  * @testpath:   /-separated test case path name for the test.
1809  * @test_data:  Test data argument for the test function.
1810  * @test_func:  The test function to invoke for this test.
1811  *
1812  * Create a new test case, similar to g_test_create_case(). However
1813  * the test is assumed to use no fixture, and test suites are automatically
1814  * created on the fly and added to the root fixture, based on the
1815  * slash-separated portions of @testpath. The @test_data argument
1816  * will be passed as first argument to @test_func.
1817  *
1818  * If @testpath includes the component "subprocess" anywhere in it,
1819  * the test will be skipped by default, and only run if explicitly
1820  * required via the <option>-p</option> command-line option or
1821  * g_test_trap_subprocess().
1822  *
1823  * Since: 2.16
1824  */
1825 void
1826 g_test_add_data_func (const char     *testpath,
1827                       gconstpointer   test_data,
1828                       GTestDataFunc   test_func)
1829 {
1830   g_return_if_fail (testpath != NULL);
1831   g_return_if_fail (testpath[0] == '/');
1832   g_return_if_fail (test_func != NULL);
1833
1834   g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1835 }
1836
1837 /**
1838  * g_test_add_data_func_full:
1839  * @testpath: /-separated test case path name for the test.
1840  * @test_data: Test data argument for the test function.
1841  * @test_func: The test function to invoke for this test.
1842  * @data_free_func: #GDestroyNotify for @test_data.
1843  *
1844  * Create a new test case, as with g_test_add_data_func(), but freeing
1845  * @test_data after the test run is complete.
1846  *
1847  * Since: 2.34
1848  */
1849 void
1850 g_test_add_data_func_full (const char     *testpath,
1851                            gpointer        test_data,
1852                            GTestDataFunc   test_func,
1853                            GDestroyNotify  data_free_func)
1854 {
1855   g_return_if_fail (testpath != NULL);
1856   g_return_if_fail (testpath[0] == '/');
1857   g_return_if_fail (test_func != NULL);
1858
1859   g_test_add_vtable (testpath, 0, test_data, NULL,
1860                      (GTestFixtureFunc) test_func,
1861                      (GTestFixtureFunc) data_free_func);
1862 }
1863
1864 static gboolean
1865 g_test_suite_case_exists (GTestSuite *suite,
1866                           const char *test_path)
1867 {
1868   GSList *iter;
1869   char *slash;
1870   GTestCase *tc;
1871
1872   test_path++;
1873   slash = strchr (test_path, '/');
1874
1875   if (slash)
1876     {
1877       for (iter = suite->suites; iter; iter = iter->next)
1878         {
1879           GTestSuite *child_suite = iter->data;
1880
1881           if (!strncmp (child_suite->name, test_path, slash - test_path))
1882             if (g_test_suite_case_exists (child_suite, slash))
1883               return TRUE;
1884         }
1885     }
1886   else
1887     {
1888       for (iter = suite->cases; iter; iter = iter->next)
1889         {
1890           tc = iter->data;
1891           if (!strcmp (tc->name, test_path))
1892             return TRUE;
1893         }
1894     }
1895
1896   return FALSE;
1897 }
1898
1899 /**
1900  * g_test_create_suite:
1901  * @suite_name: a name for the suite
1902  *
1903  * Create a new test suite with the name @suite_name.
1904  *
1905  * Returns: A newly allocated #GTestSuite instance.
1906  *
1907  * Since: 2.16
1908  */
1909 GTestSuite*
1910 g_test_create_suite (const char *suite_name)
1911 {
1912   GTestSuite *ts;
1913   g_return_val_if_fail (suite_name != NULL, NULL);
1914   g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1915   g_return_val_if_fail (suite_name[0] != 0, NULL);
1916   ts = g_slice_new0 (GTestSuite);
1917   ts->name = g_strdup (suite_name);
1918   return ts;
1919 }
1920
1921 /**
1922  * g_test_suite_add:
1923  * @suite: a #GTestSuite
1924  * @test_case: a #GTestCase
1925  *
1926  * Adds @test_case to @suite.
1927  *
1928  * Since: 2.16
1929  */
1930 void
1931 g_test_suite_add (GTestSuite     *suite,
1932                   GTestCase      *test_case)
1933 {
1934   g_return_if_fail (suite != NULL);
1935   g_return_if_fail (test_case != NULL);
1936
1937   suite->cases = g_slist_prepend (suite->cases, test_case);
1938 }
1939
1940 /**
1941  * g_test_suite_add_suite:
1942  * @suite:       a #GTestSuite
1943  * @nestedsuite: another #GTestSuite
1944  *
1945  * Adds @nestedsuite to @suite.
1946  *
1947  * Since: 2.16
1948  */
1949 void
1950 g_test_suite_add_suite (GTestSuite     *suite,
1951                         GTestSuite     *nestedsuite)
1952 {
1953   g_return_if_fail (suite != NULL);
1954   g_return_if_fail (nestedsuite != NULL);
1955
1956   suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1957 }
1958
1959 /**
1960  * g_test_queue_free:
1961  * @gfree_pointer: the pointer to be stored.
1962  *
1963  * Enqueue a pointer to be released with g_free() during the next
1964  * teardown phase. This is equivalent to calling g_test_queue_destroy()
1965  * with a destroy callback of g_free().
1966  *
1967  * Since: 2.16
1968  */
1969 void
1970 g_test_queue_free (gpointer gfree_pointer)
1971 {
1972   if (gfree_pointer)
1973     g_test_queue_destroy (g_free, gfree_pointer);
1974 }
1975
1976 /**
1977  * g_test_queue_destroy:
1978  * @destroy_func:       Destroy callback for teardown phase.
1979  * @destroy_data:       Destroy callback data.
1980  *
1981  * This function enqueus a callback @destroy_func to be executed
1982  * during the next test case teardown phase. This is most useful
1983  * to auto destruct allocted test resources at the end of a test run.
1984  * Resources are released in reverse queue order, that means enqueueing
1985  * callback A before callback B will cause B() to be called before
1986  * A() during teardown.
1987  *
1988  * Since: 2.16
1989  */
1990 void
1991 g_test_queue_destroy (GDestroyNotify destroy_func,
1992                       gpointer       destroy_data)
1993 {
1994   DestroyEntry *dentry;
1995
1996   g_return_if_fail (destroy_func != NULL);
1997
1998   dentry = g_slice_new0 (DestroyEntry);
1999   dentry->destroy_func = destroy_func;
2000   dentry->destroy_data = destroy_data;
2001   dentry->next = test_destroy_queue;
2002   test_destroy_queue = dentry;
2003 }
2004
2005 static gboolean
2006 test_case_run (GTestCase *tc)
2007 {
2008   gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
2009   GSList **old_free_list, *filename_free_list = NULL;
2010   gboolean success = G_TEST_RUN_SUCCESS;
2011
2012   old_free_list = test_filename_free_list;
2013   test_filename_free_list = &filename_free_list;
2014
2015   test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
2016   if (strstr (test_run_name, "/subprocess"))
2017     {
2018       GSList *iter;
2019       gboolean found = FALSE;
2020
2021       for (iter = test_paths; iter; iter = iter->next)
2022         {
2023           if (!strcmp (test_run_name, iter->data))
2024             {
2025               found = TRUE;
2026               break;
2027             }
2028         }
2029
2030       if (!found)
2031         {
2032           if (g_test_verbose ())
2033             g_print ("GTest: skipping: %s\n", test_run_name);
2034           goto out;
2035         }
2036     }
2037
2038   if (++test_run_count <= test_startup_skip_count)
2039     g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
2040   else if (test_run_list)
2041     {
2042       g_print ("%s\n", test_run_name);
2043       g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
2044     }
2045   else
2046     {
2047       GTimer *test_run_timer = g_timer_new();
2048       long double largs[3];
2049       void *fixture;
2050       g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
2051       test_run_forks = 0;
2052       test_run_success = G_TEST_RUN_SUCCESS;
2053       g_clear_pointer (&test_run_msg, g_free);
2054       g_test_log_set_fatal_handler (NULL, NULL);
2055       g_timer_start (test_run_timer);
2056       fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
2057       test_run_seed (test_run_seedstr);
2058       if (tc->fixture_setup)
2059         tc->fixture_setup (fixture, tc->test_data);
2060       tc->fixture_test (fixture, tc->test_data);
2061       test_trap_clear();
2062       while (test_destroy_queue)
2063         {
2064           DestroyEntry *dentry = test_destroy_queue;
2065           test_destroy_queue = dentry->next;
2066           dentry->destroy_func (dentry->destroy_data);
2067           g_slice_free (DestroyEntry, dentry);
2068         }
2069       if (tc->fixture_teardown)
2070         tc->fixture_teardown (fixture, tc->test_data);
2071       if (tc->fixture_size)
2072         g_free (fixture);
2073       g_timer_stop (test_run_timer);
2074       success = test_run_success;
2075       test_run_success = G_TEST_RUN_FAILURE;
2076       largs[0] = success; /* OK */
2077       largs[1] = test_run_forks;
2078       largs[2] = g_timer_elapsed (test_run_timer, NULL);
2079       g_test_log (G_TEST_LOG_STOP_CASE, test_run_name, test_run_msg, G_N_ELEMENTS (largs), largs);
2080       g_clear_pointer (&test_run_msg, g_free);
2081       g_timer_destroy (test_run_timer);
2082     }
2083
2084  out:
2085   g_slist_free_full (filename_free_list, g_free);
2086   test_filename_free_list = old_free_list;
2087   g_free (test_run_name);
2088   test_run_name = old_name;
2089   g_free (test_uri_base);
2090   test_uri_base = old_base;
2091
2092   return (success == G_TEST_RUN_SUCCESS ||
2093           success == G_TEST_RUN_SKIPPED);
2094 }
2095
2096 static int
2097 g_test_run_suite_internal (GTestSuite *suite,
2098                            const char *path)
2099 {
2100   guint n_bad = 0, l;
2101   gchar *rest, *old_name = test_run_name;
2102   GSList *slist, *reversed;
2103
2104   g_return_val_if_fail (suite != NULL, -1);
2105
2106   g_test_log (G_TEST_LOG_START_SUITE, suite->name, NULL, 0, NULL);
2107
2108   while (path[0] == '/')
2109     path++;
2110   l = strlen (path);
2111   rest = strchr (path, '/');
2112   l = rest ? MIN (l, rest - path) : l;
2113   test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
2114   reversed = g_slist_reverse (g_slist_copy (suite->cases));
2115   for (slist = reversed; slist; slist = slist->next)
2116     {
2117       GTestCase *tc = slist->data;
2118       guint n = l ? strlen (tc->name) : 0;
2119       if (l == n && !rest && strncmp (path, tc->name, n) == 0)
2120         {
2121           if (!test_case_run (tc))
2122             n_bad++;
2123         }
2124     }
2125   g_slist_free (reversed);
2126   reversed = g_slist_reverse (g_slist_copy (suite->suites));
2127   for (slist = reversed; slist; slist = slist->next)
2128     {
2129       GTestSuite *ts = slist->data;
2130       guint n = l ? strlen (ts->name) : 0;
2131       if (l == n && strncmp (path, ts->name, n) == 0)
2132         n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
2133     }
2134   g_slist_free (reversed);
2135   g_free (test_run_name);
2136   test_run_name = old_name;
2137
2138   g_test_log (G_TEST_LOG_STOP_SUITE, suite->name, NULL, 0, NULL);
2139
2140   return n_bad;
2141 }
2142
2143 /**
2144  * g_test_run_suite:
2145  * @suite: a #GTestSuite
2146  *
2147  * Execute the tests within @suite and all nested #GTestSuites.
2148  * The test suites to be executed are filtered according to
2149  * test path arguments (-p <replaceable>testpath</replaceable>) 
2150  * as parsed by g_test_init(). See the g_test_run() documentation
2151  * for more information on the order that tests are run in.
2152  *
2153  * g_test_run_suite() or g_test_run() may only be called once
2154  * in a program.
2155  *
2156  * Returns: 0 on success
2157  *
2158  * Since: 2.16
2159  */
2160 int
2161 g_test_run_suite (GTestSuite *suite)
2162 {
2163   GSList *my_test_paths;
2164   guint n_bad = 0;
2165
2166   g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
2167   g_return_val_if_fail (g_test_run_once == TRUE, -1);
2168
2169   g_test_run_once = FALSE;
2170
2171   if (test_paths)
2172     my_test_paths = g_slist_copy (test_paths);
2173   else
2174     my_test_paths = g_slist_prepend (NULL, "");
2175
2176   while (my_test_paths)
2177     {
2178       const char *rest, *path = my_test_paths->data;
2179       guint l, n = strlen (suite->name);
2180       my_test_paths = g_slist_delete_link (my_test_paths, my_test_paths);
2181       while (path[0] == '/')
2182         path++;
2183       if (!n) /* root suite, run unconditionally */
2184         {
2185           n_bad += g_test_run_suite_internal (suite, path);
2186           continue;
2187         }
2188       /* regular suite, match path */
2189       rest = strchr (path, '/');
2190       l = strlen (path);
2191       l = rest ? MIN (l, rest - path) : l;
2192       if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
2193         n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
2194     }
2195
2196   return n_bad;
2197 }
2198
2199 static void
2200 gtest_default_log_handler (const gchar    *log_domain,
2201                            GLogLevelFlags  log_level,
2202                            const gchar    *message,
2203                            gpointer        unused_data)
2204 {
2205   const gchar *strv[16];
2206   gboolean fatal = FALSE;
2207   gchar *msg;
2208   guint i = 0;
2209
2210   if (log_domain)
2211     {
2212       strv[i++] = log_domain;
2213       strv[i++] = "-";
2214     }
2215   if (log_level & G_LOG_FLAG_FATAL)
2216     {
2217       strv[i++] = "FATAL-";
2218       fatal = TRUE;
2219     }
2220   if (log_level & G_LOG_FLAG_RECURSION)
2221     strv[i++] = "RECURSIVE-";
2222   if (log_level & G_LOG_LEVEL_ERROR)
2223     strv[i++] = "ERROR";
2224   if (log_level & G_LOG_LEVEL_CRITICAL)
2225     strv[i++] = "CRITICAL";
2226   if (log_level & G_LOG_LEVEL_WARNING)
2227     strv[i++] = "WARNING";
2228   if (log_level & G_LOG_LEVEL_MESSAGE)
2229     strv[i++] = "MESSAGE";
2230   if (log_level & G_LOG_LEVEL_INFO)
2231     strv[i++] = "INFO";
2232   if (log_level & G_LOG_LEVEL_DEBUG)
2233     strv[i++] = "DEBUG";
2234   strv[i++] = ": ";
2235   strv[i++] = message;
2236   strv[i++] = NULL;
2237
2238   msg = g_strjoinv ("", (gchar**) strv);
2239   g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
2240   g_log_default_handler (log_domain, log_level, message, unused_data);
2241
2242   g_free (msg);
2243 }
2244
2245 void
2246 g_assertion_message (const char     *domain,
2247                      const char     *file,
2248                      int             line,
2249                      const char     *func,
2250                      const char     *message)
2251 {
2252   char lstr[32];
2253   char *s;
2254
2255   if (!message)
2256     message = "code should not be reached";
2257   g_snprintf (lstr, 32, "%d", line);
2258   s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
2259                    "ERROR:", file, ":", lstr, ":",
2260                    func, func[0] ? ":" : "",
2261                    " ", message, NULL);
2262   g_printerr ("**\n%s\n", s);
2263
2264   g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
2265
2266   if (test_nonfatal_assertions)
2267     {
2268       g_free (s);
2269       g_test_fail ();
2270       return;
2271     }
2272
2273   /* store assertion message in global variable, so that it can be found in a
2274    * core dump */
2275   if (__glib_assert_msg != NULL)
2276     /* free the old one */
2277     free (__glib_assert_msg);
2278   __glib_assert_msg = (char*) malloc (strlen (s) + 1);
2279   strcpy (__glib_assert_msg, s);
2280
2281   g_free (s);
2282
2283   if (test_in_subprocess)
2284     {
2285       /* If this is a test case subprocess then it probably hit this
2286        * assertion on purpose, so just exit() rather than abort()ing,
2287        * to avoid triggering any system crash-reporting daemon.
2288        */
2289       _exit (1);
2290     }
2291   else
2292     abort ();
2293 }
2294
2295 void
2296 g_assertion_message_expr (const char     *domain,
2297                           const char     *file,
2298                           int             line,
2299                           const char     *func,
2300                           const char     *expr)
2301 {
2302   char *s;
2303   if (!expr)
2304     s = g_strdup ("code should not be reached");
2305   else
2306     s = g_strconcat ("assertion failed: (", expr, ")", NULL);
2307   g_assertion_message (domain, file, line, func, s);
2308   g_free (s);
2309
2310   /* Normally g_assertion_message() won't return, but we need this for
2311    * when test_nonfatal_assertions is set, since
2312    * g_assertion_message_expr() is used for always-fatal assertions.
2313    */
2314   if (test_in_subprocess)
2315     _exit (1);
2316   else
2317     abort ();
2318 }
2319
2320 void
2321 g_assertion_message_cmpnum (const char     *domain,
2322                             const char     *file,
2323                             int             line,
2324                             const char     *func,
2325                             const char     *expr,
2326                             long double     arg1,
2327                             const char     *cmp,
2328                             long double     arg2,
2329                             char            numtype)
2330 {
2331   char *s = NULL;
2332
2333   switch (numtype)
2334     {
2335     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;
2336     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;
2337     case 'f':   s = g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr, (double) arg1, cmp, (double) arg2); break;
2338       /* ideally use: floats=%.7g double=%.17g */
2339     }
2340   g_assertion_message (domain, file, line, func, s);
2341   g_free (s);
2342 }
2343
2344 void
2345 g_assertion_message_cmpstr (const char     *domain,
2346                             const char     *file,
2347                             int             line,
2348                             const char     *func,
2349                             const char     *expr,
2350                             const char     *arg1,
2351                             const char     *cmp,
2352                             const char     *arg2)
2353 {
2354   char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
2355   a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
2356   a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
2357   g_free (t1);
2358   g_free (t2);
2359   s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
2360   g_free (a1);
2361   g_free (a2);
2362   g_assertion_message (domain, file, line, func, s);
2363   g_free (s);
2364 }
2365
2366 void
2367 g_assertion_message_error (const char     *domain,
2368                            const char     *file,
2369                            int             line,
2370                            const char     *func,
2371                            const char     *expr,
2372                            const GError   *error,
2373                            GQuark          error_domain,
2374                            int             error_code)
2375 {
2376   GString *gstring;
2377
2378   /* This is used by both g_assert_error() and g_assert_no_error(), so there
2379    * are three cases: expected an error but got the wrong error, expected
2380    * an error but got no error, and expected no error but got an error.
2381    */
2382
2383   gstring = g_string_new ("assertion failed ");
2384   if (error_domain)
2385       g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
2386                               g_quark_to_string (error_domain), error_code);
2387   else
2388     g_string_append_printf (gstring, "(%s == NULL): ", expr);
2389
2390   if (error)
2391       g_string_append_printf (gstring, "%s (%s, %d)", error->message,
2392                               g_quark_to_string (error->domain), error->code);
2393   else
2394     g_string_append_printf (gstring, "%s is NULL", expr);
2395
2396   g_assertion_message (domain, file, line, func, gstring->str);
2397   g_string_free (gstring, TRUE);
2398 }
2399
2400 /**
2401  * g_strcmp0:
2402  * @str1: (allow-none): a C string or %NULL
2403  * @str2: (allow-none): another C string or %NULL
2404  *
2405  * Compares @str1 and @str2 like strcmp(). Handles %NULL
2406  * gracefully by sorting it before non-%NULL strings.
2407  * Comparing two %NULL pointers returns 0.
2408  *
2409  * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
2410  *
2411  * Since: 2.16
2412  */
2413 int
2414 g_strcmp0 (const char     *str1,
2415            const char     *str2)
2416 {
2417   if (!str1)
2418     return -(str1 != str2);
2419   if (!str2)
2420     return str1 != str2;
2421   return strcmp (str1, str2);
2422 }
2423
2424 static void
2425 test_trap_clear (void)
2426 {
2427   test_trap_last_status = 0;
2428   test_trap_last_pid = 0;
2429   g_clear_pointer (&test_trap_last_subprocess, g_free);
2430   g_clear_pointer (&test_trap_last_stdout, g_free);
2431   g_clear_pointer (&test_trap_last_stderr, g_free);
2432 }
2433
2434 #ifdef G_OS_UNIX
2435
2436 static int
2437 sane_dup2 (int fd1,
2438            int fd2)
2439 {
2440   int ret;
2441   do
2442     ret = dup2 (fd1, fd2);
2443   while (ret < 0 && errno == EINTR);
2444   return ret;
2445 }
2446
2447 #endif
2448
2449 typedef struct {
2450   GPid pid;
2451   GMainLoop *loop;
2452   int child_status;
2453
2454   GIOChannel *stdout_io;
2455   gboolean echo_stdout;
2456   GString *stdout_str;
2457
2458   GIOChannel *stderr_io;
2459   gboolean echo_stderr;
2460   GString *stderr_str;
2461 } WaitForChildData;
2462
2463 static void
2464 check_complete (WaitForChildData *data)
2465 {
2466   if (data->child_status != -1 && data->stdout_io == NULL && data->stderr_io == NULL)
2467     g_main_loop_quit (data->loop);
2468 }
2469
2470 static void
2471 child_exited (GPid     pid,
2472               gint     status,
2473               gpointer user_data)
2474 {
2475   WaitForChildData *data = user_data;
2476
2477 #ifdef G_OS_UNIX
2478   if (WIFEXITED (status)) /* normal exit */
2479     data->child_status = WEXITSTATUS (status); /* 0..255 */
2480   else if (WIFSIGNALED (status) && WTERMSIG (status) == SIGALRM)
2481     data->child_status = G_TEST_STATUS_TIMED_OUT;
2482   else if (WIFSIGNALED (status))
2483     data->child_status = (WTERMSIG (status) << 12); /* signalled */
2484   else /* WCOREDUMP (status) */
2485     data->child_status = 512; /* coredump */
2486 #else
2487   data->child_status = status;
2488 #endif
2489
2490   check_complete (data);
2491 }
2492
2493 static gboolean
2494 child_timeout (gpointer user_data)
2495 {
2496   WaitForChildData *data = user_data;
2497
2498 #ifdef G_OS_WIN32
2499   TerminateProcess (data->pid, G_TEST_STATUS_TIMED_OUT);
2500 #else
2501   kill (data->pid, SIGALRM);
2502 #endif
2503
2504   return FALSE;
2505 }
2506
2507 static gboolean
2508 child_read (GIOChannel *io, GIOCondition cond, gpointer user_data)
2509 {
2510   WaitForChildData *data = user_data;
2511   GIOStatus status;
2512   gsize nread, nwrote, total;
2513   gchar buf[4096];
2514   FILE *echo_file = NULL;
2515
2516   status = g_io_channel_read_chars (io, buf, sizeof (buf), &nread, NULL);
2517   if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF)
2518     {
2519       // FIXME data->error = (status == G_IO_STATUS_ERROR);
2520       if (io == data->stdout_io)
2521         g_clear_pointer (&data->stdout_io, g_io_channel_unref);
2522       else
2523         g_clear_pointer (&data->stderr_io, g_io_channel_unref);
2524
2525       check_complete (data);
2526       return FALSE;
2527     }
2528   else if (status == G_IO_STATUS_AGAIN)
2529     return TRUE;
2530
2531   if (io == data->stdout_io)
2532     {
2533       g_string_append_len (data->stdout_str, buf, nread);
2534       if (data->echo_stdout)
2535         echo_file = stdout;
2536     }
2537   else
2538     {
2539       g_string_append_len (data->stderr_str, buf, nread);
2540       if (data->echo_stderr)
2541         echo_file = stderr;
2542     }
2543
2544   if (echo_file)
2545     {
2546       for (total = 0; total < nread; total += nwrote)
2547         {
2548           nwrote = fwrite (buf + total, 1, nread - total, echo_file);
2549           if (nwrote == 0)
2550             g_error ("write failed: %s", g_strerror (errno));
2551         }
2552     }
2553
2554   return TRUE;
2555 }
2556
2557 static void
2558 wait_for_child (GPid pid,
2559                 int stdout_fd, gboolean echo_stdout,
2560                 int stderr_fd, gboolean echo_stderr,
2561                 guint64 timeout)
2562 {
2563   WaitForChildData data;
2564   GMainContext *context;
2565   GSource *source;
2566
2567   data.pid = pid;
2568   data.child_status = -1;
2569
2570   context = g_main_context_new ();
2571   data.loop = g_main_loop_new (context, FALSE);
2572
2573   source = g_child_watch_source_new (pid);
2574   g_source_set_callback (source, (GSourceFunc) child_exited, &data, NULL);
2575   g_source_attach (source, context);
2576   g_source_unref (source);
2577
2578   data.echo_stdout = echo_stdout;
2579   data.stdout_str = g_string_new (NULL);
2580   data.stdout_io = g_io_channel_unix_new (stdout_fd);
2581   g_io_channel_set_close_on_unref (data.stdout_io, TRUE);
2582   g_io_channel_set_encoding (data.stdout_io, NULL, NULL);
2583   g_io_channel_set_buffered (data.stdout_io, FALSE);
2584   source = g_io_create_watch (data.stdout_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2585   g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2586   g_source_attach (source, context);
2587   g_source_unref (source);
2588
2589   data.echo_stderr = echo_stderr;
2590   data.stderr_str = g_string_new (NULL);
2591   data.stderr_io = g_io_channel_unix_new (stderr_fd);
2592   g_io_channel_set_close_on_unref (data.stderr_io, TRUE);
2593   g_io_channel_set_encoding (data.stderr_io, NULL, NULL);
2594   g_io_channel_set_buffered (data.stderr_io, FALSE);
2595   source = g_io_create_watch (data.stderr_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2596   g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2597   g_source_attach (source, context);
2598   g_source_unref (source);
2599
2600   if (timeout)
2601     {
2602       source = g_timeout_source_new (0);
2603       g_source_set_ready_time (source, g_get_monotonic_time () + timeout);
2604       g_source_set_callback (source, (GSourceFunc) child_timeout, &data, NULL);
2605       g_source_attach (source, context);
2606       g_source_unref (source);
2607     }
2608
2609   g_main_loop_run (data.loop);
2610   g_main_loop_unref (data.loop);
2611   g_main_context_unref (context);
2612
2613   test_trap_last_pid = pid;
2614   test_trap_last_status = data.child_status;
2615   test_trap_last_stdout = g_string_free (data.stdout_str, FALSE);
2616   test_trap_last_stderr = g_string_free (data.stderr_str, FALSE);
2617
2618   g_clear_pointer (&data.stdout_io, g_io_channel_unref);
2619   g_clear_pointer (&data.stderr_io, g_io_channel_unref);
2620 }
2621
2622 /**
2623  * g_test_trap_fork:
2624  * @usec_timeout:    Timeout for the forked test in micro seconds.
2625  * @test_trap_flags: Flags to modify forking behaviour.
2626  *
2627  * Fork the current test program to execute a test case that might
2628  * not return or that might abort.
2629  *
2630  * If @usec_timeout is non-0, the forked test case is aborted and
2631  * considered failing if its run time exceeds it.
2632  *
2633  * The forking behavior can be configured with the #GTestTrapFlags flags.
2634  *
2635  * In the following example, the test code forks, the forked child
2636  * process produces some sample output and exits successfully.
2637  * The forking parent process then asserts successful child program
2638  * termination and validates child program outputs.
2639  *
2640  * |[<!-- language="C" --> 
2641  *   static void
2642  *   test_fork_patterns (void)
2643  *   {
2644  *     if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2645  *       {
2646  *         g_print ("some stdout text: somagic17\n");
2647  *         g_printerr ("some stderr text: semagic43\n");
2648  *         exit (0); /&ast; successful test run &ast;/
2649  *       }
2650  *     g_test_trap_assert_passed ();
2651  *     g_test_trap_assert_stdout ("*somagic17*");
2652  *     g_test_trap_assert_stderr ("*semagic43*");
2653  *   }
2654  * ]|
2655  *
2656  * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2657  *
2658  * Since: 2.16
2659  *
2660  * Deprecated: This function is implemented only on Unix platforms,
2661  * and is not always reliable due to problems inherent in
2662  * fork-without-exec. Use g_test_trap_subprocess() instead.
2663  */
2664 gboolean
2665 g_test_trap_fork (guint64        usec_timeout,
2666                   GTestTrapFlags test_trap_flags)
2667 {
2668 #ifdef G_OS_UNIX
2669   int stdout_pipe[2] = { -1, -1 };
2670   int stderr_pipe[2] = { -1, -1 };
2671
2672   test_trap_clear();
2673   if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0)
2674     g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
2675   test_trap_last_pid = fork ();
2676   if (test_trap_last_pid < 0)
2677     g_error ("failed to fork test program: %s", g_strerror (errno));
2678   if (test_trap_last_pid == 0)  /* child */
2679     {
2680       int fd0 = -1;
2681       close (stdout_pipe[0]);
2682       close (stderr_pipe[0]);
2683       if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2684         fd0 = g_open ("/dev/null", O_RDONLY, 0);
2685       if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2686         g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
2687       if (fd0 >= 3)
2688         close (fd0);
2689       if (stdout_pipe[1] >= 3)
2690         close (stdout_pipe[1]);
2691       if (stderr_pipe[1] >= 3)
2692         close (stderr_pipe[1]);
2693       return TRUE;
2694     }
2695   else                          /* parent */
2696     {
2697       test_run_forks++;
2698       close (stdout_pipe[1]);
2699       close (stderr_pipe[1]);
2700
2701       wait_for_child (test_trap_last_pid,
2702                       stdout_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT),
2703                       stderr_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR),
2704                       usec_timeout);
2705       return FALSE;
2706     }
2707 #else
2708   g_message ("Not implemented: g_test_trap_fork");
2709
2710   return FALSE;
2711 #endif
2712 }
2713
2714 /**
2715  * g_test_trap_subprocess:
2716  * @test_path: (allow-none): Test to run in a subprocess
2717  * @usec_timeout: Timeout for the subprocess test in micro seconds.
2718  * @test_flags:   Flags to modify subprocess behaviour.
2719  *
2720  * Respawns the test program to run only @test_path in a subprocess.
2721  * This can be used for a test case that might not return, or that
2722  * might abort.
2723  *
2724  * If @test_path is %NULL then the same test is re-run in a subprocess.
2725  * You can use g_test_subprocess() to determine whether the test is in
2726  * a subprocess or not.
2727  *
2728  * @test_path can also be the name of the parent
2729  * test, followed by "<literal>/subprocess/</literal>" and then a name
2730  * for the specific subtest (or just ending with
2731  * "<literal>/subprocess</literal>" if the test only has one child
2732  * test); tests with names of this form will automatically be skipped
2733  * in the parent process.
2734  *
2735  * If @usec_timeout is non-0, the test subprocess is aborted and
2736  * considered failing if its run time exceeds it.
2737  *
2738  * The subprocess behavior can be configured with the
2739  * #GTestSubprocessFlags flags.
2740  *
2741  * You can use methods such as g_test_trap_assert_passed(),
2742  * g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to
2743  * check the results of the subprocess. (But note that
2744  * g_test_trap_assert_stdout() and g_test_trap_assert_stderr()
2745  * cannot be used if @test_flags specifies that the child should
2746  * inherit the parent stdout/stderr.) 
2747  *
2748  * If your <literal>main ()</literal> needs to behave differently in
2749  * the subprocess, you can call g_test_subprocess() (after calling
2750  * g_test_init()) to see whether you are in a subprocess.
2751  *
2752  * The following example tests that calling
2753  * <literal>my_object_new(1000000)</literal> will abort with an error
2754  * message.
2755  *
2756  * |[<!-- language="C" --> 
2757  *   static void
2758  *   test_create_large_object_subprocess (void)
2759  *   {
2760  *     if (g_test_subprocess ())
2761  *       {
2762  *         my_object_new (1000000);
2763  *         return;
2764  *       }
2765  *
2766  *     /&ast; Reruns this same test in a subprocess &ast;/
2767  *     g_test_trap_subprocess (NULL, 0, 0);
2768  *     g_test_trap_assert_failed ();
2769  *     g_test_trap_assert_stderr ("*ERROR*too large*");
2770  *   }
2771  *
2772  *   int
2773  *   main (int argc, char **argv)
2774  *   {
2775  *     g_test_init (&argc, &argv, NULL);
2776  *
2777  *     g_test_add_func ("/myobject/create_large_object",
2778  *                      test_create_large_object);
2779  *     return g_test_run ();
2780  *   }
2781  * ]|
2782  *
2783  * Since: 2.38
2784  */
2785 void
2786 g_test_trap_subprocess (const char           *test_path,
2787                         guint64               usec_timeout,
2788                         GTestSubprocessFlags  test_flags)
2789 {
2790   GError *error = NULL;
2791   GPtrArray *argv;
2792   GSpawnFlags flags;
2793   int stdout_fd, stderr_fd;
2794   GPid pid;
2795
2796   /* Sanity check that they used GTestSubprocessFlags, not GTestTrapFlags */
2797   g_assert ((test_flags & (G_TEST_TRAP_INHERIT_STDIN | G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR)) == 0);
2798
2799   if (test_path)
2800     {
2801       if (!g_test_suite_case_exists (g_test_get_root (), test_path))
2802         g_error ("g_test_trap_subprocess: test does not exist: %s", test_path);
2803     }
2804   else
2805     {
2806       test_path = test_run_name;
2807     }
2808
2809   if (g_test_verbose ())
2810     g_print ("GTest: subprocess: %s\n", test_path);
2811
2812   test_trap_clear ();
2813   test_trap_last_subprocess = g_strdup (test_path);
2814
2815   argv = g_ptr_array_new ();
2816   g_ptr_array_add (argv, test_argv0);
2817   g_ptr_array_add (argv, "-q");
2818   g_ptr_array_add (argv, "-p");
2819   g_ptr_array_add (argv, (char *)test_path);
2820   g_ptr_array_add (argv, "--GTestSubprocess");
2821   if (test_log_fd != -1)
2822     {
2823       char log_fd_buf[128];
2824
2825       g_ptr_array_add (argv, "--GTestLogFD");
2826       g_snprintf (log_fd_buf, sizeof (log_fd_buf), "%d", test_log_fd);
2827       g_ptr_array_add (argv, log_fd_buf);
2828     }
2829   g_ptr_array_add (argv, NULL);
2830
2831   flags = G_SPAWN_DO_NOT_REAP_CHILD;
2832   if (test_flags & G_TEST_TRAP_INHERIT_STDIN)
2833     flags |= G_SPAWN_CHILD_INHERITS_STDIN;
2834
2835   if (!g_spawn_async_with_pipes (test_initial_cwd,
2836                                  (char **)argv->pdata,
2837                                  NULL, flags,
2838                                  NULL, NULL,
2839                                  &pid, NULL, &stdout_fd, &stderr_fd,
2840                                  &error))
2841     {
2842       g_error ("g_test_trap_subprocess() failed: %s\n",
2843                error->message);
2844     }
2845   g_ptr_array_free (argv, TRUE);
2846
2847   wait_for_child (pid,
2848                   stdout_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDOUT),
2849                   stderr_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDERR),
2850                   usec_timeout);
2851 }
2852
2853 /**
2854  * g_test_subprocess:
2855  *
2856  * Returns %TRUE (after g_test_init() has been called) if the test
2857  * program is running under g_test_trap_subprocess().
2858  *
2859  * Returns: %TRUE if the test program is running under
2860  * g_test_trap_subprocess().
2861  *
2862  * Since: 2.38
2863  */
2864 gboolean
2865 g_test_subprocess (void)
2866 {
2867   return test_in_subprocess;
2868 }
2869
2870 /**
2871  * g_test_trap_has_passed:
2872  *
2873  * Check the result of the last g_test_trap_subprocess() call.
2874  *
2875  * Returns: %TRUE if the last test subprocess terminated successfully.
2876  *
2877  * Since: 2.16
2878  */
2879 gboolean
2880 g_test_trap_has_passed (void)
2881 {
2882   return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
2883 }
2884
2885 /**
2886  * g_test_trap_reached_timeout:
2887  *
2888  * Check the result of the last g_test_trap_subprocess() call.
2889  *
2890  * Returns: %TRUE if the last test subprocess got killed due to a timeout.
2891  *
2892  * Since: 2.16
2893  */
2894 gboolean
2895 g_test_trap_reached_timeout (void)
2896 {
2897   return test_trap_last_status == G_TEST_STATUS_TIMED_OUT;
2898 }
2899
2900 void
2901 g_test_trap_assertions (const char     *domain,
2902                         const char     *file,
2903                         int             line,
2904                         const char     *func,
2905                         guint64         assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
2906                         const char     *pattern)
2907 {
2908   gboolean must_pass = assertion_flags == 0;
2909   gboolean must_fail = assertion_flags == 1;
2910   gboolean match_result = 0 == (assertion_flags & 1);
2911   const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
2912   const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
2913   const char *match_error = match_result ? "failed to match" : "contains invalid match";
2914   char *process_id;
2915
2916 #ifdef G_OS_UNIX
2917   if (test_trap_last_subprocess != NULL)
2918     {
2919       process_id = g_strdup_printf ("%s [%d]", test_trap_last_subprocess,
2920                                     test_trap_last_pid);
2921     }
2922   else if (test_trap_last_pid != 0)
2923     process_id = g_strdup_printf ("%d", test_trap_last_pid);
2924 #else
2925   if (test_trap_last_subprocess != NULL)
2926     process_id = g_strdup (test_trap_last_subprocess);
2927 #endif
2928   else
2929     g_error ("g_test_trap_ assertion with no trapped test");
2930
2931   if (must_pass && !g_test_trap_has_passed())
2932     {
2933       char *msg = g_strdup_printf ("child process (%s) failed unexpectedly", process_id);
2934       g_assertion_message (domain, file, line, func, msg);
2935       g_free (msg);
2936     }
2937   if (must_fail && g_test_trap_has_passed())
2938     {
2939       char *msg = g_strdup_printf ("child process (%s) did not fail as expected", process_id);
2940       g_assertion_message (domain, file, line, func, msg);
2941       g_free (msg);
2942     }
2943   if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
2944     {
2945       char *msg = g_strdup_printf ("stdout of child process (%s) %s: %s", process_id, match_error, stdout_pattern);
2946       g_assertion_message (domain, file, line, func, msg);
2947       g_free (msg);
2948     }
2949   if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
2950     {
2951       char *msg = g_strdup_printf ("stderr of child process (%s) %s: %s", process_id, match_error, stderr_pattern);
2952       g_assertion_message (domain, file, line, func, msg);
2953       g_free (msg);
2954     }
2955   g_free (process_id);
2956 }
2957
2958 static void
2959 gstring_overwrite_int (GString *gstring,
2960                        guint    pos,
2961                        guint32  vuint)
2962 {
2963   vuint = g_htonl (vuint);
2964   g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
2965 }
2966
2967 static void
2968 gstring_append_int (GString *gstring,
2969                     guint32  vuint)
2970 {
2971   vuint = g_htonl (vuint);
2972   g_string_append_len (gstring, (const gchar*) &vuint, 4);
2973 }
2974
2975 static void
2976 gstring_append_double (GString *gstring,
2977                        double   vdouble)
2978 {
2979   union { double vdouble; guint64 vuint64; } u;
2980   u.vdouble = vdouble;
2981   u.vuint64 = GUINT64_TO_BE (u.vuint64);
2982   g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
2983 }
2984
2985 static guint8*
2986 g_test_log_dump (GTestLogMsg *msg,
2987                  guint       *len)
2988 {
2989   GString *gstring = g_string_sized_new (1024);
2990   guint ui;
2991   gstring_append_int (gstring, 0);              /* message length */
2992   gstring_append_int (gstring, msg->log_type);
2993   gstring_append_int (gstring, msg->n_strings);
2994   gstring_append_int (gstring, msg->n_nums);
2995   gstring_append_int (gstring, 0);      /* reserved */
2996   for (ui = 0; ui < msg->n_strings; ui++)
2997     {
2998       guint l = strlen (msg->strings[ui]);
2999       gstring_append_int (gstring, l);
3000       g_string_append_len (gstring, msg->strings[ui], l);
3001     }
3002   for (ui = 0; ui < msg->n_nums; ui++)
3003     gstring_append_double (gstring, msg->nums[ui]);
3004   *len = gstring->len;
3005   gstring_overwrite_int (gstring, 0, *len);     /* message length */
3006   return (guint8*) g_string_free (gstring, FALSE);
3007 }
3008
3009 static inline long double
3010 net_double (const gchar **ipointer)
3011 {
3012   union { guint64 vuint64; double vdouble; } u;
3013   guint64 aligned_int64;
3014   memcpy (&aligned_int64, *ipointer, 8);
3015   *ipointer += 8;
3016   u.vuint64 = GUINT64_FROM_BE (aligned_int64);
3017   return u.vdouble;
3018 }
3019
3020 static inline guint32
3021 net_int (const gchar **ipointer)
3022 {
3023   guint32 aligned_int;
3024   memcpy (&aligned_int, *ipointer, 4);
3025   *ipointer += 4;
3026   return g_ntohl (aligned_int);
3027 }
3028
3029 static gboolean
3030 g_test_log_extract (GTestLogBuffer *tbuffer)
3031 {
3032   const gchar *p = tbuffer->data->str;
3033   GTestLogMsg msg;
3034   guint mlength;
3035   if (tbuffer->data->len < 4 * 5)
3036     return FALSE;
3037   mlength = net_int (&p);
3038   if (tbuffer->data->len < mlength)
3039     return FALSE;
3040   msg.log_type = net_int (&p);
3041   msg.n_strings = net_int (&p);
3042   msg.n_nums = net_int (&p);
3043   if (net_int (&p) == 0)
3044     {
3045       guint ui;
3046       msg.strings = g_new0 (gchar*, msg.n_strings + 1);
3047       msg.nums = g_new0 (long double, msg.n_nums);
3048       for (ui = 0; ui < msg.n_strings; ui++)
3049         {
3050           guint sl = net_int (&p);
3051           msg.strings[ui] = g_strndup (p, sl);
3052           p += sl;
3053         }
3054       for (ui = 0; ui < msg.n_nums; ui++)
3055         msg.nums[ui] = net_double (&p);
3056       if (p <= tbuffer->data->str + mlength)
3057         {
3058           g_string_erase (tbuffer->data, 0, mlength);
3059           tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
3060           return TRUE;
3061         }
3062     }
3063   g_free (msg.nums);
3064   g_strfreev (msg.strings);
3065   g_error ("corrupt log stream from test program");
3066   return FALSE;
3067 }
3068
3069 /**
3070  * g_test_log_buffer_new:
3071  *
3072  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3073  */
3074 GTestLogBuffer*
3075 g_test_log_buffer_new (void)
3076 {
3077   GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
3078   tb->data = g_string_sized_new (1024);
3079   return tb;
3080 }
3081
3082 /**
3083  * g_test_log_buffer_free:
3084  *
3085  * Internal function for gtester to free test log messages, no ABI guarantees provided.
3086  */
3087 void
3088 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
3089 {
3090   g_return_if_fail (tbuffer != NULL);
3091   while (tbuffer->msgs)
3092     g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
3093   g_string_free (tbuffer->data, TRUE);
3094   g_free (tbuffer);
3095 }
3096
3097 /**
3098  * g_test_log_buffer_push:
3099  *
3100  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3101  */
3102 void
3103 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
3104                         guint           n_bytes,
3105                         const guint8   *bytes)
3106 {
3107   g_return_if_fail (tbuffer != NULL);
3108   if (n_bytes)
3109     {
3110       gboolean more_messages;
3111       g_return_if_fail (bytes != NULL);
3112       g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
3113       do
3114         more_messages = g_test_log_extract (tbuffer);
3115       while (more_messages);
3116     }
3117 }
3118
3119 /**
3120  * g_test_log_buffer_pop:
3121  *
3122  * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
3123  */
3124 GTestLogMsg*
3125 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
3126 {
3127   GTestLogMsg *msg = NULL;
3128   g_return_val_if_fail (tbuffer != NULL, NULL);
3129   if (tbuffer->msgs)
3130     {
3131       GSList *slist = g_slist_last (tbuffer->msgs);
3132       msg = slist->data;
3133       tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
3134     }
3135   return msg;
3136 }
3137
3138 /**
3139  * g_test_log_msg_free:
3140  *
3141  * Internal function for gtester to free test log messages, no ABI guarantees provided.
3142  */
3143 void
3144 g_test_log_msg_free (GTestLogMsg *tmsg)
3145 {
3146   g_return_if_fail (tmsg != NULL);
3147   g_strfreev (tmsg->strings);
3148   g_free (tmsg->nums);
3149   g_free (tmsg);
3150 }
3151
3152 static gchar *
3153 g_test_build_filename_va (GTestFileType  file_type,
3154                           const gchar   *first_path,
3155                           va_list        ap)
3156 {
3157   const gchar *pathv[16];
3158   gint num_path_segments;
3159
3160   if (file_type == G_TEST_DIST)
3161     pathv[0] = test_disted_files_dir;
3162   else if (file_type == G_TEST_BUILT)
3163     pathv[0] = test_built_files_dir;
3164   else
3165     g_assert_not_reached ();
3166
3167   pathv[1] = first_path;
3168
3169   for (num_path_segments = 2; num_path_segments < G_N_ELEMENTS (pathv); num_path_segments++)
3170     {
3171       pathv[num_path_segments] = va_arg (ap, const char *);
3172       if (pathv[num_path_segments] == NULL)
3173         break;
3174     }
3175
3176   g_assert_cmpint (num_path_segments, <, G_N_ELEMENTS (pathv));
3177
3178   return g_build_filenamev ((gchar **) pathv);
3179 }
3180
3181 /**
3182  * g_test_build_filename:
3183  * @file_type: the type of file (built vs. distributed)
3184  * @first_path: the first segment of the pathname
3185  * @...: %NULL-terminated additional path segments
3186  *
3187  * Creates the pathname to a data file that is required for a test.
3188  *
3189  * This function is conceptually similar to g_build_filename() except
3190  * that the first argument has been replaced with a #GTestFileType
3191  * argument.
3192  *
3193  * The data file should either have been distributed with the module
3194  * containing the test (%G_TEST_DIST) or built as part of the build
3195  * system of that module (%G_TEST_BUILT).
3196  *
3197  * In order for this function to work in srcdir != builddir situations,
3198  * the G_TEST_SRCDIR and G_TEST_BUILDDIR environment variables need to
3199  * have been defined.  As of 2.38, this is done by the glib.mk
3200  * included in GLib.  Please ensure that your copy is up to date before
3201  * using this function.
3202  *
3203  * In case neither variable is set, this function will fall back to
3204  * using the dirname portion of argv[0], possibly removing ".libs".
3205  * This allows for casual running of tests directly from the commandline
3206  * in the srcdir == builddir case and should also support running of
3207  * installed tests, assuming the data files have been installed in the
3208  * same relative path as the test binary.
3209  *
3210  * Returns: the path of the file, to be freed using g_free()
3211  *
3212  * Since: 2.38
3213  **/
3214 /**
3215  * GTestFileType:
3216  * @G_TEST_DIST: a file that was included in the distribution tarball
3217  * @G_TEST_BUILT: a file that was built on the compiling machine
3218  *
3219  * The type of file to return the filename for, when used with
3220  * g_test_build_filename().
3221  *
3222  * These two options correspond rather directly to the 'dist' and
3223  * 'built' terminology that automake uses and are explicitly used to
3224  * distinguish between the 'srcdir' and 'builddir' being separate.  All
3225  * files in your project should either be dist (in the
3226  * <literal>DIST_EXTRA</literal> or <literal>dist_schema_DATA</literal>
3227  * sense, in which case they will always be in the srcdir) or built (in
3228  * the <literal>BUILT_SOURCES</literal> sense, in which case they will
3229  * always be in the builddir).
3230  *
3231  * Note: as a general rule of automake, files that are generated only as
3232  * part of the build-from-git process (but then are distributed with the
3233  * tarball) always go in srcdir (even if doing a srcdir != builddir
3234  * build from git) and are considered as distributed files.
3235  *
3236  * Since: 2.38
3237  **/
3238 gchar *
3239 g_test_build_filename (GTestFileType  file_type,
3240                        const gchar   *first_path,
3241                        ...)
3242 {
3243   gchar *result;
3244   va_list ap;
3245
3246   g_assert (g_test_initialized ());
3247
3248   va_start (ap, first_path);
3249   result = g_test_build_filename_va (file_type, first_path, ap);
3250   va_end (ap);
3251
3252   return result;
3253 }
3254
3255 /**
3256  * g_test_get_dir:
3257  * @file_type: the type of file (built vs. distributed)
3258  *
3259  * Gets the pathname of the directory containing test files of the type
3260  * specified by @file_type.
3261  *
3262  * This is approximately the same as calling g_test_build_filename("."),
3263  * but you don't need to free the return value.
3264  *
3265  * Returns: the path of the directory, owned by GLib
3266  *
3267  * Since: 2.38
3268  **/
3269 const gchar *
3270 g_test_get_dir (GTestFileType file_type)
3271 {
3272   g_assert (g_test_initialized ());
3273
3274   if (file_type == G_TEST_DIST)
3275     return test_disted_files_dir;
3276   else if (file_type == G_TEST_BUILT)
3277     return test_built_files_dir;
3278
3279   g_assert_not_reached ();
3280 }
3281
3282 /**
3283  * g_test_get_filename:
3284  * @file_type: the type of file (built vs. distributed)
3285  * @first_path: the first segment of the pathname
3286  * @...: %NULL-terminated additional path segments
3287  *
3288  * Gets the pathname to a data file that is required for a test.
3289  *
3290  * This is the same as g_test_build_filename() with two differences.
3291  * The first difference is that must only use this function from within
3292  * a testcase function.  The second difference is that you need not free
3293  * the return value -- it will be automatically freed when the testcase
3294  * finishes running.
3295  *
3296  * It is safe to use this function from a thread inside of a testcase
3297  * but you must ensure that all such uses occur before the main testcase
3298  * function returns (ie: it is best to ensure that all threads have been
3299  * joined).
3300  *
3301  * Returns: the path, automatically freed at the end of the testcase
3302  *
3303  * Since: 2.38
3304  **/
3305 const gchar *
3306 g_test_get_filename (GTestFileType  file_type,
3307                      const gchar   *first_path,
3308                      ...)
3309 {
3310   gchar *result;
3311   GSList *node;
3312   va_list ap;
3313
3314   g_assert (g_test_initialized ());
3315   if (test_filename_free_list == NULL)
3316     g_error ("g_test_get_filename() can only be used within testcase functions");
3317
3318   va_start (ap, first_path);
3319   result = g_test_build_filename_va (file_type, first_path, ap);
3320   va_end (ap);
3321
3322   node = g_slist_prepend (NULL, result);
3323   do
3324     node->next = *test_filename_free_list;
3325   while (!g_atomic_pointer_compare_and_exchange (test_filename_free_list, node->next, node));
3326
3327   return result;
3328 }
3329
3330 /* --- macros docs START --- */
3331 /**
3332  * g_test_add:
3333  * @testpath:  The test path for a new test case.
3334  * @Fixture:   The type of a fixture data structure.
3335  * @tdata:     Data argument for the test functions.
3336  * @fsetup:    The function to set up the fixture data.
3337  * @ftest:     The actual test function.
3338  * @fteardown: The function to tear down the fixture data.
3339  *
3340  * Hook up a new test case at @testpath, similar to g_test_add_func().
3341  * A fixture data structure with setup and teardown function may be provided
3342  * though, similar to g_test_create_case().
3343  * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
3344  * fteardown() callbacks can expect a @Fixture pointer as first argument in
3345  * a type safe manner.
3346  *
3347  * Since: 2.16
3348  **/
3349 /* --- macros docs END --- */