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