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