gkdbus: Fix underflow and unreachable code bug
[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  * SPDX-License-Identifier: LGPL-2.1-or-later
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "config.h"
22
23 #include "gtestutils.h"
24 #include "gfileutils.h"
25
26 #include <sys/types.h>
27 #ifdef G_OS_UNIX
28 #include <sys/wait.h>
29 #include <sys/time.h>
30 #include <fcntl.h>
31 #include <unistd.h>
32 #endif
33 #include <string.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <inttypes.h>
37 #ifdef HAVE_SYS_PRCTL_H
38 #include <sys/prctl.h>
39 #endif
40 #ifdef HAVE_SYS_RESOURCE_H
41 #include <sys/resource.h>
42 #endif
43 #ifdef G_OS_WIN32
44 #include <crtdbg.h>
45 #include <io.h>
46 #include <windows.h>
47 #endif
48 #include <errno.h>
49 #include <signal.h>
50 #ifdef HAVE_SYS_SELECT_H
51 #include <sys/select.h>
52 #endif /* HAVE_SYS_SELECT_H */
53 #include <glib/gstdio.h>
54
55 #include "gmain.h"
56 #include "gpattern.h"
57 #include "grand.h"
58 #include "gstrfuncs.h"
59 #include "gtimer.h"
60 #include "gslice.h"
61 #include "gspawn.h"
62 #include "glib-private.h"
63 #include "gutilsprivate.h"
64
65 #define TAP_VERSION G_STRINGIFY (13)
66 /* FIXME: Remove '#' prefix when we'll depend on a meson version supporting TAP 14
67  * See https://gitlab.gnome.org/GNOME/glib/-/issues/2885 */
68 #define TAP_SUBTEST_PREFIX "#    "  /* a 4-space indented line */
69
70 /**
71  * SECTION:testing
72  * @title: Testing
73  * @short_description: a test framework
74  *
75  * GLib provides a framework for writing and maintaining unit tests
76  * in parallel to the code they are testing. The API is designed according
77  * to established concepts found in the other test frameworks (JUnit, NUnit,
78  * RUnit), which in turn is based on smalltalk unit testing concepts.
79  *
80  * - Test case: Tests (test methods) are grouped together with their
81  *   fixture into test cases.
82  *
83  * - Fixture: A test fixture consists of fixture data and setup and
84  *   teardown methods to establish the environment for the test
85  *   functions. We use fresh fixtures, i.e. fixtures are newly set
86  *   up and torn down around each test invocation to avoid dependencies
87  *   between tests.
88  *
89  * - Test suite: Test cases can be grouped into test suites, to allow
90  *   subsets of the available tests to be run. Test suites can be
91  *   grouped into other test suites as well.
92  *
93  * The API is designed to handle creation and registration of test suites
94  * and test cases implicitly. A simple call like
95  * |[<!-- language="C" --> 
96  *   g_test_init (&argc, &argv, G_TEST_OPTION_ISOLATE_DIRS, NULL);
97  *
98  *   g_test_add_func ("/misc/assertions", test_assertions);
99  * ]|
100  * creates a test suite called "misc" with a single test case named
101  * "assertions", which consists of running the test_assertions function.
102  *
103  * g_test_init() should be called before calling any other test functions.
104  *
105  * In addition to the traditional g_assert_true(), the test framework provides
106  * an extended set of assertions for comparisons: g_assert_cmpfloat(),
107  * g_assert_cmpfloat_with_epsilon(), g_assert_cmpint(), g_assert_cmpuint(),
108  * g_assert_cmphex(), g_assert_cmpstr(), g_assert_cmpmem() and
109  * g_assert_cmpvariant(). The
110  * advantage of these variants over plain g_assert_true() is that the assertion
111  * messages can be more elaborate, and include the values of the compared
112  * entities.
113  *
114  * Note that g_assert() should not be used in unit tests, since it is a no-op
115  * when compiling with `G_DISABLE_ASSERT`. Use g_assert() in production code,
116  * and g_assert_true() in unit tests.
117  *
118  * A full example of creating a test suite with two tests using fixtures:
119  * |[<!-- language="C" -->
120  * #include <glib.h>
121  * #include <locale.h>
122  *
123  * typedef struct {
124  *   MyObject *obj;
125  *   OtherObject *helper;
126  * } MyObjectFixture;
127  *
128  * static void
129  * my_object_fixture_set_up (MyObjectFixture *fixture,
130  *                           gconstpointer user_data)
131  * {
132  *   fixture->obj = my_object_new ();
133  *   my_object_set_prop1 (fixture->obj, "some-value");
134  *   my_object_do_some_complex_setup (fixture->obj, user_data);
135  *
136  *   fixture->helper = other_object_new ();
137  * }
138  *
139  * static void
140  * my_object_fixture_tear_down (MyObjectFixture *fixture,
141  *                              gconstpointer user_data)
142  * {
143  *   g_clear_object (&fixture->helper);
144  *   g_clear_object (&fixture->obj);
145  * }
146  *
147  * static void
148  * test_my_object_test1 (MyObjectFixture *fixture,
149  *                       gconstpointer user_data)
150  * {
151  *   g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "initial-value");
152  * }
153  *
154  * static void
155  * test_my_object_test2 (MyObjectFixture *fixture,
156  *                       gconstpointer user_data)
157  * {
158  *   my_object_do_some_work_using_helper (fixture->obj, fixture->helper);
159  *   g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "updated-value");
160  * }
161  *
162  * int
163  * main (int argc, char *argv[])
164  * {
165  *   setlocale (LC_ALL, "");
166  *
167  *   g_test_init (&argc, &argv, NULL);
168  *
169  *   // Define the tests.
170  *   g_test_add ("/my-object/test1", MyObjectFixture, "some-user-data",
171  *               my_object_fixture_set_up, test_my_object_test1,
172  *               my_object_fixture_tear_down);
173  *   g_test_add ("/my-object/test2", MyObjectFixture, "some-user-data",
174  *               my_object_fixture_set_up, test_my_object_test2,
175  *               my_object_fixture_tear_down);
176  *
177  *   return g_test_run ();
178  * }
179  * ]|
180  *
181  * ## Integrating GTest in your project
182  *
183  * If you are using the [Meson](http://mesonbuild.com) build system, you will
184  * typically use the provided `test()` primitive to call the test binaries,
185  * e.g.:
186  *
187  * |[<!-- language="plain" -->
188  *   test(
189  *     'foo',
190  *     executable('foo', 'foo.c', dependencies: deps),
191  *     env: [
192  *       'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
193  *       'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
194  *     ],
195  *   )
196  *
197  *   test(
198  *     'bar',
199  *     executable('bar', 'bar.c', dependencies: deps),
200  *     env: [
201  *       'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
202  *       'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
203  *     ],
204  *   )
205  * ]|
206  *
207  * If you are using Autotools, you're strongly encouraged to use the Automake
208  * [TAP](https://testanything.org/) harness; GLib provides template files for
209  * easily integrating with it:
210  *
211  *   - [glib-tap.mk](https://gitlab.gnome.org/GNOME/glib/blob/glib-2-58/glib-tap.mk)
212  *   - [tap-test](https://gitlab.gnome.org/GNOME/glib/blob/glib-2-58/tap-test)
213  *   - [tap-driver.sh](https://gitlab.gnome.org/GNOME/glib/blob/glib-2-58/tap-driver.sh)
214  *
215  * You can copy these files in your own project's root directory, and then
216  * set up your `Makefile.am` file to reference them, for instance:
217  *
218  * |[<!-- language="plain" -->
219  * include $(top_srcdir)/glib-tap.mk
220  *
221  * # test binaries
222  * test_programs = \
223  *   foo \
224  *   bar
225  *
226  * # data distributed in the tarball
227  * dist_test_data = \
228  *   foo.data.txt \
229  *   bar.data.txt
230  *
231  * # data not distributed in the tarball
232  * test_data = \
233  *   blah.data.txt
234  * ]|
235  *
236  * Make sure to distribute the TAP files, using something like the following
237  * in your top-level `Makefile.am`:
238  *
239  * |[<!-- language="plain" -->
240  * EXTRA_DIST += \
241  *   tap-driver.sh \
242  *   tap-test
243  * ]|
244  *
245  * `glib-tap.mk` will be distributed implicitly due to being included in a
246  * `Makefile.am`. All three files should be added to version control.
247  *
248  * If you don't have access to the Autotools TAP harness, you can use the
249  * [gtester][gtester] and [gtester-report][gtester-report] tools, and use
250  * the [glib.mk](https://gitlab.gnome.org/GNOME/glib/blob/glib-2-58/glib.mk)
251  * Automake template provided by GLib. Note, however, that since GLib 2.62,
252  * [gtester][gtester] and [gtester-report][gtester-report] have been deprecated
253  * in favour of using TAP. The `--tap` argument to tests is enabled by default
254  * as of GLib 2.62.
255  */
256
257 /**
258  * g_test_initialized:
259  *
260  * Returns %TRUE if g_test_init() has been called.
261  *
262  * Returns: %TRUE if g_test_init() has been called.
263  *
264  * Since: 2.36
265  */
266
267 /**
268  * g_test_quick:
269  *
270  * Returns %TRUE if tests are run in quick mode.
271  * Exactly one of g_test_quick() and g_test_slow() is active in any run;
272  * there is no "medium speed".
273  *
274  * By default, tests are run in quick mode. In tests that use
275  * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
276  * can be used to change this.
277  *
278  * Returns: %TRUE if in quick mode
279  */
280
281 /**
282  * g_test_slow:
283  *
284  * Returns %TRUE if tests are run in slow mode.
285  * Exactly one of g_test_quick() and g_test_slow() is active in any run;
286  * there is no "medium speed".
287  *
288  * By default, tests are run in quick mode. In tests that use
289  * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
290  * can be used to change this.
291  *
292  * Returns: the opposite of g_test_quick()
293  */
294
295 /**
296  * g_test_thorough:
297  *
298  * Returns %TRUE if tests are run in thorough mode, equivalent to
299  * g_test_slow().
300  *
301  * By default, tests are run in quick mode. In tests that use
302  * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
303  * can be used to change this.
304  *
305  * Returns: the same thing as g_test_slow()
306  */
307
308 /**
309  * g_test_perf:
310  *
311  * Returns %TRUE if tests are run in performance mode.
312  *
313  * By default, tests are run in quick mode. In tests that use
314  * g_test_init(), the option `-m perf` enables performance tests, while
315  * `-m quick` disables them.
316  *
317  * Returns: %TRUE if in performance mode
318  */
319
320 /**
321  * g_test_undefined:
322  *
323  * Returns %TRUE if tests may provoke assertions and other formally-undefined
324  * behaviour, to verify that appropriate warnings are given. It might, in some
325  * cases, be useful to turn this off with if running tests under valgrind;
326  * in tests that use g_test_init(), the option `-m no-undefined` disables
327  * those tests, while `-m undefined` explicitly enables them (normally
328  * the default behaviour).
329  *
330  * Since GLib 2.68, if GLib was compiled with gcc or clang and
331  * [AddressSanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer)
332  * is enabled, the default changes to not exercising undefined behaviour.
333  *
334  * Returns: %TRUE if tests may provoke programming errors
335  */
336
337 /**
338  * g_test_verbose:
339  *
340  * Returns %TRUE if tests are run in verbose mode.
341  * In tests that use g_test_init(), the option `--verbose` enables this,
342  * while `-q` or `--quiet` disables it.
343  * The default is neither g_test_verbose() nor g_test_quiet().
344  *
345  * Returns: %TRUE if in verbose mode
346  */
347
348 /**
349  * g_test_quiet:
350  *
351  * Returns %TRUE if tests are run in quiet mode.
352  * In tests that use g_test_init(), the option `-q` or `--quiet` enables
353  * this, while `--verbose` disables it.
354  * The default is neither g_test_verbose() nor g_test_quiet().
355  *
356  * Returns: %TRUE if in quiet mode
357  */
358
359 /**
360  * g_test_queue_unref:
361  * @gobject: the object to unref
362  *
363  * Enqueue an object to be released with g_object_unref() during
364  * the next teardown phase. This is equivalent to calling
365  * g_test_queue_destroy() with a destroy callback of g_object_unref().
366  *
367  * Since: 2.16
368  */
369
370 /**
371  * GTestSubprocessFlags:
372  * @G_TEST_SUBPROCESS_DEFAULT: Default behaviour. Since: 2.74
373  * @G_TEST_SUBPROCESS_INHERIT_STDIN: If this flag is given, the child
374  *     process will inherit the parent's stdin. Otherwise, the child's
375  *     stdin is redirected to `/dev/null`.
376  * @G_TEST_SUBPROCESS_INHERIT_STDOUT: If this flag is given, the child
377  *     process will inherit the parent's stdout. Otherwise, the child's
378  *     stdout will not be visible, but it will be captured to allow
379  *     later tests with g_test_trap_assert_stdout().
380  * @G_TEST_SUBPROCESS_INHERIT_STDERR: If this flag is given, the child
381  *     process will inherit the parent's stderr. Otherwise, the child's
382  *     stderr will not be visible, but it will be captured to allow
383  *     later tests with g_test_trap_assert_stderr().
384  *
385  * Flags to pass to g_test_trap_subprocess() to control input and output.
386  *
387  * Note that in contrast with g_test_trap_fork(), the default is to
388  * not show stdout and stderr.
389  */
390
391 /**
392  * g_test_trap_assert_passed:
393  *
394  * Assert that the last test subprocess passed.
395  * See g_test_trap_subprocess().
396  *
397  * Since: 2.16
398  */
399
400 /**
401  * g_test_trap_assert_failed:
402  *
403  * Assert that the last test subprocess failed.
404  * See g_test_trap_subprocess().
405  *
406  * This is sometimes used to test situations that are formally considered to
407  * be undefined behaviour, like inputs that fail a g_return_if_fail()
408  * check. In these situations you should skip the entire test, including the
409  * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
410  * to indicate that undefined behaviour may be tested.
411  *
412  * Since: 2.16
413  */
414
415 /**
416  * g_test_trap_assert_stdout:
417  * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
418  *
419  * Assert that the stdout output of the last test subprocess matches
420  * @soutpattern. See g_test_trap_subprocess().
421  *
422  * Since: 2.16
423  */
424
425 /**
426  * g_test_trap_assert_stdout_unmatched:
427  * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
428  *
429  * Assert that the stdout output of the last test subprocess
430  * does not match @soutpattern. See g_test_trap_subprocess().
431  *
432  * Since: 2.16
433  */
434
435 /**
436  * g_test_trap_assert_stderr:
437  * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
438  *
439  * Assert that the stderr output of the last test subprocess
440  * matches @serrpattern. See  g_test_trap_subprocess().
441  *
442  * This is sometimes used to test situations that are formally
443  * considered to be undefined behaviour, like code that hits a
444  * g_assert() or g_error(). In these situations you should skip the
445  * entire test, including the call to g_test_trap_subprocess(), unless
446  * g_test_undefined() returns %TRUE to indicate that undefined
447  * behaviour may be tested.
448  *
449  * Since: 2.16
450  */
451
452 /**
453  * g_test_trap_assert_stderr_unmatched:
454  * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
455  *
456  * Assert that the stderr output of the last test subprocess
457  * does not match @serrpattern. See g_test_trap_subprocess().
458  *
459  * Since: 2.16
460  */
461
462 /**
463  * g_test_rand_bit:
464  *
465  * Get a reproducible random bit (0 or 1), see g_test_rand_int()
466  * for details on test case random numbers.
467  *
468  * Since: 2.16
469  */
470
471 /**
472  * g_assert:
473  * @expr: the expression to check
474  *
475  * Debugging macro to terminate the application if the assertion
476  * fails. If the assertion fails (i.e. the expression is not true),
477  * an error message is logged and the application is terminated.
478  *
479  * The macro can be turned off in final releases of code by defining
480  * `G_DISABLE_ASSERT` when compiling the application, so code must
481  * not depend on any side effects from @expr. Similarly, it must not be used
482  * in unit tests, otherwise the unit tests will be ineffective if compiled with
483  * `G_DISABLE_ASSERT`. Use g_assert_true() and related macros in unit tests
484  * instead.
485  */
486
487 /**
488  * g_assert_not_reached:
489  *
490  * Debugging macro to terminate the application if it is ever
491  * reached. If it is reached, an error message is logged and the
492  * application is terminated.
493  *
494  * The macro can be turned off in final releases of code by defining
495  * `G_DISABLE_ASSERT` when compiling the application. Hence, it should not be
496  * used in unit tests, where assertions should always be effective.
497  */
498
499 /**
500  * g_assert_true:
501  * @expr: the expression to check
502  *
503  * Debugging macro to check that an expression is true.
504  *
505  * If the assertion fails (i.e. the expression is not true),
506  * an error message is logged and the application is either
507  * terminated or the testcase marked as failed.
508  *
509  * Note that unlike g_assert(), this macro is unaffected by whether
510  * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
511  * conversely, g_assert() should not be used in tests.
512  *
513  * See g_test_set_nonfatal_assertions().
514  *
515  * Since: 2.38
516  */
517
518 /**
519  * g_assert_false:
520  * @expr: the expression to check
521  *
522  * Debugging macro to check an expression is false.
523  *
524  * If the assertion fails (i.e. the expression is not false),
525  * an error message is logged and the application is either
526  * terminated or the testcase marked as failed.
527  *
528  * Note that unlike g_assert(), this macro is unaffected by whether
529  * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
530  * conversely, g_assert() should not be used in tests.
531  *
532  * See g_test_set_nonfatal_assertions().
533  *
534  * Since: 2.38
535  */
536
537 /**
538  * g_assert_null:
539  * @expr: the expression to check
540  *
541  * Debugging macro to check an expression is %NULL.
542  *
543  * If the assertion fails (i.e. the expression is not %NULL),
544  * an error message is logged and the application is either
545  * terminated or the testcase marked as failed.
546  *
547  * Note that unlike g_assert(), this macro is unaffected by whether
548  * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
549  * conversely, g_assert() should not be used in tests.
550  *
551  * See g_test_set_nonfatal_assertions().
552  *
553  * Since: 2.38
554  */
555
556 /**
557  * g_assert_nonnull:
558  * @expr: the expression to check
559  *
560  * Debugging macro to check an expression is not %NULL.
561  *
562  * If the assertion fails (i.e. the expression is %NULL),
563  * an error message is logged and the application is either
564  * terminated or the testcase marked as failed.
565  *
566  * Note that unlike g_assert(), this macro is unaffected by whether
567  * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
568  * conversely, g_assert() should not be used in tests.
569  *
570  * See g_test_set_nonfatal_assertions().
571  *
572  * Since: 2.40
573  */
574
575 /**
576  * g_assert_cmpstr:
577  * @s1: a string (may be %NULL)
578  * @cmp: The comparison operator to use.
579  *     One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
580  * @s2: another string (may be %NULL)
581  *
582  * Debugging macro to compare two strings. If the comparison fails,
583  * an error message is logged and the application is either terminated
584  * or the testcase marked as failed.
585  * The strings are compared using g_strcmp0().
586  *
587  * The effect of `g_assert_cmpstr (s1, op, s2)` is
588  * the same as `g_assert_true (g_strcmp0 (s1, s2) op 0)`.
589  * The advantage of this macro is that it can produce a message that
590  * includes the actual values of @s1 and @s2.
591  *
592  * |[<!-- language="C" --> 
593  *   g_assert_cmpstr (mystring, ==, "fubar");
594  * ]|
595  *
596  * Since: 2.16
597  */
598
599 /**
600  * g_assert_cmpstrv:
601  * @strv1: (nullable): a string array (may be %NULL)
602  * @strv2: (nullable): another string array (may be %NULL)
603  *
604  * Debugging macro to check if two %NULL-terminated string arrays (i.e. 2
605  * #GStrv) are equal. If they are not equal, an error message is logged and the
606  * application is either terminated or the testcase marked as failed.
607  * If both arrays are %NULL, the check passes. If one array is %NULL but the
608  * other is not, an error message is logged.
609  *
610  * The effect of `g_assert_cmpstrv (strv1, strv2)` is the same as
611  * `g_assert_true (g_strv_equal (strv1, strv2))` (if both arrays are not
612  * %NULL). The advantage of this macro is that it can produce a message that
613  * includes how @strv1 and @strv2 are different.
614  *
615  * |[<!-- language="C" -->
616  *   const char *expected[] = { "one", "two", "three", NULL };
617  *   g_assert_cmpstrv (mystrv, expected);
618  * ]|
619  *
620  * Since: 2.68
621  */
622
623 /**
624  * g_assert_cmpint:
625  * @n1: an integer
626  * @cmp: The comparison operator to use.
627  *     One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
628  * @n2: another integer
629  *
630  * Debugging macro to compare two integers.
631  *
632  * The effect of `g_assert_cmpint (n1, op, n2)` is
633  * the same as `g_assert_true (n1 op n2)`. The advantage
634  * of this macro is that it can produce a message that includes the
635  * actual values of @n1 and @n2.
636  *
637  * Since: 2.16
638  */
639
640 /**
641  * g_assert_cmpuint:
642  * @n1: an unsigned integer
643  * @cmp: The comparison operator to use.
644  *     One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
645  * @n2: another unsigned integer
646  *
647  * Debugging macro to compare two unsigned integers.
648  *
649  * The effect of `g_assert_cmpuint (n1, op, n2)` is
650  * the same as `g_assert_true (n1 op n2)`. The advantage
651  * of this macro is that it can produce a message that includes the
652  * actual values of @n1 and @n2.
653  *
654  * Since: 2.16
655  */
656
657 /**
658  * g_assert_cmphex:
659  * @n1: an unsigned integer
660  * @cmp: The comparison operator to use.
661  *     One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
662  * @n2: another unsigned integer
663  *
664  * Debugging macro to compare to unsigned integers.
665  *
666  * This is a variant of g_assert_cmpuint() that displays the numbers
667  * in hexadecimal notation in the message.
668  *
669  * Since: 2.16
670  */
671
672 /**
673  * g_assert_cmpfloat:
674  * @n1: a floating point number
675  * @cmp: The comparison operator to use.
676  *     One of `==`, `!=`, `<`, `>`, `<=`, `>=`.
677  * @n2: another floating point number
678  *
679  * Debugging macro to compare two floating point numbers.
680  *
681  * The effect of `g_assert_cmpfloat (n1, op, n2)` is
682  * the same as `g_assert_true (n1 op n2)`. The advantage
683  * of this macro is that it can produce a message that includes the
684  * actual values of @n1 and @n2.
685  *
686  * Since: 2.16
687  */
688
689 /**
690  * g_assert_cmpfloat_with_epsilon:
691  * @n1: a floating point number
692  * @n2: another floating point number
693  * @epsilon: a numeric value that expresses the expected tolerance
694  *   between @n1 and @n2
695  *
696  * Debugging macro to compare two floating point numbers within an epsilon.
697  *
698  * The effect of `g_assert_cmpfloat_with_epsilon (n1, n2, epsilon)` is
699  * the same as `g_assert_true (abs (n1 - n2) < epsilon)`. The advantage
700  * of this macro is that it can produce a message that includes the
701  * actual values of @n1 and @n2.
702  *
703  * Since: 2.58
704  */
705
706 /**
707  * g_assert_no_errno:
708  * @expr: the expression to check
709  *
710  * Debugging macro to check that an expression has a non-negative return value,
711  * as used by traditional POSIX functions (such as `rmdir()`) to indicate
712  * success.
713  *
714  * If the assertion fails (i.e. the @expr returns a negative value), an error
715  * message is logged and the testcase is marked as failed. The error message
716  * will contain the value of `errno` and its human-readable message from
717  * g_strerror().
718  *
719  * This macro will clear the value of `errno` before executing @expr.
720  *
721  * Since: 2.66
722  */
723
724 /**
725  * g_assert_cmpmem:
726  * @m1: (nullable): pointer to a buffer
727  * @l1: length of @m1
728  * @m2: (nullable): pointer to another buffer
729  * @l2: length of @m2
730  *
731  * Debugging macro to compare memory regions. If the comparison fails,
732  * an error message is logged and the application is either terminated
733  * or the testcase marked as failed.
734  *
735  * The effect of `g_assert_cmpmem (m1, l1, m2, l2)` is
736  * the same as `g_assert_true (l1 == l2 && memcmp (m1, m2, l1) == 0)`.
737  * The advantage of this macro is that it can produce a message that
738  * includes the actual values of @l1 and @l2.
739  *
740  * @m1 may be %NULL if (and only if) @l1 is zero; similarly for @m2 and @l2.
741  *
742  * |[<!-- language="C" -->
743  *   g_assert_cmpmem (buf->data, buf->len, expected, sizeof (expected));
744  * ]|
745  *
746  * Since: 2.46
747  */
748
749 /**
750  * g_assert_cmpvariant:
751  * @v1: pointer to a #GVariant
752  * @v2: pointer to another #GVariant
753  *
754  * Debugging macro to compare two #GVariants. If the comparison fails,
755  * an error message is logged and the application is either terminated
756  * or the testcase marked as failed. The variants are compared using
757  * g_variant_equal().
758  *
759  * The effect of `g_assert_cmpvariant (v1, v2)` is the same as
760  * `g_assert_true (g_variant_equal (v1, v2))`. The advantage of this macro is
761  * that it can produce a message that includes the actual values of @v1 and @v2.
762  *
763  * Since: 2.60
764  */
765
766 /**
767  * g_assert_no_error:
768  * @err: a #GError, possibly %NULL
769  *
770  * Debugging macro to check that a #GError is not set.
771  *
772  * The effect of `g_assert_no_error (err)` is
773  * the same as `g_assert_true (err == NULL)`. The advantage
774  * of this macro is that it can produce a message that includes
775  * the error message and code.
776  *
777  * Since: 2.20
778  */
779
780 /**
781  * g_assert_error:
782  * @err: a #GError, possibly %NULL
783  * @dom: the expected error domain (a #GQuark)
784  * @c: the expected error code
785  *
786  * Debugging macro to check that a method has returned
787  * the correct #GError.
788  *
789  * The effect of `g_assert_error (err, dom, c)` is
790  * the same as `g_assert_true (err != NULL && err->domain
791  * == dom && err->code == c)`. The advantage of this
792  * macro is that it can produce a message that includes the incorrect
793  * error message and code.
794  *
795  * This can only be used to test for a specific error. If you want to
796  * test that @err is set, but don't care what it's set to, just use
797  * `g_assert_nonnull (err)`.
798  *
799  * Since: 2.20
800  */
801
802 /**
803  * GTestCase:
804  *
805  * An opaque structure representing a test case.
806  */
807
808 /**
809  * GTestSuite:
810  *
811  * An opaque structure representing a test suite.
812  */
813
814
815 /* Global variable for storing assertion messages; this is the counterpart to
816  * glibc's (private) __abort_msg variable, and allows developers and crash
817  * analysis systems like Apport and ABRT to fish out assertion messages from
818  * core dumps, instead of having to catch them on screen output.
819  */
820 GLIB_VAR char *__glib_assert_msg;
821 char *__glib_assert_msg = NULL;
822
823 /* --- constants --- */
824 #define G_TEST_STATUS_TIMED_OUT 1024
825
826 /* --- structures --- */
827 struct GTestCase
828 {
829   gchar  *name;
830   guint   fixture_size;
831   void   (*fixture_setup)    (void*, gconstpointer);
832   void   (*fixture_test)     (void*, gconstpointer);
833   void   (*fixture_teardown) (void*, gconstpointer);
834   gpointer test_data;
835 };
836 struct GTestSuite
837 {
838   gchar  *name;
839   GSList *suites;
840   GSList *cases;
841 };
842 typedef struct DestroyEntry DestroyEntry;
843 struct DestroyEntry
844 {
845   DestroyEntry *next;
846   GDestroyNotify destroy_func;
847   gpointer       destroy_data;
848 };
849
850 /* --- prototypes --- */
851 static void     test_cleanup                    (void);
852 static void     test_run_seed                   (const gchar *rseed);
853 static void     test_trap_clear                 (void);
854 static guint8*  g_test_log_dump                 (GTestLogMsg *msg,
855                                                  guint       *len);
856 static void     gtest_default_log_handler       (const gchar    *log_domain,
857                                                  GLogLevelFlags  log_level,
858                                                  const gchar    *message,
859                                                  gpointer        unused_data);
860 static void     g_test_tap_print                (unsigned    subtest_level,
861                                                  gboolean    commented,
862                                                  const char *format,
863                                                  ...) G_GNUC_PRINTF (3, 4);
864
865 static const char * const g_test_result_names[] = {
866   "OK",
867   "SKIP",
868   "FAIL",
869   "TODO"
870 };
871
872 /* --- variables --- */
873 static int         test_log_fd = -1;
874 static gboolean    test_mode_fatal = TRUE;
875 static gboolean    g_test_run_once = TRUE;
876 static gboolean    test_isolate_dirs = FALSE;
877 static gchar      *test_isolate_dirs_tmpdir = NULL;
878 static const gchar *test_tmpdir = NULL;
879 static gboolean    test_run_list = FALSE;
880 static gchar      *test_run_seedstr = NULL;
881 G_LOCK_DEFINE_STATIC (test_run_rand);
882 static GRand      *test_run_rand = NULL;
883 static gchar      *test_run_name = "";
884 static gchar      *test_run_name_path = "";
885 static GSList    **test_filename_free_list;
886 static guint       test_run_forks = 0;
887 static guint       test_run_count = 0;
888 static guint       test_count = 0;
889 static guint       test_skipped_count = 0;
890 static GTestResult test_run_success = G_TEST_RUN_FAILURE;
891 static gchar      *test_run_msg = NULL;
892 static guint       test_startup_skip_count = 0;
893 static GTimer     *test_user_timer = NULL;
894 static double      test_user_stamp = 0;
895 static GSList     *test_paths = NULL;
896 static gboolean    test_prefix = FALSE;
897 static gboolean    test_prefix_extended = FALSE;
898 static GSList     *test_paths_skipped = NULL;
899 static gboolean    test_prefix_skipped = FALSE;
900 static gboolean    test_prefix_extended_skipped = FALSE;
901 static GTestSuite *test_suite_root = NULL;
902 static int         test_trap_last_status = 0;  /* unmodified platform-specific status */
903 static GPid        test_trap_last_pid = 0;
904 static char       *test_trap_last_subprocess = NULL;
905 static char       *test_trap_last_stdout = NULL;
906 static char       *test_trap_last_stderr = NULL;
907 static char       *test_uri_base = NULL;
908 static gboolean    test_debug_log = FALSE;
909 static gboolean    test_tap_log = TRUE;  /* default to TAP as of GLib 2.62; see #1619; the non-TAP output mode is deprecated */
910 static gboolean    test_nonfatal_assertions = FALSE;
911 static DestroyEntry *test_destroy_queue = NULL;
912 static const char *test_argv0 = NULL;           /* (nullable), points into global argv */
913 static char       *test_argv0_dirname = NULL;   /* owned by GLib */
914 static const char *test_disted_files_dir;       /* points into test_argv0_dirname or an environment variable */
915 static const char *test_built_files_dir;        /* points into test_argv0_dirname or an environment variable */
916 static char       *test_initial_cwd = NULL;
917 static gboolean    test_in_forked_child = FALSE;
918 static gboolean    test_in_subprocess = FALSE;
919 static gboolean    test_is_subtest = FALSE;
920 static GTestConfig mutable_test_config_vars = {
921   FALSE,        /* test_initialized */
922   TRUE,         /* test_quick */
923   FALSE,        /* test_perf */
924   FALSE,        /* test_verbose */
925   FALSE,        /* test_quiet */
926   TRUE,         /* test_undefined */
927 };
928 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
929 static gboolean  no_g_set_prgname = FALSE;
930 static GPrintFunc g_default_print_func = NULL;
931
932 enum
933 {
934   G_TEST_CASE_LARGS_RESULT = 0,
935   G_TEST_CASE_LARGS_RUN_FORKS = 1,
936   G_TEST_CASE_LARGS_EXECUTION_TIME = 2,
937
938   G_TEST_CASE_LARGS_MAX
939 };
940
941 /* --- functions --- */
942 static inline gboolean
943 is_subtest (void)
944 {
945   return test_is_subtest || test_in_forked_child || test_in_subprocess;
946 }
947
948 static void
949 g_test_print_handler_full (const gchar *string,
950                            gboolean     use_tap_format,
951                            gboolean     is_tap_comment,
952                            unsigned     subtest_level)
953 {
954   g_assert (string != NULL);
955
956   if (G_LIKELY (use_tap_format) && strchr (string, '\n') != NULL)
957     {
958       static gboolean last_had_final_newline = TRUE;
959       GString *output = g_string_new_len (NULL, strlen (string) + 2);
960       const char *line = string;
961
962       do
963         {
964           const char *next = strchr (line, '\n');
965
966           if (last_had_final_newline && (next || *line != '\0'))
967             {
968               for (unsigned l = 0; l < subtest_level; ++l)
969                 g_string_append (output, TAP_SUBTEST_PREFIX);
970
971               if G_LIKELY (is_tap_comment)
972                 g_string_append (output, "# ");
973             }
974
975           if (next)
976             {
977               next += 1; /* Include the newline */
978               g_string_append_len (output, line, next - line);
979             }
980           else
981             {
982               g_string_append (output, line);
983               last_had_final_newline = (*line == '\0');
984             }
985
986           line = next;
987         }
988       while (line != NULL);
989
990       g_default_print_func (output->str);
991       g_string_free (g_steal_pointer (&output), TRUE);
992     }
993   else
994     {
995       g_default_print_func (string);
996     }
997 }
998
999 static void
1000 g_test_print_handler (const gchar *string)
1001 {
1002   g_test_print_handler_full (string, test_tap_log, TRUE, is_subtest () ? 1 : 0);
1003 }
1004
1005 static void
1006 g_test_tap_print (unsigned    subtest_level,
1007                   gboolean    commented,
1008                   const char *format,
1009                   ...)
1010 {
1011   va_list args;
1012   char *string;
1013
1014   va_start (args, format);
1015   string = g_strdup_vprintf (format, args);
1016   va_end (args);
1017
1018   g_test_print_handler_full (string, TRUE, commented, subtest_level);
1019   g_free (string);
1020 }
1021
1022 const char*
1023 g_test_log_type_name (GTestLogType log_type)
1024 {
1025   switch (log_type)
1026     {
1027     case G_TEST_LOG_NONE:               return "none";
1028     case G_TEST_LOG_ERROR:              return "error";
1029     case G_TEST_LOG_START_BINARY:       return "binary";
1030     case G_TEST_LOG_LIST_CASE:          return "list";
1031     case G_TEST_LOG_SKIP_CASE:          return "skip";
1032     case G_TEST_LOG_START_CASE:         return "start";
1033     case G_TEST_LOG_STOP_CASE:          return "stop";
1034     case G_TEST_LOG_MIN_RESULT:         return "minperf";
1035     case G_TEST_LOG_MAX_RESULT:         return "maxperf";
1036     case G_TEST_LOG_MESSAGE:            return "message";
1037     case G_TEST_LOG_START_SUITE:        return "start suite";
1038     case G_TEST_LOG_STOP_SUITE:         return "stop suite";
1039     }
1040   return "???";
1041 }
1042
1043 static void
1044 g_test_log_send (guint         n_bytes,
1045                  const guint8 *buffer)
1046 {
1047   if (test_log_fd >= 0)
1048     {
1049       int r;
1050       do
1051         r = write (test_log_fd, buffer, n_bytes);
1052       while (r < 0 && errno == EINTR);
1053     }
1054   if (test_debug_log)
1055     {
1056       GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
1057       GTestLogMsg *msg;
1058       GString *output;
1059       guint ui;
1060       g_test_log_buffer_push (lbuffer, n_bytes, buffer);
1061       msg = g_test_log_buffer_pop (lbuffer);
1062       g_warn_if_fail (msg != NULL);
1063       g_warn_if_fail (lbuffer->data->len == 0);
1064       g_test_log_buffer_free (lbuffer);
1065       /* print message */
1066       output = g_string_new (NULL);
1067       g_string_printf (output, "{*LOG(%s)", g_test_log_type_name (msg->log_type));
1068       for (ui = 0; ui < msg->n_strings; ui++)
1069         g_string_append_printf (output, ":{%s}", msg->strings[ui]);
1070       if (msg->n_nums)
1071         {
1072           g_string_append (output, ":(");
1073           for (ui = 0; ui < msg->n_nums; ui++)
1074             {
1075               if ((long double) (long) msg->nums[ui] == msg->nums[ui])
1076                 g_string_append_printf (output, "%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
1077               else
1078                 g_string_append_printf (output, "%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
1079             }
1080           g_string_append_c (output, ')');
1081         }
1082       g_string_append (output, ":LOG*}");
1083       g_printerr ("%s\n", output->str);
1084       g_string_free (output, TRUE);
1085       g_test_log_msg_free (msg);
1086     }
1087 }
1088
1089 static void
1090 g_test_log (GTestLogType lbit,
1091             const gchar *string1,
1092             const gchar *string2,
1093             guint        n_args,
1094             long double *largs)
1095 {
1096   GTestResult result;
1097   gboolean fail;
1098   GTestLogMsg msg;
1099   gchar *astrings[3] = { NULL, NULL, NULL };
1100   guint8 *dbuffer;
1101   guint32 dbufferlen;
1102   unsigned subtest_level;
1103   gdouble timing;
1104
1105   if (g_once_init_enter (&g_default_print_func))
1106     {
1107       g_once_init_leave (&g_default_print_func,
1108                          g_set_print_handler (g_test_print_handler));
1109       g_assert_nonnull (g_default_print_func);
1110     }
1111
1112   subtest_level = is_subtest () ? 1 : 0;
1113
1114   switch (lbit)
1115     {
1116     case G_TEST_LOG_START_BINARY:
1117       if (test_tap_log)
1118         {
1119           if (!is_subtest ())
1120             {
1121               g_test_tap_print (0, FALSE, "TAP version " TAP_VERSION "\n");
1122             }
1123           else
1124             {
1125               g_test_tap_print (subtest_level > 0 ? subtest_level - 1 : 0, TRUE,
1126                                 "Subtest: %s\n", test_argv0);
1127             }
1128
1129           g_print ("random seed: %s\n", string2);
1130         }
1131       else if (g_test_verbose ())
1132         {
1133           g_print ("GTest: random seed: %s\n", string2);
1134         }
1135       break;
1136     case G_TEST_LOG_START_SUITE:
1137       if (test_tap_log)
1138         {
1139           /* We only print the TAP "plan" (1..n) ahead of time if we did
1140            * not use the -p option to select specific tests to be run. */
1141           if (string1[0] != 0)
1142             g_print ("Start of %s tests\n", string1);
1143           else if (test_paths == NULL)
1144             g_test_tap_print (subtest_level, FALSE, "1..%d\n", test_count);
1145         }
1146       break;
1147     case G_TEST_LOG_STOP_SUITE:
1148       if (test_tap_log)
1149         {
1150           /* If we didn't print the TAP "plan" at the beginning because
1151            * we were using -p, we need to print how many tests we ran at
1152            * the end instead. */
1153           if (string1[0] != 0)
1154             g_print ("End of %s tests\n", string1);
1155           else if (test_paths != NULL)
1156             g_test_tap_print (subtest_level, FALSE, "1..%d\n", test_run_count);
1157         }
1158       break;
1159     case G_TEST_LOG_STOP_CASE:
1160       result = largs[G_TEST_CASE_LARGS_RESULT];
1161       timing = largs[G_TEST_CASE_LARGS_EXECUTION_TIME];
1162       fail = result == G_TEST_RUN_FAILURE;
1163       if (test_tap_log)
1164         {
1165           GString *tap_output;
1166
1167           /* The TAP representation for an expected failure starts with
1168            * "not ok", even though it does not actually count as failing
1169            * due to the use of the TODO directive. "ok # TODO" would mean
1170            * a test that was expected to fail unexpectedly succeeded,
1171            * for which GTestResult does not currently have a
1172            * representation. */
1173           if (fail || result == G_TEST_RUN_INCOMPLETE)
1174             tap_output = g_string_new ("not ok");
1175           else
1176             tap_output = g_string_new ("ok");
1177
1178           if (is_subtest ())
1179             g_string_prepend (tap_output, TAP_SUBTEST_PREFIX);
1180
1181           g_string_append_printf (tap_output, " %d %s", test_run_count, string1);
1182           if (result == G_TEST_RUN_INCOMPLETE)
1183             g_string_append_printf (tap_output, " # TODO %s", string2 ? string2 : "");
1184           else if (result == G_TEST_RUN_SKIPPED)
1185             g_string_append_printf (tap_output, " # SKIP %s", string2 ? string2 : "");
1186           else if (result == G_TEST_RUN_FAILURE && string2 != NULL)
1187             g_string_append_printf (tap_output, " - %s", string2);
1188
1189           g_string_append_c (tap_output, '\n');
1190           g_default_print_func (tap_output->str);
1191           g_string_free (g_steal_pointer (&tap_output), TRUE);
1192
1193           /* Print msg for any slow tests, where 'slow' means >= 0.5 secs */
1194           if (timing > 0.5)
1195             {
1196               tap_output = g_string_new ("# ");
1197               g_string_append_printf (tap_output, "slow test %s executed in %0.2lf secs\n",
1198                                       string1, timing);
1199               g_default_print_func (tap_output->str);
1200               g_string_free (g_steal_pointer (&tap_output), TRUE);
1201             }
1202         }
1203       else if (g_test_verbose ())
1204         g_print ("GTest: result: %s\n", g_test_result_names[result]);
1205       else if (!g_test_quiet () && !test_in_subprocess)
1206         g_print ("%s\n", g_test_result_names[result]);
1207       if (fail && test_mode_fatal)
1208         {
1209           if (test_tap_log)
1210             g_test_tap_print (0, FALSE, "Bail out!\n");
1211           g_abort ();
1212         }
1213       if (result == G_TEST_RUN_SKIPPED || result == G_TEST_RUN_INCOMPLETE)
1214         test_skipped_count++;
1215       break;
1216     case G_TEST_LOG_SKIP_CASE:
1217       if (test_tap_log)
1218         {
1219           g_test_tap_print (subtest_level, FALSE, "ok %d %s # SKIP\n",
1220                             test_run_count, string1);
1221         }
1222       break;
1223     case G_TEST_LOG_MIN_RESULT:
1224       if (test_tap_log)
1225         g_print ("min perf: %s\n", string1);
1226       else if (g_test_verbose ())
1227         g_print ("(MINPERF:%s)\n", string1);
1228       break;
1229     case G_TEST_LOG_MAX_RESULT:
1230       if (test_tap_log)
1231         g_print ("max perf: %s\n", string1);
1232       else if (g_test_verbose ())
1233         g_print ("(MAXPERF:%s)\n", string1);
1234       break;
1235     case G_TEST_LOG_MESSAGE:
1236       if (test_tap_log)
1237         g_print ("%s\n", string1);
1238       else if (g_test_verbose ())
1239         g_print ("(MSG: %s)\n", string1);
1240       break;
1241     case G_TEST_LOG_ERROR:
1242       if (test_tap_log)
1243         {
1244           char *message = g_strdup (string1);
1245
1246           if (message)
1247             {
1248               char *line = message;
1249
1250               while ((line = strchr (line, '\n')))
1251                   *(line++) = ' ';
1252
1253               message = g_strstrip (message);
1254             }
1255
1256           if (test_run_name && *test_run_name != '\0')
1257             {
1258               if (message && *message != '\0')
1259                 g_test_tap_print (subtest_level, FALSE, "not ok %s - %s\n",
1260                                   test_run_name, message);
1261               else
1262                 g_test_tap_print (subtest_level, FALSE, "not ok %s\n",
1263                                   test_run_name);
1264
1265               g_clear_pointer (&message, g_free);
1266             }
1267
1268           if (message && *message != '\0')
1269             g_test_tap_print (subtest_level, FALSE, "Bail out! %s\n", message);
1270           else
1271             g_test_tap_print (subtest_level, FALSE, "Bail out!\n");
1272
1273           g_free (message);
1274         }
1275       else if (g_test_verbose ())
1276         {
1277           g_print ("(ERROR: %s)\n", string1);
1278         }
1279       break;
1280     default: ;
1281     }
1282
1283   msg.log_type = lbit;
1284   msg.n_strings = (string1 != NULL) + (string1 && string2);
1285   msg.strings = astrings;
1286   astrings[0] = (gchar*) string1;
1287   astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
1288   msg.n_nums = n_args;
1289   msg.nums = largs;
1290   dbuffer = g_test_log_dump (&msg, &dbufferlen);
1291   g_test_log_send (dbufferlen, dbuffer);
1292   g_free (dbuffer);
1293
1294   switch (lbit)
1295     {
1296     case G_TEST_LOG_START_CASE:
1297       if (test_tap_log)
1298         ;
1299       else if (g_test_verbose ())
1300         g_print ("GTest: run: %s\n", string1);
1301       else if (!g_test_quiet ())
1302         g_print ("%s: ", string1);
1303       break;
1304     default: ;
1305     }
1306 }
1307
1308 /**
1309  * g_test_disable_crash_reporting:
1310  *
1311  * Attempt to disable system crash reporting infrastructure.
1312  *
1313  * This function should be called before exercising code paths that are
1314  * expected or intended to crash, to avoid wasting resources in system-wide
1315  * crash collection infrastructure such as systemd-coredump or abrt.
1316  *
1317  * Since: 2.78
1318  */
1319 void
1320 g_test_disable_crash_reporting (void)
1321 {
1322 #ifdef HAVE_SYS_RESOURCE_H
1323   struct rlimit limit = { 0, 0 };
1324
1325   (void) setrlimit (RLIMIT_CORE, &limit);
1326 #endif
1327
1328 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1329   /* On Linux, RLIMIT_CORE = 0 is ignored if core dumps are
1330    * configured to be written to a pipe, but PR_SET_DUMPABLE is not. */
1331   (void) prctl (PR_SET_DUMPABLE, 0, 0, 0, 0);
1332 #endif
1333 }
1334
1335 /* We intentionally parse the command line without GOptionContext
1336  * because otherwise you would never be able to test it.
1337  */
1338 static void
1339 parse_args (gint    *argc_p,
1340             gchar ***argv_p)
1341 {
1342   guint argc = *argc_p;
1343   gchar **argv = *argv_p;
1344   guint i, e;
1345
1346   test_argv0 = argv[0];  /* will be NULL iff argc == 0 */
1347   test_initial_cwd = g_get_current_dir ();
1348
1349   /* parse known args */
1350   for (i = 1; i < argc; i++)
1351     {
1352       if (strcmp (argv[i], "--g-fatal-warnings") == 0)
1353         {
1354           GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1355           fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1356           g_log_set_always_fatal (fatal_mask);
1357           argv[i] = NULL;
1358         }
1359       else if (strcmp (argv[i], "--keep-going") == 0 ||
1360                strcmp (argv[i], "-k") == 0)
1361         {
1362           test_mode_fatal = FALSE;
1363           argv[i] = NULL;
1364         }
1365       else if (strcmp (argv[i], "--debug-log") == 0)
1366         {
1367           test_debug_log = TRUE;
1368           argv[i] = NULL;
1369         }
1370       else if (strcmp (argv[i], "--tap") == 0)
1371         {
1372           test_tap_log = TRUE;
1373           argv[i] = NULL;
1374         }
1375       else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
1376         {
1377           gchar *equal = argv[i] + 12;
1378           if (*equal == '=')
1379             test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
1380           else if (i + 1 < argc)
1381             {
1382               argv[i++] = NULL;
1383               test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
1384             }
1385           argv[i] = NULL;
1386
1387           /* Force non-TAP output when using gtester */
1388           test_tap_log = FALSE;
1389         }
1390       else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
1391         {
1392           gchar *equal = argv[i] + 16;
1393           if (*equal == '=')
1394             test_startup_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
1395           else if (i + 1 < argc)
1396             {
1397               argv[i++] = NULL;
1398               test_startup_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
1399             }
1400           argv[i] = NULL;
1401         }
1402       else if (strcmp ("--GTestSubprocess", argv[i]) == 0)
1403         {
1404           test_in_subprocess = TRUE;
1405           /* We typically expect these child processes to crash, and some
1406            * tests spawn a *lot* of them.  Avoid spamming system crash
1407            * collection programs such as systemd-coredump and abrt.
1408            */
1409           g_test_disable_crash_reporting ();
1410
1411           argv[i] = NULL;
1412
1413           /* Force non-TAP output when spawning a subprocess, since people often
1414            * test the stdout/stderr of the subprocess strictly */
1415           test_tap_log = FALSE;
1416         }
1417       else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
1418         {
1419           gchar *equal = argv[i] + 2;
1420           if (*equal == '=')
1421             test_paths = g_slist_prepend (test_paths, equal + 1);
1422           else if (i + 1 < argc)
1423             {
1424               argv[i++] = NULL;
1425               test_paths = g_slist_prepend (test_paths, argv[i]);
1426             }
1427           argv[i] = NULL;
1428           if (test_prefix_extended) {
1429             printf ("do not mix [-r | --run-prefix] with '-p'\n");
1430             exit (1);
1431           }
1432           test_prefix = TRUE;
1433         }
1434       else if (strcmp ("-r", argv[i]) == 0 ||
1435                strncmp ("-r=", argv[i], 3) == 0 ||
1436                strcmp ("--run-prefix", argv[i]) == 0 ||
1437                strncmp ("--run-prefix=", argv[i], 13) == 0)
1438         {
1439             gchar *equal = argv[i] + 2;
1440             if (*equal == '=')
1441               test_paths = g_slist_prepend (test_paths, equal + 1);
1442             else if (i + 1 < argc)
1443               {
1444                 argv[i++] = NULL;
1445                 test_paths = g_slist_prepend (test_paths, argv[i]);
1446               }
1447             argv[i] = NULL;
1448             if (test_prefix) {
1449               printf ("do not mix [-r | --run-prefix] with '-p'\n");
1450               exit (1);
1451             }
1452             test_prefix_extended = TRUE;
1453         }
1454       else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
1455         {
1456           gchar *equal = argv[i] + 2;
1457           if (*equal == '=')
1458             test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
1459           else if (i + 1 < argc)
1460             {
1461               argv[i++] = NULL;
1462               test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
1463             }
1464           argv[i] = NULL;
1465           if (test_prefix_extended_skipped) {
1466             printf ("do not mix [-x | --skip-prefix] with '-s'\n");
1467             exit (1);
1468           }
1469           test_prefix_skipped = TRUE;
1470         }
1471       else if (strcmp ("-x", argv[i]) == 0 ||
1472                strncmp ("-x=", argv[i], 3) == 0 ||
1473                strcmp ("--skip-prefix", argv[i]) == 0 ||
1474                strncmp ("--skip-prefix=", argv[i], 14) == 0)
1475         {
1476           gchar *equal = argv[i] + 2;
1477           if (*equal == '=')
1478             test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
1479           else if (i + 1 < argc)
1480             {
1481               argv[i++] = NULL;
1482               test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
1483             }
1484           argv[i] = NULL;
1485           if (test_prefix_skipped) {
1486             printf ("do not mix [-x | --skip-prefix] with '-s'\n");
1487             exit (1);
1488           }
1489           test_prefix_extended_skipped = TRUE;
1490         }
1491       else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
1492         {
1493           gchar *equal = argv[i] + 2;
1494           const gchar *mode = "";
1495           if (*equal == '=')
1496             mode = equal + 1;
1497           else if (i + 1 < argc)
1498             {
1499               argv[i++] = NULL;
1500               mode = argv[i];
1501             }
1502           if (strcmp (mode, "perf") == 0)
1503             mutable_test_config_vars.test_perf = TRUE;
1504           else if (strcmp (mode, "slow") == 0)
1505             mutable_test_config_vars.test_quick = FALSE;
1506           else if (strcmp (mode, "thorough") == 0)
1507             mutable_test_config_vars.test_quick = FALSE;
1508           else if (strcmp (mode, "quick") == 0)
1509             {
1510               mutable_test_config_vars.test_quick = TRUE;
1511               mutable_test_config_vars.test_perf = FALSE;
1512             }
1513           else if (strcmp (mode, "undefined") == 0)
1514             mutable_test_config_vars.test_undefined = TRUE;
1515           else if (strcmp (mode, "no-undefined") == 0)
1516             mutable_test_config_vars.test_undefined = FALSE;
1517           else
1518             g_error ("unknown test mode: -m %s", mode);
1519           argv[i] = NULL;
1520         }
1521       else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
1522         {
1523           mutable_test_config_vars.test_quiet = TRUE;
1524           mutable_test_config_vars.test_verbose = FALSE;
1525           argv[i] = NULL;
1526         }
1527       else if (strcmp ("--verbose", argv[i]) == 0)
1528         {
1529           mutable_test_config_vars.test_quiet = FALSE;
1530           mutable_test_config_vars.test_verbose = TRUE;
1531           argv[i] = NULL;
1532         }
1533       else if (strcmp ("-l", argv[i]) == 0)
1534         {
1535           test_run_list = TRUE;
1536           argv[i] = NULL;
1537         }
1538       else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
1539         {
1540           gchar *equal = argv[i] + 6;
1541           if (*equal == '=')
1542             test_run_seedstr = equal + 1;
1543           else if (i + 1 < argc)
1544             {
1545               argv[i++] = NULL;
1546               test_run_seedstr = argv[i];
1547             }
1548           argv[i] = NULL;
1549         }
1550       else if (strcmp ("-?", argv[i]) == 0 ||
1551                strcmp ("-h", argv[i]) == 0 ||
1552                strcmp ("--help", argv[i]) == 0)
1553         {
1554           printf ("Usage:\n"
1555                   "  %s [OPTION...]\n\n"
1556                   "Help Options:\n"
1557                   "  -h, --help                     Show help options\n\n"
1558                   "Test Options:\n"
1559                   "  --g-fatal-warnings             Make all warnings fatal\n"
1560                   "  -l                             List test cases available in a test executable\n"
1561                   "  -m {perf|slow|thorough|quick}  Execute tests according to mode\n"
1562                   "  -m {undefined|no-undefined}    Execute tests according to mode\n"
1563                   "  -p TESTPATH                    Only start test cases matching TESTPATH\n"
1564                   "  -s TESTPATH                    Skip all tests matching TESTPATH\n"
1565                   "  [-r | --run-prefix] PREFIX     Only start test cases (or suites) matching PREFIX (incompatible with -p).\n"
1566                   "                                 Unlike the -p option (which only goes one level deep), this option would \n"
1567                   "                                 run all tests path that have PREFIX at the beginning of their name.\n"
1568                   "                                 Note that the prefix used should be a valid test path (and not a simple prefix).\n"
1569                   "  [-x | --skip-prefix] PREFIX    Skip all tests matching PREFIX (incompatible with -s)\n"
1570                   "                                 Unlike the -s option (which only skips the exact TESTPATH), this option will \n"
1571                   "                                 skip all the tests that begins with PREFIX).\n"
1572                   "  --seed=SEEDSTRING              Start tests with random seed SEEDSTRING\n"
1573                   "  --debug-log                    debug test logging output\n"
1574                   "  -q, --quiet                    Run tests quietly\n"
1575                   "  --verbose                      Run tests verbosely\n",
1576                   argv[0]);
1577           exit (0);
1578         }
1579     }
1580
1581   /* We've been prepending to test_paths, but its order matters, so
1582    * permute it */
1583   test_paths = g_slist_reverse (test_paths);
1584
1585   /* collapse argv */
1586   e = 0;
1587   for (i = 0; i < argc; i++)
1588     if (argv[i])
1589       {
1590         argv[e++] = argv[i];
1591         if (i >= e)
1592           argv[i] = NULL;
1593       }
1594   *argc_p = e;
1595 }
1596
1597 /* A fairly naive `rm -rf` implementation to clean up after unit tests. */
1598 static void
1599 rm_rf (const gchar *path)
1600 {
1601   GDir *dir = NULL;
1602   const gchar *entry;
1603
1604   dir = g_dir_open (path, 0, NULL);
1605   if (dir == NULL)
1606     {
1607       /* Assume it’s a file. Ignore failure. */
1608       (void) g_remove (path);
1609       return;
1610     }
1611
1612   while ((entry = g_dir_read_name (dir)) != NULL)
1613     {
1614       gchar *sub_path = g_build_filename (path, entry, NULL);
1615       rm_rf (sub_path);
1616       g_free (sub_path);
1617     }
1618
1619   g_dir_close (dir);
1620
1621   g_rmdir (path);
1622 }
1623
1624 /* Implement the %G_TEST_OPTION_ISOLATE_DIRS option, iff it’s enabled. Create
1625  * a temporary directory for this unit test (disambiguated using @test_run_name)
1626  * and use g_set_user_dirs() to point various XDG directories into it, without
1627  * having to call setenv() in a process which potentially has threads running.
1628  *
1629  * Note that this is called for each unit test, and hence won’t have taken
1630  * effect before g_test_run() is called in the unit test’s main(). Hence
1631  * references to XDG variables in main() will not be using the temporary
1632  * directory. */
1633 static gboolean
1634 test_do_isolate_dirs (GError **error)
1635 {
1636   gchar *subdir = NULL;
1637   gchar *home_dir = NULL, *cache_dir = NULL, *config_dir = NULL;
1638   gchar *state_dir = NULL, *data_dir = NULL, *runtime_dir = NULL;
1639   gchar *config_dirs[3];
1640   gchar *data_dirs[3];
1641
1642   if (!test_isolate_dirs)
1643     return TRUE;
1644
1645   /* The @test_run_name includes the test suites, so may be several directories
1646    * deep. Add a `.dirs` directory to contain all the paths we create, and
1647    * guarantee none of them clash with test paths below the current one — test
1648    * paths may not contain components starting with `.`. */
1649   subdir = g_build_filename (test_tmpdir, test_run_name_path, ".dirs", NULL);
1650
1651   /* We have to create the runtime directory (because it must be bound to
1652    * the session lifetime, which we consider to be the lifetime of the unit
1653    * test for testing purposes — see
1654    * https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html.
1655    * We don’t need to create the other directories — the specification
1656    * requires that client code create them if they don’t exist. Not creating
1657    * them automatically is a good test of clients’ adherence to the spec
1658    * and error handling of missing directories. */
1659   runtime_dir = g_build_filename (subdir, "runtime", NULL);
1660   if (g_mkdir_with_parents (runtime_dir, 0700) != 0)
1661     {
1662       gint saved_errno = errno;
1663       g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
1664                    "Failed to create XDG_RUNTIME_DIR ‘%s’: %s",
1665                   runtime_dir, g_strerror (saved_errno));
1666       g_free (runtime_dir);
1667       g_free (subdir);
1668       return FALSE;
1669     }
1670
1671   home_dir = g_build_filename (subdir, "home", NULL);
1672   cache_dir = g_build_filename (subdir, "cache", NULL);
1673   config_dir = g_build_filename (subdir, "config", NULL);
1674   data_dir = g_build_filename (subdir, "data", NULL);
1675   state_dir = g_build_filename (subdir, "state", NULL);
1676
1677   config_dirs[0] = g_build_filename (subdir, "system-config1", NULL);
1678   config_dirs[1] = g_build_filename (subdir, "system-config2", NULL);
1679   config_dirs[2] = NULL;
1680
1681   data_dirs[0] = g_build_filename (subdir, "system-data1", NULL);
1682   data_dirs[1] = g_build_filename (subdir, "system-data2", NULL);
1683   data_dirs[2] = NULL;
1684
1685   /* Remember to update the documentation for %G_TEST_OPTION_ISOLATE_DIRS if
1686    * this list changes. */
1687   g_set_user_dirs ("HOME", home_dir,
1688                    "XDG_CACHE_HOME", cache_dir,
1689                    "XDG_CONFIG_DIRS", config_dirs,
1690                    "XDG_CONFIG_HOME", config_dir,
1691                    "XDG_DATA_DIRS", data_dirs,
1692                    "XDG_DATA_HOME", data_dir,
1693                    "XDG_STATE_HOME", state_dir,
1694                    "XDG_RUNTIME_DIR", runtime_dir,
1695                    NULL);
1696
1697   g_free (runtime_dir);
1698   g_free (state_dir);
1699   g_free (data_dir);
1700   g_free (config_dir);
1701   g_free (cache_dir);
1702   g_free (home_dir);
1703   g_free (data_dirs[1]);
1704   g_free (data_dirs[0]);
1705   g_free (config_dirs[1]);
1706   g_free (config_dirs[0]);
1707   g_free (subdir);
1708
1709   return TRUE;
1710 }
1711
1712 /* Clean up after test_do_isolate_dirs(). */
1713 static void
1714 test_rm_isolate_dirs (void)
1715 {
1716   gchar *subdir = NULL;
1717
1718   if (!test_isolate_dirs)
1719     return;
1720
1721   subdir = g_build_filename (test_tmpdir, test_run_name_path, NULL);
1722   rm_rf (subdir);
1723   g_free (subdir);
1724 }
1725
1726 /**
1727  * g_test_init:
1728  * @argc: Address of the @argc parameter of the main() function.
1729  *        Changed if any arguments were handled.
1730  * @argv: Address of the @argv parameter of main().
1731  *        Any parameters understood by g_test_init() stripped before return.
1732  * @...: %NULL-terminated list of special options, documented below.
1733  *
1734  * Initialize the GLib testing framework, e.g. by seeding the
1735  * test random number generator, the name for g_get_prgname()
1736  * and parsing test related command line args.
1737  *
1738  * This should be called before calling any other `g_test_*()` functions.
1739  *
1740  * So far, the following arguments are understood:
1741  *
1742  * - `-l`: List test cases available in a test executable.
1743  * - `--seed=SEED`: Provide a random seed to reproduce test
1744  *   runs using random numbers.
1745  * - `--verbose`: Run tests verbosely.
1746  * - `-q`, `--quiet`: Run tests quietly.
1747  * - `-p PATH`: Execute all tests matching the given path.
1748  * - `-s PATH`: Skip all tests matching the given path.
1749  *   This can also be used to force a test to run that would otherwise
1750  *   be skipped (ie, a test whose name contains "/subprocess").
1751  * - `-m {perf|slow|thorough|quick|undefined|no-undefined}`: Execute tests according to these test modes:
1752  *
1753  *   `perf`: Performance tests, may take long and report results (off by default).
1754  *
1755  *   `slow`, `thorough`: Slow and thorough tests, may take quite long and maximize coverage
1756  *   (off by default).
1757  *
1758  *   `quick`: Quick tests, should run really quickly and give good coverage (the default).
1759  *
1760  *   `undefined`: Tests for undefined behaviour, may provoke programming errors
1761  *   under g_test_trap_subprocess() or g_test_expect_message() to check
1762  *   that appropriate assertions or warnings are given (the default).
1763  *
1764  *   `no-undefined`: Avoid tests for undefined behaviour
1765  *
1766  * - `--debug-log`: Debug test logging output.
1767  *
1768  * Options which can be passed to @... are:
1769  *
1770  *  - `"no_g_set_prgname"`: Causes g_test_init() to not call g_set_prgname().
1771  *  - %G_TEST_OPTION_ISOLATE_DIRS: Creates a unique temporary directory for each
1772  *    unit test and uses g_set_user_dirs() to set XDG directories to point into
1773  *    that temporary directory for the duration of the unit test. See the
1774  *    documentation for %G_TEST_OPTION_ISOLATE_DIRS.
1775  *
1776  * Since 2.58, if tests are compiled with `G_DISABLE_ASSERT` defined,
1777  * g_test_init() will print an error and exit. This is to prevent no-op tests
1778  * from being executed, as g_assert() is commonly (erroneously) used in unit
1779  * tests, and is a no-op when compiled with `G_DISABLE_ASSERT`. Ensure your
1780  * tests are compiled without `G_DISABLE_ASSERT` defined.
1781  *
1782  * Since: 2.16
1783  */
1784 void
1785 (g_test_init) (int    *argc,
1786                char ***argv,
1787                ...)
1788 {
1789   static char seedstr[4 + 4 * 8 + 1];
1790   va_list args;
1791   gpointer option;
1792   /* make warnings and criticals fatal for all test programs */
1793   GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1794
1795   fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1796   g_log_set_always_fatal (fatal_mask);
1797   /* check caller args */
1798   g_return_if_fail (argc != NULL);
1799   g_return_if_fail (argv != NULL);
1800   g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
1801   mutable_test_config_vars.test_initialized = TRUE;
1802
1803 #ifdef _GLIB_ADDRESS_SANITIZER
1804   mutable_test_config_vars.test_undefined = FALSE;
1805 #endif
1806
1807 #ifdef G_OS_WIN32
1808   // don't open a window for errors (like the "abort() was called one")
1809   _CrtSetReportMode (_CRT_ERROR, _CRTDBG_MODE_FILE);
1810   _CrtSetReportFile (_CRT_ERROR, _CRTDBG_FILE_STDERR);
1811   // while gtest tests tend to use g_assert and friends
1812   // if they do use the C standard assert macro we want to
1813   // output a message to stderr, not open a popup window
1814   _CrtSetReportMode (_CRT_ASSERT, _CRTDBG_MODE_FILE);
1815   _CrtSetReportFile (_CRT_ASSERT, _CRTDBG_FILE_STDERR);
1816   // in release mode abort() will pop up a windows error
1817   // reporting dialog, let's prevent that. Only msvcrxx and
1818   // the UCRT have this function, but there's no great way to
1819   // detect msvcrxx (that I know of) so only call this when using
1820   // the UCRT
1821 #ifdef _UCRT
1822   _set_abort_behavior (0, _CALL_REPORTFAULT);
1823 #endif
1824 #endif
1825
1826   va_start (args, argv);
1827   while ((option = va_arg (args, char *)))
1828     {
1829       if (g_strcmp0 (option, "no_g_set_prgname") == 0)
1830         no_g_set_prgname = TRUE;
1831       else if (g_strcmp0 (option, G_TEST_OPTION_ISOLATE_DIRS) == 0)
1832         test_isolate_dirs = TRUE;
1833     }
1834   va_end (args);
1835
1836   /* parse args, sets up mode, changes seed, etc. */
1837   parse_args (argc, argv);
1838
1839   if (test_run_seedstr == NULL)
1840     {
1841       /* setup random seed string */
1842       g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x",
1843                   g_random_int(), g_random_int(), g_random_int(), g_random_int());
1844       test_run_seedstr = seedstr;
1845     }
1846
1847   if (!g_get_prgname() && !no_g_set_prgname)
1848     g_set_prgname ((*argv)[0]);
1849
1850   if (g_getenv ("G_TEST_ROOT_PROCESS"))
1851     {
1852       test_is_subtest = TRUE;
1853     }
1854   else if (!g_setenv ("G_TEST_ROOT_PROCESS", test_argv0 ? test_argv0 : "root", TRUE))
1855     {
1856       g_printerr ("%s: Failed to set environment variable ‘%s’\n",
1857                   test_argv0, "G_TEST_ROOT_PROCESS");
1858       exit (1);
1859     }
1860
1861   /* Set up the temporary directory for isolating the test. We have to do this
1862    * early, as we want the return values from g_get_user_data_dir() (and
1863    * friends) to return subdirectories of the temporary directory throughout
1864    * the setup function, test, and teardown function, for each unit test.
1865    * See test_do_isolate_dirs().
1866    *
1867    * The directory is deleted at the bottom of g_test_run().
1868    *
1869    * Rather than setting the XDG_* environment variables we use a new
1870    * G_TEST_TMPDIR variable which gives the top-level temporary directory. This
1871    * allows test subprocesses to reuse the same temporary directory when
1872    * g_test_init() is called in them. */
1873   if (test_isolate_dirs)
1874     {
1875       if (g_getenv ("G_TEST_TMPDIR") == NULL)
1876         {
1877           gchar *test_prgname = NULL;
1878           gchar *tmpl = NULL;
1879           GError *local_error = NULL;
1880
1881           test_prgname = g_path_get_basename (g_get_prgname ());
1882           if (*test_prgname == '\0')
1883             {
1884               g_free (test_prgname);
1885               test_prgname = g_strdup ("unknown");
1886             }
1887           tmpl = g_strdup_printf ("test_%s_XXXXXX", test_prgname);
1888           g_free (test_prgname);
1889
1890           test_isolate_dirs_tmpdir = g_dir_make_tmp (tmpl, &local_error);
1891           if (local_error != NULL)
1892             {
1893               g_printerr ("%s: Failed to create temporary directory: %s\n",
1894                           (*argv)[0], local_error->message);
1895               g_error_free (local_error);
1896               exit (1);
1897             }
1898           g_free (tmpl);
1899
1900           /* Propagate the temporary directory to subprocesses. */
1901           if (!g_setenv ("G_TEST_TMPDIR", test_isolate_dirs_tmpdir, TRUE))
1902             {
1903               g_printerr ("%s: Failed to set environment variable ‘%s’\n",
1904                           (*argv)[0], "G_TEST_TMPDIR");
1905               exit (1);
1906             }
1907           _g_unset_cached_tmp_dir ();
1908
1909           /* And clear the traditional environment variables so subprocesses
1910            * spawned by the code under test can’t trash anything. If a test
1911            * spawns a process, the test is responsible for propagating
1912            * appropriate environment variables.
1913            *
1914            * We assume that any in-process code will use g_get_user_data_dir()
1915            * and friends, rather than getenv() directly.
1916            *
1917            * We set them to ‘/dev/null’ as that should fairly obviously not
1918            * accidentally work, and should be fairly greppable. */
1919             {
1920               const gchar *overridden_environment_variables[] =
1921                 {
1922                   "HOME",
1923                   "XDG_CACHE_HOME",
1924                   "XDG_CONFIG_DIRS",
1925                   "XDG_CONFIG_HOME",
1926                   "XDG_DATA_DIRS",
1927                   "XDG_DATA_HOME",
1928                   "XDG_RUNTIME_DIR",
1929                 };
1930               gsize i;
1931
1932               for (i = 0; i < G_N_ELEMENTS (overridden_environment_variables); i++)
1933                 {
1934                   if (!g_setenv (overridden_environment_variables[i], "/dev/null", TRUE))
1935                     {
1936                       g_printerr ("%s: Failed to set environment variable ‘%s’\n",
1937                                   (*argv)[0], overridden_environment_variables[i]);
1938                       exit (1);
1939                     }
1940                 }
1941             }
1942         }
1943
1944       /* Cache this for the remainder of this process’ lifetime. */
1945       test_tmpdir = g_getenv ("G_TEST_TMPDIR");
1946     }
1947
1948   /* verify GRand reliability, needed for reliable seeds */
1949   if (1)
1950     {
1951       GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
1952       guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
1953       /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
1954       if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
1955         g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
1956       g_rand_free (rg);
1957     }
1958
1959   /* check rand seed */
1960   test_run_seed (test_run_seedstr);
1961
1962   /* report program start */
1963   g_log_set_default_handler (gtest_default_log_handler, NULL);
1964   g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
1965
1966   test_argv0_dirname = (test_argv0 != NULL) ? g_path_get_dirname (test_argv0) : g_strdup (".");
1967
1968   /* Make sure we get the real dirname that the test was run from */
1969   if (g_str_has_suffix (test_argv0_dirname, "/.libs"))
1970     {
1971       gchar *tmp;
1972       tmp = g_path_get_dirname (test_argv0_dirname);
1973       g_free (test_argv0_dirname);
1974       test_argv0_dirname = tmp;
1975     }
1976
1977   test_disted_files_dir = g_getenv ("G_TEST_SRCDIR");
1978   if (!test_disted_files_dir)
1979     test_disted_files_dir = test_argv0_dirname;
1980
1981   test_built_files_dir = g_getenv ("G_TEST_BUILDDIR");
1982   if (!test_built_files_dir)
1983     test_built_files_dir = test_argv0_dirname;
1984 }
1985
1986 static void
1987 test_cleanup (void)
1988 {
1989   /* Free statically allocated variables */
1990
1991   g_clear_pointer (&test_run_rand, g_rand_free);
1992
1993   g_clear_pointer (&test_argv0_dirname, g_free);
1994
1995   g_clear_pointer (&test_initial_cwd, g_free);
1996 }
1997
1998 static void
1999 test_run_seed (const gchar *rseed)
2000 {
2001   guint seed_failed = 0;
2002   if (test_run_rand)
2003     g_rand_free (test_run_rand);
2004   test_run_rand = NULL;
2005   while (strchr (" \t\v\r\n\f", *rseed))
2006     rseed++;
2007   if (strncmp (rseed, "R02S", 4) == 0)  /* seed for random generator 02 (GRand-2.2) */
2008     {
2009       const char *s = rseed + 4;
2010       if (strlen (s) >= 32)             /* require 4 * 8 chars */
2011         {
2012           guint32 seedarray[4];
2013           gchar *p, hexbuf[9] = { 0, };
2014           memcpy (hexbuf, s + 0, 8);
2015           seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
2016           seed_failed += p != NULL && *p != 0;
2017           memcpy (hexbuf, s + 8, 8);
2018           seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
2019           seed_failed += p != NULL && *p != 0;
2020           memcpy (hexbuf, s + 16, 8);
2021           seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
2022           seed_failed += p != NULL && *p != 0;
2023           memcpy (hexbuf, s + 24, 8);
2024           seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
2025           seed_failed += p != NULL && *p != 0;
2026           if (!seed_failed)
2027             {
2028               test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
2029               return;
2030             }
2031         }
2032     }
2033   g_error ("Unknown or invalid random seed: %s", rseed);
2034 }
2035
2036 /**
2037  * g_test_rand_int:
2038  *
2039  * Get a reproducible random integer number.
2040  *
2041  * The random numbers generated by the g_test_rand_*() family of functions
2042  * change with every new test program start, unless the --seed option is
2043  * given when starting test programs.
2044  *
2045  * For individual test cases however, the random number generator is
2046  * reseeded, to avoid dependencies between tests and to make --seed
2047  * effective for all test cases.
2048  *
2049  * Returns: a random number from the seeded random number generator.
2050  *
2051  * Since: 2.16
2052  */
2053 gint32
2054 g_test_rand_int (void)
2055 {
2056   gint32 r;
2057
2058   G_LOCK (test_run_rand);
2059   r = g_rand_int (test_run_rand);
2060   G_UNLOCK (test_run_rand);
2061
2062   return r;
2063 }
2064
2065 /**
2066  * g_test_rand_int_range:
2067  * @begin: the minimum value returned by this function
2068  * @end:   the smallest value not to be returned by this function
2069  *
2070  * Get a reproducible random integer number out of a specified range,
2071  * see g_test_rand_int() for details on test case random numbers.
2072  *
2073  * Returns: a number with @begin <= number < @end.
2074  * 
2075  * Since: 2.16
2076  */
2077 gint32
2078 g_test_rand_int_range (gint32          begin,
2079                        gint32          end)
2080 {
2081   gint32 r;
2082
2083   G_LOCK (test_run_rand);
2084   r = g_rand_int_range (test_run_rand, begin, end);
2085   G_UNLOCK (test_run_rand);
2086
2087   return r;
2088 }
2089
2090 /**
2091  * g_test_rand_double:
2092  *
2093  * Get a reproducible random floating point number,
2094  * see g_test_rand_int() for details on test case random numbers.
2095  *
2096  * Returns: a random number from the seeded random number generator.
2097  *
2098  * Since: 2.16
2099  */
2100 double
2101 g_test_rand_double (void)
2102 {
2103   double r;
2104
2105   G_LOCK (test_run_rand);
2106   r = g_rand_double (test_run_rand);
2107   G_UNLOCK (test_run_rand);
2108
2109   return r;
2110 }
2111
2112 /**
2113  * g_test_rand_double_range:
2114  * @range_start: the minimum value returned by this function
2115  * @range_end: the minimum value not returned by this function
2116  *
2117  * Get a reproducible random floating pointer number out of a specified range,
2118  * see g_test_rand_int() for details on test case random numbers.
2119  *
2120  * Returns: a number with @range_start <= number < @range_end.
2121  *
2122  * Since: 2.16
2123  */
2124 double
2125 g_test_rand_double_range (double          range_start,
2126                           double          range_end)
2127 {
2128   double r;
2129
2130   G_LOCK (test_run_rand);
2131   r = g_rand_double_range (test_run_rand, range_start, range_end);
2132   G_UNLOCK (test_run_rand);
2133
2134   return r;
2135 }
2136
2137 /**
2138  * g_test_timer_start:
2139  *
2140  * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
2141  * to be done. Call this function again to restart the timer.
2142  *
2143  * Since: 2.16
2144  */
2145 void
2146 g_test_timer_start (void)
2147 {
2148   if (!test_user_timer)
2149     test_user_timer = g_timer_new();
2150   test_user_stamp = 0;
2151   g_timer_start (test_user_timer);
2152 }
2153
2154 /**
2155  * g_test_timer_elapsed:
2156  *
2157  * Get the number of seconds since the last start of the timer with
2158  * g_test_timer_start().
2159  *
2160  * Returns: the time since the last start of the timer in seconds, as a double
2161  *
2162  * Since: 2.16
2163  */
2164 double
2165 g_test_timer_elapsed (void)
2166 {
2167   test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
2168   return test_user_stamp;
2169 }
2170
2171 /**
2172  * g_test_timer_last:
2173  *
2174  * Report the last result of g_test_timer_elapsed().
2175  *
2176  * Returns: the last result of g_test_timer_elapsed(), as a double
2177  *
2178  * Since: 2.16
2179  */
2180 double
2181 g_test_timer_last (void)
2182 {
2183   return test_user_stamp;
2184 }
2185
2186 /**
2187  * g_test_minimized_result:
2188  * @minimized_quantity: the reported value
2189  * @format: the format string of the report message
2190  * @...: arguments to pass to the printf() function
2191  *
2192  * Report the result of a performance or measurement test.
2193  * The test should generally strive to minimize the reported
2194  * quantities (smaller values are better than larger ones),
2195  * this and @minimized_quantity can determine sorting
2196  * order for test result reports.
2197  *
2198  * Since: 2.16
2199  */
2200 void
2201 g_test_minimized_result (double          minimized_quantity,
2202                          const char     *format,
2203                          ...)
2204 {
2205   long double largs = minimized_quantity;
2206   gchar *buffer;
2207   va_list args;
2208
2209   va_start (args, format);
2210   buffer = g_strdup_vprintf (format, args);
2211   va_end (args);
2212
2213   g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
2214   g_free (buffer);
2215 }
2216
2217 /**
2218  * g_test_maximized_result:
2219  * @maximized_quantity: the reported value
2220  * @format: the format string of the report message
2221  * @...: arguments to pass to the printf() function
2222  *
2223  * Report the result of a performance or measurement test.
2224  * The test should generally strive to maximize the reported
2225  * quantities (larger values are better than smaller ones),
2226  * this and @maximized_quantity can determine sorting
2227  * order for test result reports.
2228  *
2229  * Since: 2.16
2230  */
2231 void
2232 g_test_maximized_result (double          maximized_quantity,
2233                          const char     *format,
2234                          ...)
2235 {
2236   long double largs = maximized_quantity;
2237   gchar *buffer;
2238   va_list args;
2239
2240   va_start (args, format);
2241   buffer = g_strdup_vprintf (format, args);
2242   va_end (args);
2243
2244   g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
2245   g_free (buffer);
2246 }
2247
2248 /**
2249  * g_test_message:
2250  * @format: the format string
2251  * @...:    printf-like arguments to @format
2252  *
2253  * Add a message to the test report.
2254  *
2255  * Since: 2.16
2256  */
2257 void
2258 g_test_message (const char *format,
2259                 ...)
2260 {
2261   gchar *buffer;
2262   va_list args;
2263
2264   va_start (args, format);
2265   buffer = g_strdup_vprintf (format, args);
2266   va_end (args);
2267
2268   g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
2269   g_free (buffer);
2270 }
2271
2272 /**
2273  * g_test_bug_base:
2274  * @uri_pattern: the base pattern for bug URIs
2275  *
2276  * Specify the base URI for bug reports.
2277  *
2278  * The base URI is used to construct bug report messages for
2279  * g_test_message() when g_test_bug() is called.
2280  * Calling this function outside of a test case sets the
2281  * default base URI for all test cases. Calling it from within
2282  * a test case changes the base URI for the scope of the test
2283  * case only.
2284  * Bug URIs are constructed by appending a bug specific URI
2285  * portion to @uri_pattern, or by replacing the special string
2286  * `%s` within @uri_pattern if that is present.
2287  *
2288  * If g_test_bug_base() is not called, bug URIs are formed solely
2289  * from the value provided by g_test_bug().
2290  *
2291  * Since: 2.16
2292  */
2293 void
2294 g_test_bug_base (const char *uri_pattern)
2295 {
2296   g_free (test_uri_base);
2297   test_uri_base = g_strdup (uri_pattern);
2298 }
2299
2300 /**
2301  * g_test_bug:
2302  * @bug_uri_snippet: Bug specific bug tracker URI or URI portion.
2303  *
2304  * This function adds a message to test reports that
2305  * associates a bug URI with a test case.
2306  *
2307  * Bug URIs are constructed from a base URI set with g_test_bug_base()
2308  * and @bug_uri_snippet. If g_test_bug_base() has not been called, it is
2309  * assumed to be the empty string, so a full URI can be provided to
2310  * g_test_bug() instead.
2311  *
2312  * Since GLib 2.70, the base URI is not prepended to @bug_uri_snippet if it
2313  * is already a valid URI.
2314  *
2315  * Since: 2.16
2316  * See also: g_test_summary()
2317  */
2318 void
2319 g_test_bug (const char *bug_uri_snippet)
2320 {
2321   const char *c = NULL;
2322
2323   g_return_if_fail (bug_uri_snippet != NULL);
2324
2325   if (g_str_has_prefix (bug_uri_snippet, "http:") ||
2326       g_str_has_prefix (bug_uri_snippet, "https:"))
2327     {
2328       g_test_message ("Bug Reference: %s", bug_uri_snippet);
2329       return;
2330     }
2331
2332   if (test_uri_base != NULL)
2333     c = strstr (test_uri_base, "%s");
2334   if (c)
2335     {
2336       char *b = g_strndup (test_uri_base, c - test_uri_base);
2337       char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
2338       g_free (b);
2339       g_test_message ("Bug Reference: %s", s);
2340       g_free (s);
2341     }
2342   else
2343     g_test_message ("Bug Reference: %s%s",
2344                     test_uri_base ? test_uri_base : "", bug_uri_snippet);
2345 }
2346
2347 /**
2348  * g_test_summary:
2349  * @summary: One or two sentences summarising what the test checks, and how it
2350  *    checks it.
2351  *
2352  * Set the summary for a test, which describes what the test checks, and how it
2353  * goes about checking it. This may be included in test report output, and is
2354  * useful documentation for anyone reading the source code or modifying a test
2355  * in future. It must be a single line.
2356  *
2357  * This should be called at the top of a test function.
2358  *
2359  * For example:
2360  * |[<!-- language="C" -->
2361  * static void
2362  * test_array_sort (void)
2363  * {
2364  *   g_test_summary ("Test my_array_sort() sorts the array correctly and stably, "
2365  *                   "including testing zero length and one-element arrays.");
2366  *
2367  *   …
2368  * }
2369  * ]|
2370  *
2371  * Since: 2.62
2372  * See also: g_test_bug()
2373  */
2374 void
2375 g_test_summary (const char *summary)
2376 {
2377   g_return_if_fail (summary != NULL);
2378   g_return_if_fail (strchr (summary, '\n') == NULL);
2379   g_return_if_fail (strchr (summary, '\r') == NULL);
2380
2381   g_test_message ("%s summary: %s", test_run_name, summary);
2382 }
2383
2384 /**
2385  * g_test_get_root:
2386  *
2387  * Get the toplevel test suite for the test path API.
2388  *
2389  * Returns: the toplevel #GTestSuite
2390  *
2391  * Since: 2.16
2392  */
2393 GTestSuite*
2394 g_test_get_root (void)
2395 {
2396   if (!test_suite_root)
2397     {
2398       test_suite_root = g_test_create_suite ("root");
2399       g_free (test_suite_root->name);
2400       test_suite_root->name = g_strdup ("");
2401     }
2402
2403   return test_suite_root;
2404 }
2405
2406 /**
2407  * g_test_run:
2408  *
2409  * Runs all tests under the toplevel suite which can be retrieved
2410  * with g_test_get_root(). Similar to g_test_run_suite(), the test
2411  * cases to be run are filtered according to test path arguments
2412  * (`-p testpath` and `-s testpath`) as parsed by g_test_init().
2413  * g_test_run_suite() or g_test_run() may only be called once in a
2414  * program.
2415  *
2416  * In general, the tests and sub-suites within each suite are run in
2417  * the order in which they are defined. However, note that prior to
2418  * GLib 2.36, there was a bug in the `g_test_add_*`
2419  * functions which caused them to create multiple suites with the same
2420  * name, meaning that if you created tests "/foo/simple",
2421  * "/bar/simple", and "/foo/using-bar" in that order, they would get
2422  * run in that order (since g_test_run() would run the first "/foo"
2423  * suite, then the "/bar" suite, then the second "/foo" suite). As of
2424  * 2.36, this bug is fixed, and adding the tests in that order would
2425  * result in a running order of "/foo/simple", "/foo/using-bar",
2426  * "/bar/simple". If this new ordering is sub-optimal (because it puts
2427  * more-complicated tests before simpler ones, making it harder to
2428  * figure out exactly what has failed), you can fix it by changing the
2429  * test paths to group tests by suite in a way that will result in the
2430  * desired running order. Eg, "/simple/foo", "/simple/bar",
2431  * "/complex/foo-using-bar".
2432  *
2433  * However, you should never make the actual result of a test depend
2434  * on the order that tests are run in. If you need to ensure that some
2435  * particular code runs before or after a given test case, use
2436  * g_test_add(), which lets you specify setup and teardown functions.
2437  *
2438  * If all tests are skipped or marked as incomplete (expected failures),
2439  * this function will return 0 if producing TAP output, or 77 (treated
2440  * as "skip test" by Automake) otherwise.
2441  *
2442  * Returns: 0 on success, 1 on failure (assuming it returns at all),
2443  *   0 or 77 if all tests were skipped with g_test_skip() and/or
2444  *   g_test_incomplete()
2445  *
2446  * Since: 2.16
2447  */
2448 int
2449 g_test_run (void)
2450 {
2451   int ret;
2452   GTestSuite *suite;
2453
2454   if (atexit (test_cleanup) != 0)
2455     {
2456       int errsv = errno;
2457       g_error ("Unable to register test cleanup to be run at exit: %s",
2458                g_strerror (errsv));
2459     }
2460
2461   suite = g_test_get_root ();
2462   if (g_test_run_suite (suite) != 0)
2463     {
2464       ret = 1;
2465       goto out;
2466     }
2467
2468   /* Clean up the temporary directory. */
2469   if (test_isolate_dirs_tmpdir != NULL)
2470     {
2471       rm_rf (test_isolate_dirs_tmpdir);
2472       g_free (test_isolate_dirs_tmpdir);
2473       test_isolate_dirs_tmpdir = NULL;
2474     }
2475
2476   /* 77 is special to Automake's default driver, but not Automake's TAP driver
2477    * or Perl's prove(1) TAP driver. */
2478   if (test_tap_log)
2479     {
2480       ret = 0;
2481       goto out;
2482     }
2483
2484   if (test_run_count > 0 && test_run_count == test_skipped_count)
2485     {
2486       ret = 77;
2487       goto out;
2488     }
2489   else
2490     {
2491       ret = 0;
2492       goto out;
2493     }
2494
2495 out:
2496   g_test_suite_free (suite);
2497   return ret;
2498 }
2499
2500 /**
2501  * g_test_create_case:
2502  * @test_name:     the name for the test case
2503  * @data_size:     the size of the fixture data structure
2504  * @test_data:     test data argument for the test functions
2505  * @data_setup:    (scope async): the function to set up the fixture data
2506  * @data_test:     (scope async): the actual test function
2507  * @data_teardown: (scope async): the function to teardown the fixture data
2508  *
2509  * Create a new #GTestCase, named @test_name.
2510  *
2511  * This API is fairly low level, and calling g_test_add() or g_test_add_func()
2512  * is preferable.
2513  *
2514  * When this test is executed, a fixture structure of size @data_size
2515  * will be automatically allocated and filled with zeros. Then @data_setup is
2516  * called to initialize the fixture. After fixture setup, the actual test
2517  * function @data_test is called. Once the test run completes, the
2518  * fixture structure is torn down by calling @data_teardown and
2519  * after that the memory is automatically released by the test framework.
2520  *
2521  * Splitting up a test run into fixture setup, test function and
2522  * fixture teardown is most useful if the same fixture type is used for
2523  * multiple tests. In this cases, g_test_create_case() will be
2524  * called with the same type of fixture (the @data_size argument), but varying
2525  * @test_name and @data_test arguments.
2526  *
2527  * Returns: a newly allocated #GTestCase.
2528  *
2529  * Since: 2.16
2530  */
2531 GTestCase*
2532 g_test_create_case (const char       *test_name,
2533                     gsize             data_size,
2534                     gconstpointer     test_data,
2535                     GTestFixtureFunc  data_setup,
2536                     GTestFixtureFunc  data_test,
2537                     GTestFixtureFunc  data_teardown)
2538 {
2539   GTestCase *tc;
2540
2541   g_return_val_if_fail (test_name != NULL, NULL);
2542   g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
2543   g_return_val_if_fail (test_name[0] != 0, NULL);
2544   g_return_val_if_fail (data_test != NULL, NULL);
2545
2546   tc = g_slice_new0 (GTestCase);
2547   tc->name = g_strdup (test_name);
2548   tc->test_data = (gpointer) test_data;
2549   tc->fixture_size = data_size;
2550   tc->fixture_setup = (void*) data_setup;
2551   tc->fixture_test = (void*) data_test;
2552   tc->fixture_teardown = (void*) data_teardown;
2553
2554   return tc;
2555 }
2556
2557 static gint
2558 find_suite (gconstpointer l, gconstpointer s)
2559 {
2560   const GTestSuite *suite = l;
2561   const gchar *str = s;
2562
2563   return strcmp (suite->name, str);
2564 }
2565
2566 static gint
2567 find_case (gconstpointer l, gconstpointer s)
2568 {
2569   const GTestCase *tc = l;
2570   const gchar *str = s;
2571
2572   return strcmp (tc->name, str);
2573 }
2574
2575 /**
2576  * GTestFixtureFunc:
2577  * @fixture: (not nullable): the test fixture
2578  * @user_data: the data provided when registering the test
2579  *
2580  * The type used for functions that operate on test fixtures.  This is
2581  * used for the fixture setup and teardown functions as well as for the
2582  * testcases themselves.
2583  *
2584  * @user_data is a pointer to the data that was given when registering
2585  * the test case.
2586  *
2587  * @fixture will be a pointer to the area of memory allocated by the
2588  * test framework, of the size requested.  If the requested size was
2589  * zero then @fixture will be equal to @user_data.
2590  *
2591  * Since: 2.28
2592  */
2593 void
2594 g_test_add_vtable (const char       *testpath,
2595                    gsize             data_size,
2596                    gconstpointer     test_data,
2597                    GTestFixtureFunc  data_setup,
2598                    GTestFixtureFunc  fixture_test_func,
2599                    GTestFixtureFunc  data_teardown)
2600 {
2601   gchar **segments;
2602   guint ui;
2603   GTestSuite *suite;
2604
2605   g_return_if_fail (testpath != NULL);
2606   g_return_if_fail (g_path_is_absolute (testpath));
2607   g_return_if_fail (fixture_test_func != NULL);
2608   g_return_if_fail (!test_isolate_dirs || strstr (testpath, "/.") == NULL);
2609
2610   suite = g_test_get_root();
2611   segments = g_strsplit (testpath, "/", -1);
2612   for (ui = 0; segments[ui] != NULL; ui++)
2613     {
2614       const char *seg = segments[ui];
2615       gboolean islast = segments[ui + 1] == NULL;
2616       if (islast && !seg[0])
2617         g_error ("invalid test case path: %s", testpath);
2618       else if (!seg[0])
2619         continue;       /* initial or duplicate slash */
2620       else if (!islast)
2621         {
2622           GSList *l;
2623           GTestSuite *csuite;
2624           l = g_slist_find_custom (suite->suites, seg, find_suite);
2625           if (l)
2626             {
2627               csuite = l->data;
2628             }
2629           else
2630             {
2631               csuite = g_test_create_suite (seg);
2632               g_test_suite_add_suite (suite, csuite);
2633             }
2634           suite = csuite;
2635         }
2636       else /* islast */
2637         {
2638           GTestCase *tc;
2639
2640           if (g_slist_find_custom (suite->cases, seg, find_case))
2641             g_error ("duplicate test case path: %s", testpath);
2642
2643           tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
2644           g_test_suite_add (suite, tc);
2645         }
2646     }
2647   g_strfreev (segments);
2648 }
2649
2650 /**
2651  * g_test_fail:
2652  *
2653  * Indicates that a test failed. This function can be called
2654  * multiple times from the same test. You can use this function
2655  * if your test failed in a recoverable way.
2656  * 
2657  * Do not use this function if the failure of a test could cause
2658  * other tests to malfunction.
2659  *
2660  * Calling this function will not stop the test from running, you
2661  * need to return from the test function yourself. So you can
2662  * produce additional diagnostic messages or even continue running
2663  * the test.
2664  *
2665  * If not called from inside a test, this function does nothing.
2666  *
2667  * Note that unlike g_test_skip() and g_test_incomplete(), this
2668  * function does not log a message alongside the test failure.
2669  * If details of the test failure are available, either log them with
2670  * g_test_message() before g_test_fail(), or use g_test_fail_printf()
2671  * instead.
2672  *
2673  * Since: 2.30
2674  **/
2675 void
2676 g_test_fail (void)
2677 {
2678   test_run_success = G_TEST_RUN_FAILURE;
2679   g_clear_pointer (&test_run_msg, g_free);
2680 }
2681
2682 /**
2683  * g_test_fail_printf:
2684  * @format: the format string
2685  * @...:    printf-like arguments to @format
2686  *
2687  * Equivalent to g_test_fail(), but also record a message like
2688  * g_test_skip_printf().
2689  *
2690  * Since: 2.70
2691  **/
2692 void
2693 g_test_fail_printf (const char *format,
2694                     ...)
2695 {
2696   va_list args;
2697
2698   test_run_success = G_TEST_RUN_FAILURE;
2699   va_start (args, format);
2700   g_free (test_run_msg);
2701   test_run_msg = g_strdup_vprintf (format, args);
2702   va_end (args);
2703 }
2704
2705 /**
2706  * g_test_incomplete:
2707  * @msg: (nullable): explanation
2708  *
2709  * Indicates that a test failed because of some incomplete
2710  * functionality. This function can be called multiple times
2711  * from the same test.
2712  *
2713  * Calling this function will not stop the test from running, you
2714  * need to return from the test function yourself. So you can
2715  * produce additional diagnostic messages or even continue running
2716  * the test.
2717  *
2718  * If not called from inside a test, this function does nothing.
2719  *
2720  * Since: 2.38
2721  */
2722 void
2723 g_test_incomplete (const gchar *msg)
2724 {
2725   test_run_success = G_TEST_RUN_INCOMPLETE;
2726   g_free (test_run_msg);
2727   test_run_msg = g_strdup (msg);
2728 }
2729
2730 /**
2731  * g_test_incomplete_printf:
2732  * @format: the format string
2733  * @...:    printf-like arguments to @format
2734  *
2735  * Equivalent to g_test_incomplete(), but the explanation is formatted
2736  * as if by g_strdup_printf().
2737  *
2738  * Since: 2.70
2739  */
2740 void
2741 g_test_incomplete_printf (const char *format,
2742                           ...)
2743 {
2744   va_list args;
2745
2746   test_run_success = G_TEST_RUN_INCOMPLETE;
2747   va_start (args, format);
2748   g_free (test_run_msg);
2749   test_run_msg = g_strdup_vprintf (format, args);
2750   va_end (args);
2751 }
2752
2753 /**
2754  * g_test_skip:
2755  * @msg: (nullable): explanation
2756  *
2757  * Indicates that a test was skipped.
2758  *
2759  * Calling this function will not stop the test from running, you
2760  * need to return from the test function yourself. So you can
2761  * produce additional diagnostic messages or even continue running
2762  * the test.
2763  *
2764  * If not called from inside a test, this function does nothing.
2765  *
2766  * Since: 2.38
2767  */
2768 void
2769 g_test_skip (const gchar *msg)
2770 {
2771   test_run_success = G_TEST_RUN_SKIPPED;
2772   g_free (test_run_msg);
2773   test_run_msg = g_strdup (msg);
2774 }
2775
2776 /**
2777  * g_test_skip_printf:
2778  * @format: the format string
2779  * @...:    printf-like arguments to @format
2780  *
2781  * Equivalent to g_test_skip(), but the explanation is formatted
2782  * as if by g_strdup_printf().
2783  *
2784  * Since: 2.70
2785  */
2786 void
2787 g_test_skip_printf (const char *format,
2788                     ...)
2789 {
2790   va_list args;
2791
2792   test_run_success = G_TEST_RUN_SKIPPED;
2793   va_start (args, format);
2794   g_free (test_run_msg);
2795   test_run_msg = g_strdup_vprintf (format, args);
2796   va_end (args);
2797 }
2798
2799 /**
2800  * g_test_failed:
2801  *
2802  * Returns whether a test has already failed. This will
2803  * be the case when g_test_fail(), g_test_incomplete()
2804  * or g_test_skip() have been called, but also if an
2805  * assertion has failed.
2806  *
2807  * This can be useful to return early from a test if
2808  * continuing after a failed assertion might be harmful.
2809  *
2810  * The return value of this function is only meaningful
2811  * if it is called from inside a test function.
2812  *
2813  * Returns: %TRUE if the test has failed
2814  *
2815  * Since: 2.38
2816  */
2817 gboolean
2818 g_test_failed (void)
2819 {
2820   return test_run_success != G_TEST_RUN_SUCCESS;
2821 }
2822
2823 /**
2824  * g_test_set_nonfatal_assertions:
2825  *
2826  * Changes the behaviour of the various `g_assert_*()` macros,
2827  * g_test_assert_expected_messages() and the various
2828  * `g_test_trap_assert_*()` macros to not abort to program, but instead
2829  * call g_test_fail() and continue. (This also changes the behavior of
2830  * g_test_fail() so that it will not cause the test program to abort
2831  * after completing the failed test.)
2832  *
2833  * Note that the g_assert_not_reached() and g_assert() macros are not
2834  * affected by this.
2835  *
2836  * This function can only be called after g_test_init().
2837  *
2838  * Since: 2.38
2839  */
2840 void
2841 g_test_set_nonfatal_assertions (void)
2842 {
2843   if (!g_test_config_vars->test_initialized)
2844     g_error ("g_test_set_nonfatal_assertions called without g_test_init");
2845   test_nonfatal_assertions = TRUE;
2846   test_mode_fatal = FALSE;
2847 }
2848
2849 /**
2850  * GTestFunc:
2851  *
2852  * The type used for test case functions.
2853  *
2854  * Since: 2.28
2855  */
2856
2857 /**
2858  * g_test_add_func:
2859  * @testpath:  /-separated test case path name for the test.
2860  * @test_func: (scope async):  The test function to invoke for this test.
2861  *
2862  * Create a new test case, similar to g_test_create_case(). However
2863  * the test is assumed to use no fixture, and test suites are automatically
2864  * created on the fly and added to the root fixture, based on the
2865  * slash-separated portions of @testpath.
2866  *
2867  * If @testpath includes the component "subprocess" anywhere in it,
2868  * the test will be skipped by default, and only run if explicitly
2869  * required via the `-p` command-line option or g_test_trap_subprocess().
2870  *
2871  * No component of @testpath may start with a dot (`.`) if the
2872  * %G_TEST_OPTION_ISOLATE_DIRS option is being used; and it is recommended to
2873  * do so even if it isn’t.
2874  *
2875  * Since: 2.16
2876  */
2877 void
2878 g_test_add_func (const char *testpath,
2879                  GTestFunc   test_func)
2880 {
2881   g_return_if_fail (testpath != NULL);
2882   g_return_if_fail (testpath[0] == '/');
2883   g_return_if_fail (test_func != NULL);
2884   g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
2885 }
2886
2887 /**
2888  * GTestDataFunc:
2889  * @user_data: the data provided when registering the test
2890  *
2891  * The type used for test case functions that take an extra pointer
2892  * argument.
2893  *
2894  * Since: 2.28
2895  */
2896
2897 /**
2898  * g_test_add_data_func:
2899  * @testpath:  /-separated test case path name for the test.
2900  * @test_data: Test data argument for the test function.
2901  * @test_func: (scope async): The test function to invoke for this test.
2902  *
2903  * Create a new test case, similar to g_test_create_case(). However
2904  * the test is assumed to use no fixture, and test suites are automatically
2905  * created on the fly and added to the root fixture, based on the
2906  * slash-separated portions of @testpath. The @test_data argument
2907  * will be passed as first argument to @test_func.
2908  *
2909  * If @testpath includes the component "subprocess" anywhere in it,
2910  * the test will be skipped by default, and only run if explicitly
2911  * required via the `-p` command-line option or g_test_trap_subprocess().
2912  *
2913  * No component of @testpath may start with a dot (`.`) if the
2914  * %G_TEST_OPTION_ISOLATE_DIRS option is being used; and it is recommended to
2915  * do so even if it isn’t.
2916  *
2917  * Since: 2.16
2918  */
2919 void
2920 g_test_add_data_func (const char     *testpath,
2921                       gconstpointer   test_data,
2922                       GTestDataFunc   test_func)
2923 {
2924   g_return_if_fail (testpath != NULL);
2925   g_return_if_fail (testpath[0] == '/');
2926   g_return_if_fail (test_func != NULL);
2927
2928   g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
2929 }
2930
2931 /**
2932  * g_test_add_data_func_full:
2933  * @testpath: /-separated test case path name for the test.
2934  * @test_data: Test data argument for the test function.
2935  * @test_func: The test function to invoke for this test.
2936  * @data_free_func: #GDestroyNotify for @test_data.
2937  *
2938  * Create a new test case, as with g_test_add_data_func(), but freeing
2939  * @test_data after the test run is complete.
2940  *
2941  * Since: 2.34
2942  */
2943 void
2944 g_test_add_data_func_full (const char     *testpath,
2945                            gpointer        test_data,
2946                            GTestDataFunc   test_func,
2947                            GDestroyNotify  data_free_func)
2948 {
2949   g_return_if_fail (testpath != NULL);
2950   g_return_if_fail (testpath[0] == '/');
2951   g_return_if_fail (test_func != NULL);
2952
2953   g_test_add_vtable (testpath, 0, test_data, NULL,
2954                      (GTestFixtureFunc) test_func,
2955                      (GTestFixtureFunc) data_free_func);
2956 }
2957
2958 static gboolean
2959 g_test_suite_case_exists (GTestSuite *suite,
2960                           const char *test_path)
2961 {
2962   GSList *iter;
2963   char *slash;
2964   GTestCase *tc;
2965
2966   test_path++;
2967   slash = strchr (test_path, '/');
2968
2969   if (slash)
2970     {
2971       for (iter = suite->suites; iter; iter = iter->next)
2972         {
2973           GTestSuite *child_suite = iter->data;
2974
2975           if (!strncmp (child_suite->name, test_path, slash - test_path))
2976             if (g_test_suite_case_exists (child_suite, slash))
2977               return TRUE;
2978         }
2979     }
2980   else
2981     {
2982       for (iter = suite->cases; iter; iter = iter->next)
2983         {
2984           tc = iter->data;
2985           if (!strcmp (tc->name, test_path))
2986             return TRUE;
2987         }
2988     }
2989
2990   return FALSE;
2991 }
2992
2993 /**
2994  * g_test_create_suite:
2995  * @suite_name: a name for the suite
2996  *
2997  * Create a new test suite with the name @suite_name.
2998  *
2999  * Returns: A newly allocated #GTestSuite instance.
3000  *
3001  * Since: 2.16
3002  */
3003 GTestSuite*
3004 g_test_create_suite (const char *suite_name)
3005 {
3006   GTestSuite *ts;
3007   g_return_val_if_fail (suite_name != NULL, NULL);
3008   g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
3009   g_return_val_if_fail (suite_name[0] != 0, NULL);
3010   ts = g_slice_new0 (GTestSuite);
3011   ts->name = g_strdup (suite_name);
3012   return ts;
3013 }
3014
3015 /**
3016  * g_test_suite_add:
3017  * @suite: a #GTestSuite
3018  * @test_case: a #GTestCase
3019  *
3020  * Adds @test_case to @suite.
3021  *
3022  * Since: 2.16
3023  */
3024 void
3025 g_test_suite_add (GTestSuite     *suite,
3026                   GTestCase      *test_case)
3027 {
3028   g_return_if_fail (suite != NULL);
3029   g_return_if_fail (test_case != NULL);
3030
3031   suite->cases = g_slist_append (suite->cases, test_case);
3032 }
3033
3034 /**
3035  * g_test_suite_add_suite:
3036  * @suite:       a #GTestSuite
3037  * @nestedsuite: another #GTestSuite
3038  *
3039  * Adds @nestedsuite to @suite.
3040  *
3041  * Since: 2.16
3042  */
3043 void
3044 g_test_suite_add_suite (GTestSuite     *suite,
3045                         GTestSuite     *nestedsuite)
3046 {
3047   g_return_if_fail (suite != NULL);
3048   g_return_if_fail (nestedsuite != NULL);
3049
3050   suite->suites = g_slist_append (suite->suites, nestedsuite);
3051 }
3052
3053 /**
3054  * g_test_queue_free:
3055  * @gfree_pointer: the pointer to be stored.
3056  *
3057  * Enqueue a pointer to be released with g_free() during the next
3058  * teardown phase. This is equivalent to calling g_test_queue_destroy()
3059  * with a destroy callback of g_free().
3060  *
3061  * Since: 2.16
3062  */
3063 void
3064 g_test_queue_free (gpointer gfree_pointer)
3065 {
3066   if (gfree_pointer)
3067     g_test_queue_destroy (g_free, gfree_pointer);
3068 }
3069
3070 /**
3071  * g_test_queue_destroy:
3072  * @destroy_func:       Destroy callback for teardown phase.
3073  * @destroy_data:       Destroy callback data.
3074  *
3075  * This function enqueus a callback @destroy_func to be executed
3076  * during the next test case teardown phase. This is most useful
3077  * to auto destruct allocated test resources at the end of a test run.
3078  * Resources are released in reverse queue order, that means enqueueing
3079  * callback A before callback B will cause B() to be called before
3080  * A() during teardown.
3081  *
3082  * Since: 2.16
3083  */
3084 void
3085 g_test_queue_destroy (GDestroyNotify destroy_func,
3086                       gpointer       destroy_data)
3087 {
3088   DestroyEntry *dentry;
3089
3090   g_return_if_fail (destroy_func != NULL);
3091
3092   dentry = g_slice_new0 (DestroyEntry);
3093   dentry->destroy_func = destroy_func;
3094   dentry->destroy_data = destroy_data;
3095   dentry->next = test_destroy_queue;
3096   test_destroy_queue = dentry;
3097 }
3098
3099 static gint
3100 test_has_prefix (gconstpointer a,
3101                  gconstpointer b)
3102 {
3103     const gchar *test_path_skipped_local = (const gchar *)a;
3104     const gchar* test_run_name_local = (const gchar*)b;
3105     if (test_prefix_extended_skipped)
3106       {
3107         /* If both are null, we consider that it doesn't match */
3108         if (!test_path_skipped_local || !test_run_name_local)
3109           return FALSE;
3110         return strncmp (test_run_name_local, test_path_skipped_local, strlen (test_path_skipped_local));
3111       }
3112     return g_strcmp0 (test_run_name_local, test_path_skipped_local);
3113 }
3114
3115 static gboolean
3116 test_case_run (GTestCase *tc)
3117 {
3118   gchar *old_base = g_strdup (test_uri_base);
3119   GSList **old_free_list, *filename_free_list = NULL;
3120   gboolean success = G_TEST_RUN_SUCCESS;
3121
3122   old_free_list = test_filename_free_list;
3123   test_filename_free_list = &filename_free_list;
3124
3125   if (++test_run_count <= test_startup_skip_count)
3126     g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
3127   else if (test_run_list)
3128     {
3129       g_print ("%s\n", test_run_name);
3130       g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
3131     }
3132   else
3133     {
3134       GTimer *test_run_timer = g_timer_new();
3135       long double largs[G_TEST_CASE_LARGS_MAX];
3136       void *fixture;
3137       g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
3138       test_run_forks = 0;
3139       test_run_success = G_TEST_RUN_SUCCESS;
3140       g_clear_pointer (&test_run_msg, g_free);
3141       g_test_log_set_fatal_handler (NULL, NULL);
3142       if (test_paths_skipped && g_slist_find_custom (test_paths_skipped, test_run_name, (GCompareFunc)test_has_prefix))
3143         g_test_skip ("by request (-s option)");
3144       else
3145         {
3146           GError *local_error = NULL;
3147
3148           if (!test_do_isolate_dirs (&local_error))
3149             {
3150               g_test_log (G_TEST_LOG_ERROR, local_error->message, NULL, 0, NULL);
3151               g_test_fail ();
3152               g_error_free (local_error);
3153             }
3154           else
3155             {
3156               g_timer_start (test_run_timer);
3157               fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
3158               test_run_seed (test_run_seedstr);
3159               if (tc->fixture_setup)
3160                 tc->fixture_setup (fixture, tc->test_data);
3161               tc->fixture_test (fixture, tc->test_data);
3162               test_trap_clear();
3163               while (test_destroy_queue)
3164                 {
3165                   DestroyEntry *dentry = test_destroy_queue;
3166                   test_destroy_queue = dentry->next;
3167                   dentry->destroy_func (dentry->destroy_data);
3168                   g_slice_free (DestroyEntry, dentry);
3169                 }
3170               if (tc->fixture_teardown)
3171                 tc->fixture_teardown (fixture, tc->test_data);
3172               if (tc->fixture_size)
3173                 g_free (fixture);
3174               g_timer_stop (test_run_timer);
3175             }
3176
3177           test_rm_isolate_dirs ();
3178         }
3179       success = test_run_success;
3180       test_run_success = G_TEST_RUN_FAILURE;
3181       largs[G_TEST_CASE_LARGS_RESULT] = success; /* OK */
3182       largs[G_TEST_CASE_LARGS_RUN_FORKS] = test_run_forks;
3183       largs[G_TEST_CASE_LARGS_EXECUTION_TIME] = g_timer_elapsed (test_run_timer, NULL);
3184       g_test_log (G_TEST_LOG_STOP_CASE, test_run_name, test_run_msg, G_N_ELEMENTS (largs), largs);
3185       g_clear_pointer (&test_run_msg, g_free);
3186       g_timer_destroy (test_run_timer);
3187     }
3188
3189   g_slist_free_full (filename_free_list, g_free);
3190   test_filename_free_list = old_free_list;
3191   g_free (test_uri_base);
3192   test_uri_base = old_base;
3193
3194   return (success == G_TEST_RUN_SUCCESS ||
3195           success == G_TEST_RUN_SKIPPED ||
3196           success == G_TEST_RUN_INCOMPLETE);
3197 }
3198
3199 static gboolean
3200 path_has_prefix (const char *path,
3201                  const char *prefix)
3202 {
3203   int prefix_len = strlen (prefix);
3204
3205   return (strncmp (path, prefix, prefix_len) == 0 &&
3206           (path[prefix_len] == '\0' ||
3207            path[prefix_len] == '/'));
3208 }
3209
3210 static gboolean
3211 test_should_run (const char *test_path,
3212                  const char *cmp_path)
3213 {
3214   if (strstr (test_run_name, "/subprocess"))
3215     {
3216       if (g_strcmp0 (test_path, cmp_path) == 0)
3217         return TRUE;
3218
3219       if (g_test_verbose ())
3220         {
3221           if (test_tap_log)
3222             g_print ("skipping: %s\n", test_run_name);
3223           else
3224             g_print ("GTest: skipping: %s\n", test_run_name);
3225         }
3226       return FALSE;
3227     }
3228
3229   return !cmp_path || path_has_prefix (test_path, cmp_path);
3230 }
3231
3232 /* Recurse through @suite, running tests matching @path (or all tests
3233  * if @path is %NULL).
3234  */
3235 static int
3236 g_test_run_suite_internal (GTestSuite *suite,
3237                            const char *path)
3238 {
3239   guint n_bad = 0;
3240   gchar *old_name = test_run_name;
3241   gchar *old_name_path = test_run_name_path;
3242   GSList *iter;
3243
3244   g_return_val_if_fail (suite != NULL, -1);
3245
3246   g_test_log (G_TEST_LOG_START_SUITE, suite->name, NULL, 0, NULL);
3247
3248   for (iter = suite->cases; iter; iter = iter->next)
3249     {
3250       GTestCase *tc = iter->data;
3251
3252       test_run_name = g_build_path ("/", old_name, tc->name, NULL);
3253       test_run_name_path = g_build_path (G_DIR_SEPARATOR_S, old_name_path, tc->name, NULL);
3254       if (test_should_run (test_run_name, path))
3255         {
3256           if (!test_case_run (tc))
3257             n_bad++;
3258         }
3259       g_free (test_run_name);
3260       g_free (test_run_name_path);
3261     }
3262
3263   for (iter = suite->suites; iter; iter = iter->next)
3264     {
3265       GTestSuite *ts = iter->data;
3266
3267       test_run_name = g_build_path ("/", old_name, ts->name, NULL);
3268       test_run_name_path = g_build_path (G_DIR_SEPARATOR_S, old_name_path, ts->name, NULL);
3269       if (test_prefix_extended) {
3270         if (!path || path_has_prefix (test_run_name, path))
3271           n_bad += g_test_run_suite_internal (ts, test_run_name);
3272         else if (!path || path_has_prefix (path, test_run_name))
3273           n_bad += g_test_run_suite_internal (ts, path);
3274       } else if (!path || path_has_prefix (path, test_run_name)) {
3275         n_bad += g_test_run_suite_internal (ts, path);
3276       }
3277
3278       g_free (test_run_name);
3279       g_free (test_run_name_path);
3280     }
3281
3282   test_run_name = old_name;
3283   test_run_name_path = old_name_path;
3284
3285   g_test_log (G_TEST_LOG_STOP_SUITE, suite->name, NULL, 0, NULL);
3286
3287   return n_bad;
3288 }
3289
3290 static int
3291 g_test_suite_count (GTestSuite *suite)
3292 {
3293   int n = 0;
3294   GSList *iter;
3295
3296   g_return_val_if_fail (suite != NULL, -1);
3297
3298   for (iter = suite->cases; iter; iter = iter->next)
3299     {
3300       GTestCase *tc = iter->data;
3301
3302       if (strcmp (tc->name, "subprocess") != 0)
3303         n++;
3304     }
3305
3306   for (iter = suite->suites; iter; iter = iter->next)
3307     {
3308       GTestSuite *ts = iter->data;
3309
3310       if (strcmp (ts->name, "subprocess") != 0)
3311         n += g_test_suite_count (ts);
3312     }
3313
3314   return n;
3315 }
3316
3317 /**
3318  * g_test_run_suite:
3319  * @suite: a #GTestSuite
3320  *
3321  * Execute the tests within @suite and all nested #GTestSuites.
3322  * The test suites to be executed are filtered according to
3323  * test path arguments (`-p testpath` and `-s testpath`) as parsed by
3324  * g_test_init(). See the g_test_run() documentation for more
3325  * information on the order that tests are run in.
3326  *
3327  * g_test_run_suite() or g_test_run() may only be called once
3328  * in a program.
3329  *
3330  * Returns: 0 on success
3331  *
3332  * Since: 2.16
3333  */
3334 int
3335 g_test_run_suite (GTestSuite *suite)
3336 {
3337   int n_bad = 0;
3338
3339   g_return_val_if_fail (g_test_run_once == TRUE, -1);
3340
3341   g_test_run_once = FALSE;
3342   test_count = g_test_suite_count (suite);
3343
3344   test_run_name = g_strdup_printf ("/%s", suite->name);
3345   test_run_name_path = g_build_path (G_DIR_SEPARATOR_S, suite->name, NULL);
3346
3347   if (test_paths)
3348     {
3349       GSList *iter;
3350
3351       for (iter = test_paths; iter; iter = iter->next)
3352         n_bad += g_test_run_suite_internal (suite, iter->data);
3353     }
3354   else
3355     n_bad = g_test_run_suite_internal (suite, NULL);
3356
3357   g_clear_pointer (&test_run_name, g_free);
3358   g_clear_pointer (&test_run_name_path, g_free);
3359
3360   return n_bad;
3361 }
3362
3363 /**
3364  * g_test_case_free:
3365  * @test_case: a #GTestCase
3366  *
3367  * Free the @test_case.
3368  *
3369  * Since: 2.70
3370  */
3371 void
3372 g_test_case_free (GTestCase *test_case)
3373 {
3374   g_free (test_case->name);
3375   g_slice_free (GTestCase, test_case);
3376 }
3377
3378 /**
3379  * g_test_suite_free:
3380  * @suite: a #GTestSuite
3381  *
3382  * Free the @suite and all nested #GTestSuites.
3383  *
3384  * Since: 2.70
3385  */
3386 void
3387 g_test_suite_free (GTestSuite *suite)
3388 {
3389   g_slist_free_full (suite->cases, (GDestroyNotify)g_test_case_free);
3390
3391   g_free (suite->name);
3392
3393   g_slist_free_full (suite->suites, (GDestroyNotify)g_test_suite_free);
3394
3395   g_slice_free (GTestSuite, suite);
3396 }
3397
3398 static void
3399 gtest_default_log_handler (const gchar    *log_domain,
3400                            GLogLevelFlags  log_level,
3401                            const gchar    *message,
3402                            gpointer        unused_data)
3403 {
3404   const gchar *strv[16];
3405   gboolean fatal = FALSE;
3406   gchar *msg;
3407   guint i = 0;
3408
3409   if (log_domain)
3410     {
3411       strv[i++] = log_domain;
3412       strv[i++] = "-";
3413     }
3414   if (log_level & G_LOG_FLAG_FATAL)
3415     {
3416       strv[i++] = "FATAL-";
3417       fatal = TRUE;
3418     }
3419   if (log_level & G_LOG_FLAG_RECURSION)
3420     strv[i++] = "RECURSIVE-";
3421   if (log_level & G_LOG_LEVEL_ERROR)
3422     strv[i++] = "ERROR";
3423   if (log_level & G_LOG_LEVEL_CRITICAL)
3424     strv[i++] = "CRITICAL";
3425   if (log_level & G_LOG_LEVEL_WARNING)
3426     strv[i++] = "WARNING";
3427   if (log_level & G_LOG_LEVEL_MESSAGE)
3428     strv[i++] = "MESSAGE";
3429   if (log_level & G_LOG_LEVEL_INFO)
3430     strv[i++] = "INFO";
3431   if (log_level & G_LOG_LEVEL_DEBUG)
3432     strv[i++] = "DEBUG";
3433   strv[i++] = ": ";
3434   strv[i++] = message;
3435   strv[i++] = NULL;
3436
3437   msg = g_strjoinv ("", (gchar**) strv);
3438   g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
3439   g_free (msg);
3440
3441   if (!test_tap_log)
3442     g_log_default_handler (log_domain, log_level, message, unused_data);
3443 }
3444
3445 void
3446 g_assertion_message (const char     *domain,
3447                      const char     *file,
3448                      int             line,
3449                      const char     *func,
3450                      const char     *message)
3451 {
3452   char lstr[32];
3453   char *s;
3454
3455   if (!message)
3456     message = "code should not be reached";
3457   g_snprintf (lstr, 32, "%d", line);
3458   s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
3459                    "ERROR:", file, ":", lstr, ":",
3460                    func, func[0] ? ":" : "",
3461                    " ", message, NULL);
3462   g_printerr ("**\n%s\n", s);
3463
3464   /* Don't print a fatal error indication if assertions are non-fatal, or
3465    * if we are a child process that might be sharing the parent's stdout. */
3466   if (test_nonfatal_assertions || test_in_subprocess || test_in_forked_child)
3467     g_test_log (G_TEST_LOG_MESSAGE, s, NULL, 0, NULL);
3468   else
3469     g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
3470
3471   if (test_nonfatal_assertions)
3472     {
3473       g_free (s);
3474       g_test_fail ();
3475       return;
3476     }
3477
3478   /* store assertion message in global variable, so that it can be found in a
3479    * core dump */
3480   if (__glib_assert_msg != NULL)
3481     /* free the old one */
3482     free (__glib_assert_msg);
3483   __glib_assert_msg = (char*) malloc (strlen (s) + 1);
3484   strcpy (__glib_assert_msg, s);
3485
3486   g_free (s);
3487
3488   if (test_in_subprocess)
3489     {
3490       /* If this is a test case subprocess then it probably hit this
3491        * assertion on purpose, so just exit() rather than abort()ing,
3492        * to avoid triggering any system crash-reporting daemon.
3493        */
3494       _exit (1);
3495     }
3496   else
3497     g_abort ();
3498 }
3499
3500 /**
3501  * g_assertion_message_expr: (skip)
3502  * @domain: (nullable): log domain
3503  * @file: file containing the assertion
3504  * @line: line number of the assertion
3505  * @func: function containing the assertion
3506  * @expr: (nullable): expression which failed
3507  *
3508  * Internal function used to print messages from the public g_assert() and
3509  * g_assert_not_reached() macros.
3510  */
3511 void
3512 g_assertion_message_expr (const char     *domain,
3513                           const char     *file,
3514                           int             line,
3515                           const char     *func,
3516                           const char     *expr)
3517 {
3518   char *s;
3519   if (!expr)
3520     s = g_strdup ("code should not be reached");
3521   else
3522     s = g_strconcat ("assertion failed: (", expr, ")", NULL);
3523   g_assertion_message (domain, file, line, func, s);
3524   g_free (s);
3525
3526   /* Normally g_assertion_message() won't return, but we need this for
3527    * when test_nonfatal_assertions is set, since
3528    * g_assertion_message_expr() is used for always-fatal assertions.
3529    */
3530   if (test_in_subprocess)
3531     _exit (1);
3532   else
3533     g_abort ();
3534 }
3535
3536 void
3537 g_assertion_message_cmpint (const char     *domain,
3538                             const char     *file,
3539                             int             line,
3540                             const char     *func,
3541                             const char     *expr,
3542                             guint64         arg1,
3543                             const char     *cmp,
3544                             guint64         arg2,
3545                             char            numtype)
3546 {
3547   char *s = NULL;
3548
3549   switch (numtype)
3550     {
3551     case 'i':
3552       s = g_strdup_printf ("assertion failed (%s): "
3553                            "(%" PRIi64 " %s %" PRIi64 ")",
3554                            expr, (int64_t) arg1, cmp, (int64_t) arg2);
3555       break;
3556     case 'u':
3557       s = g_strdup_printf ("assertion failed (%s): "
3558                            "(%" PRIu64 " %s %" PRIu64 ")",
3559                            expr, (uint64_t) arg1, cmp, (uint64_t) arg2);
3560       break;
3561     case 'x':
3562       s = g_strdup_printf ("assertion failed (%s): "
3563                            "(0x%08" PRIx64 " %s 0x%08" PRIx64 ")",
3564                            expr, (uint64_t) arg1, cmp, (uint64_t) arg2);
3565       break;
3566     default:
3567       g_assert_not_reached ();
3568     }
3569   g_assertion_message (domain, file, line, func, s);
3570   g_free (s);
3571 }
3572
3573 void
3574 g_assertion_message_cmpnum (const char     *domain,
3575                             const char     *file,
3576                             int             line,
3577                             const char     *func,
3578                             const char     *expr,
3579                             long double     arg1,
3580                             const char     *cmp,
3581                             long double     arg2,
3582                             char            numtype)
3583 {
3584   char *s = NULL;
3585
3586   switch (numtype)
3587     {
3588     case 'f':   s = g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr, (double) arg1, cmp, (double) arg2); break;
3589       /* ideally use: floats=%.7g double=%.17g */
3590     case 'i':
3591     case 'x':
3592       /* Backwards compatibility to apps compiled before 2.78 */
3593       g_assertion_message_cmpint (domain, file, line, func, expr,
3594                                   (guint64) arg1, cmp, (guint64) arg2, numtype);
3595       break;
3596     default:
3597       g_assert_not_reached ();
3598     }
3599   g_assertion_message (domain, file, line, func, s);
3600   g_free (s);
3601 }
3602
3603 void
3604 g_assertion_message_cmpstr (const char     *domain,
3605                             const char     *file,
3606                             int             line,
3607                             const char     *func,
3608                             const char     *expr,
3609                             const char     *arg1,
3610                             const char     *cmp,
3611                             const char     *arg2)
3612 {
3613   char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
3614   a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
3615   a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
3616   g_free (t1);
3617   g_free (t2);
3618   s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
3619   g_free (a1);
3620   g_free (a2);
3621   g_assertion_message (domain, file, line, func, s);
3622   g_free (s);
3623 }
3624
3625 void
3626 g_assertion_message_cmpstrv (const char         *domain,
3627                              const char         *file,
3628                              int                 line,
3629                              const char         *func,
3630                              const char         *expr,
3631                              const char * const *arg1,
3632                              const char * const *arg2,
3633                              gsize               first_wrong_idx)
3634 {
3635   const char *s1 = arg1[first_wrong_idx], *s2 = arg2[first_wrong_idx];
3636   char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
3637
3638   a1 = g_strconcat ("\"", t1 = g_strescape (s1, NULL), "\"", NULL);
3639   a2 = g_strconcat ("\"", t2 = g_strescape (s2, NULL), "\"", NULL);
3640   g_free (t1);
3641   g_free (t2);
3642   s = g_strdup_printf ("assertion failed (%s): first differing element at index %" G_GSIZE_FORMAT ": %s does not equal %s",
3643                        expr, first_wrong_idx, a1, a2);
3644   g_free (a1);
3645   g_free (a2);
3646   g_assertion_message (domain, file, line, func, s);
3647   g_free (s);
3648 }
3649
3650 void
3651 g_assertion_message_error (const char     *domain,
3652                            const char     *file,
3653                            int             line,
3654                            const char     *func,
3655                            const char     *expr,
3656                            const GError   *error,
3657                            GQuark          error_domain,
3658                            int             error_code)
3659 {
3660   GString *gstring;
3661
3662   /* This is used by both g_assert_error() and g_assert_no_error(), so there
3663    * are three cases: expected an error but got the wrong error, expected
3664    * an error but got no error, and expected no error but got an error.
3665    */
3666
3667   gstring = g_string_new ("assertion failed ");
3668   if (error_domain)
3669       g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
3670                               g_quark_to_string (error_domain), error_code);
3671   else
3672     g_string_append_printf (gstring, "(%s == NULL): ", expr);
3673
3674   if (error)
3675       g_string_append_printf (gstring, "%s (%s, %d)", error->message,
3676                               g_quark_to_string (error->domain), error->code);
3677   else
3678     g_string_append_printf (gstring, "%s is NULL", expr);
3679
3680   g_assertion_message (domain, file, line, func, gstring->str);
3681   g_string_free (gstring, TRUE);
3682 }
3683
3684 /**
3685  * g_strcmp0:
3686  * @str1: (nullable): a C string or %NULL
3687  * @str2: (nullable): another C string or %NULL
3688  *
3689  * Compares @str1 and @str2 like strcmp(). Handles %NULL
3690  * gracefully by sorting it before non-%NULL strings.
3691  * Comparing two %NULL pointers returns 0.
3692  *
3693  * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
3694  *
3695  * Since: 2.16
3696  */
3697 int
3698 g_strcmp0 (const char     *str1,
3699            const char     *str2)
3700 {
3701   if (!str1)
3702     return -(str1 != str2);
3703   if (!str2)
3704     return str1 != str2;
3705   return strcmp (str1, str2);
3706 }
3707
3708 static void
3709 test_trap_clear (void)
3710 {
3711   test_trap_last_status = 0;
3712   test_trap_last_pid = 0;
3713   g_clear_pointer (&test_trap_last_subprocess, g_free);
3714   g_clear_pointer (&test_trap_last_stdout, g_free);
3715   g_clear_pointer (&test_trap_last_stderr, g_free);
3716 }
3717
3718 #ifdef G_OS_UNIX
3719
3720 static int
3721 safe_dup2 (int fd1,
3722            int fd2)
3723 {
3724   int ret;
3725   do
3726     ret = dup2 (fd1, fd2);
3727   while (ret < 0 && errno == EINTR);
3728   return ret;
3729 }
3730
3731 #endif
3732
3733 typedef struct {
3734   GPid pid;
3735   GMainLoop *loop;
3736   int child_status;  /* unmodified platform-specific status */
3737
3738   GIOChannel *stdout_io;
3739   gboolean echo_stdout;
3740   GString *stdout_str;
3741
3742   GIOChannel *stderr_io;
3743   gboolean echo_stderr;
3744   GString *stderr_str;
3745 } WaitForChildData;
3746
3747 static void
3748 check_complete (WaitForChildData *data)
3749 {
3750   if (data->child_status != -1 && data->stdout_io == NULL && data->stderr_io == NULL)
3751     g_main_loop_quit (data->loop);
3752 }
3753
3754 static void
3755 child_exited (GPid     pid,
3756               gint     status,
3757               gpointer user_data)
3758 {
3759   WaitForChildData *data = user_data;
3760
3761   g_assert (status != -1);
3762   data->child_status = status;
3763
3764   check_complete (data);
3765 }
3766
3767 static gboolean
3768 child_timeout (gpointer user_data)
3769 {
3770   WaitForChildData *data = user_data;
3771
3772 #ifdef G_OS_WIN32
3773   TerminateProcess (data->pid, G_TEST_STATUS_TIMED_OUT);
3774 #else
3775   kill (data->pid, SIGALRM);
3776 #endif
3777
3778   return FALSE;
3779 }
3780
3781 static gboolean
3782 child_read (GIOChannel *io, GIOCondition cond, gpointer user_data)
3783 {
3784   WaitForChildData *data = user_data;
3785   GIOStatus status;
3786   gsize nread, nwrote, total;
3787   gchar buf[4096];
3788   FILE *echo_file = NULL;
3789
3790   status = g_io_channel_read_chars (io, buf, sizeof (buf), &nread, NULL);
3791   if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF)
3792     {
3793       // FIXME data->error = (status == G_IO_STATUS_ERROR);
3794       if (io == data->stdout_io)
3795         g_clear_pointer (&data->stdout_io, g_io_channel_unref);
3796       else
3797         g_clear_pointer (&data->stderr_io, g_io_channel_unref);
3798
3799       check_complete (data);
3800       return FALSE;
3801     }
3802   else if (status == G_IO_STATUS_AGAIN)
3803     return TRUE;
3804
3805   if (io == data->stdout_io)
3806     {
3807       g_string_append_len (data->stdout_str, buf, nread);
3808       if (data->echo_stdout)
3809         {
3810           if G_UNLIKELY (!test_tap_log)
3811             echo_file = stdout;
3812         }
3813     }
3814   else
3815     {
3816       g_string_append_len (data->stderr_str, buf, nread);
3817       if (data->echo_stderr)
3818         echo_file = stderr;
3819     }
3820
3821   if (echo_file)
3822     {
3823       for (total = 0; total < nread; total += nwrote)
3824         {
3825           int errsv;
3826
3827           nwrote = fwrite (buf + total, 1, nread - total, echo_file);
3828           errsv = errno;
3829           if (nwrote == 0)
3830             g_error ("write failed: %s", g_strerror (errsv));
3831         }
3832     }
3833
3834   return TRUE;
3835 }
3836
3837 static void
3838 wait_for_child (GPid pid,
3839                 int stdout_fd, gboolean echo_stdout,
3840                 int stderr_fd, gboolean echo_stderr,
3841                 guint64 timeout)
3842 {
3843   WaitForChildData data;
3844   GMainContext *context;
3845   GSource *source;
3846
3847   data.pid = pid;
3848   data.child_status = -1;
3849
3850   context = g_main_context_new ();
3851   data.loop = g_main_loop_new (context, FALSE);
3852
3853   source = g_child_watch_source_new (pid);
3854   g_source_set_callback (source, (GSourceFunc) child_exited, &data, NULL);
3855   g_source_attach (source, context);
3856   g_source_unref (source);
3857
3858   data.echo_stdout = echo_stdout;
3859   data.stdout_str = g_string_new (NULL);
3860   data.stdout_io = g_io_channel_unix_new (stdout_fd);
3861   g_io_channel_set_close_on_unref (data.stdout_io, TRUE);
3862   g_io_channel_set_encoding (data.stdout_io, NULL, NULL);
3863   g_io_channel_set_buffered (data.stdout_io, FALSE);
3864   source = g_io_create_watch (data.stdout_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
3865   g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
3866   g_source_attach (source, context);
3867   g_source_unref (source);
3868
3869   data.echo_stderr = echo_stderr;
3870   data.stderr_str = g_string_new (NULL);
3871   data.stderr_io = g_io_channel_unix_new (stderr_fd);
3872   g_io_channel_set_close_on_unref (data.stderr_io, TRUE);
3873   g_io_channel_set_encoding (data.stderr_io, NULL, NULL);
3874   g_io_channel_set_buffered (data.stderr_io, FALSE);
3875   source = g_io_create_watch (data.stderr_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
3876   g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
3877   g_source_attach (source, context);
3878   g_source_unref (source);
3879
3880   if (timeout)
3881     {
3882       source = g_timeout_source_new (0);
3883       g_source_set_ready_time (source, g_get_monotonic_time () + timeout);
3884       g_source_set_callback (source, (GSourceFunc) child_timeout, &data, NULL);
3885       g_source_attach (source, context);
3886       g_source_unref (source);
3887     }
3888
3889   g_main_loop_run (data.loop);
3890   g_main_loop_unref (data.loop);
3891   g_main_context_unref (context);
3892
3893   if (echo_stdout && test_tap_log && data.stdout_str->len > 0)
3894     {
3895       gboolean added_newline = FALSE;
3896
3897       if (data.stdout_str->str[data.stdout_str->len - 1] != '\n')
3898         {
3899           g_string_append_c (data.stdout_str, '\n');
3900           added_newline = TRUE;
3901         }
3902
3903       g_test_print_handler_full (data.stdout_str->str, TRUE, TRUE, 1);
3904
3905       if (added_newline)
3906         g_string_truncate (data.stdout_str, data.stdout_str->len - 1);
3907     }
3908
3909   test_trap_last_pid = pid;
3910   test_trap_last_status = data.child_status;
3911   test_trap_last_stdout = g_string_free (data.stdout_str, FALSE);
3912   test_trap_last_stderr = g_string_free (data.stderr_str, FALSE);
3913
3914   g_clear_pointer (&data.stdout_io, g_io_channel_unref);
3915   g_clear_pointer (&data.stderr_io, g_io_channel_unref);
3916 }
3917
3918 /**
3919  * g_test_trap_fork:
3920  * @usec_timeout:    Timeout for the forked test in micro seconds.
3921  * @test_trap_flags: Flags to modify forking behaviour.
3922  *
3923  * Fork the current test program to execute a test case that might
3924  * not return or that might abort.
3925  *
3926  * If @usec_timeout is non-0, the forked test case is aborted and
3927  * considered failing if its run time exceeds it.
3928  *
3929  * The forking behavior can be configured with the #GTestTrapFlags flags.
3930  *
3931  * In the following example, the test code forks, the forked child
3932  * process produces some sample output and exits successfully.
3933  * The forking parent process then asserts successful child program
3934  * termination and validates child program outputs.
3935  *
3936  * |[<!-- language="C" --> 
3937  *   static void
3938  *   test_fork_patterns (void)
3939  *   {
3940  *     if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
3941  *       {
3942  *         g_print ("some stdout text: somagic17\n");
3943  *         g_printerr ("some stderr text: semagic43\n");
3944  *         exit (0); // successful test run
3945  *       }
3946  *     g_test_trap_assert_passed ();
3947  *     g_test_trap_assert_stdout ("*somagic17*");
3948  *     g_test_trap_assert_stderr ("*semagic43*");
3949  *   }
3950  * ]|
3951  *
3952  * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
3953  *
3954  * Since: 2.16
3955  *
3956  * Deprecated: This function is implemented only on Unix platforms,
3957  * is not always reliable due to problems inherent in fork-without-exec
3958  * and doesn't set close-on-exec flag on its file descriptors.
3959  * Use g_test_trap_subprocess() instead.
3960  */
3961 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
3962 gboolean
3963 g_test_trap_fork (guint64        usec_timeout,
3964                   GTestTrapFlags test_trap_flags)
3965 {
3966 #ifdef G_OS_UNIX
3967   int stdout_pipe[2] = { -1, -1 };
3968   int stderr_pipe[2] = { -1, -1 };
3969   int errsv;
3970
3971   test_trap_clear();
3972   if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0)
3973     {
3974       errsv = errno;
3975       g_error ("failed to create pipes to fork test program: %s", g_strerror (errsv));
3976     }
3977   test_trap_last_pid = fork ();
3978   errsv = errno;
3979   if (test_trap_last_pid < 0)
3980     g_error ("failed to fork test program: %s", g_strerror (errsv));
3981   if (test_trap_last_pid == 0)  /* child */
3982     {
3983       int fd0 = -1;
3984       test_in_forked_child = TRUE;
3985       close (stdout_pipe[0]);
3986       close (stderr_pipe[0]);
3987       if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
3988         {
3989           fd0 = g_open ("/dev/null", O_RDONLY, 0);
3990           if (fd0 < 0)
3991             g_error ("failed to open /dev/null for stdin redirection");
3992         }
3993       if (safe_dup2 (stdout_pipe[1], 1) < 0 || safe_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && safe_dup2 (fd0, 0) < 0))
3994         {
3995           errsv = errno;
3996           g_error ("failed to dup2() in forked test program: %s", g_strerror (errsv));
3997         }
3998       if (fd0 >= 3)
3999         close (fd0);
4000       if (stdout_pipe[1] >= 3)
4001         close (stdout_pipe[1]);
4002       if (stderr_pipe[1] >= 3)
4003         close (stderr_pipe[1]);
4004
4005       /* We typically expect these child processes to crash, and some
4006        * tests spawn a *lot* of them.  Avoid spamming system crash
4007        * collection programs such as systemd-coredump and abrt.
4008        */
4009       g_test_disable_crash_reporting ();
4010
4011       return TRUE;
4012     }
4013   else                          /* parent */
4014     {
4015       test_run_forks++;
4016       close (stdout_pipe[1]);
4017       close (stderr_pipe[1]);
4018
4019       wait_for_child (test_trap_last_pid,
4020                       stdout_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT),
4021                       stderr_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR),
4022                       usec_timeout);
4023       return FALSE;
4024     }
4025 #else
4026   g_message ("Not implemented: g_test_trap_fork");
4027
4028   return FALSE;
4029 #endif
4030 }
4031 G_GNUC_END_IGNORE_DEPRECATIONS
4032
4033 /**
4034  * g_test_trap_subprocess:
4035  * @test_path: (nullable): Test to run in a subprocess
4036  * @usec_timeout: Timeout for the subprocess test in micro seconds.
4037  * @test_flags:   Flags to modify subprocess behaviour.
4038  *
4039  * Respawns the test program to run only @test_path in a subprocess.
4040  * This can be used for a test case that might not return, or that
4041  * might abort.
4042  *
4043  * If @test_path is %NULL then the same test is re-run in a subprocess.
4044  * You can use g_test_subprocess() to determine whether the test is in
4045  * a subprocess or not.
4046  *
4047  * @test_path can also be the name of the parent test, followed by
4048  * "`/subprocess/`" and then a name for the specific subtest (or just
4049  * ending with "`/subprocess`" if the test only has one child test);
4050  * tests with names of this form will automatically be skipped in the
4051  * parent process.
4052  *
4053  * If @usec_timeout is non-0, the test subprocess is aborted and
4054  * considered failing if its run time exceeds it.
4055  *
4056  * The subprocess behavior can be configured with the
4057  * #GTestSubprocessFlags flags.
4058  *
4059  * You can use methods such as g_test_trap_assert_passed(),
4060  * g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to
4061  * check the results of the subprocess. (But note that
4062  * g_test_trap_assert_stdout() and g_test_trap_assert_stderr()
4063  * cannot be used if @test_flags specifies that the child should
4064  * inherit the parent stdout/stderr.) 
4065  *
4066  * If your `main ()` needs to behave differently in
4067  * the subprocess, you can call g_test_subprocess() (after calling
4068  * g_test_init()) to see whether you are in a subprocess.
4069  *
4070  * Internally, this function tracks the child process using
4071  * g_child_watch_source_new(), so your process must not ignore `SIGCHLD`, and
4072  * must not attempt to watch or wait for the child process via another
4073  * mechanism.
4074  *
4075  * The following example tests that calling
4076  * `my_object_new(1000000)` will abort with an error
4077  * message.
4078  *
4079  * |[<!-- language="C" --> 
4080  *   static void
4081  *   test_create_large_object (void)
4082  *   {
4083  *     if (g_test_subprocess ())
4084  *       {
4085  *         my_object_new (1000000);
4086  *         return;
4087  *       }
4088  *
4089  *     // Reruns this same test in a subprocess
4090  *     g_test_trap_subprocess (NULL, 0, G_TEST_SUBPROCESS_DEFAULT);
4091  *     g_test_trap_assert_failed ();
4092  *     g_test_trap_assert_stderr ("*ERROR*too large*");
4093  *   }
4094  *
4095  *   int
4096  *   main (int argc, char **argv)
4097  *   {
4098  *     g_test_init (&argc, &argv, NULL);
4099  *
4100  *     g_test_add_func ("/myobject/create_large_object",
4101  *                      test_create_large_object);
4102  *     return g_test_run ();
4103  *   }
4104  * ]|
4105  *
4106  * Since: 2.38
4107  */
4108 void
4109 g_test_trap_subprocess (const char           *test_path,
4110                         guint64               usec_timeout,
4111                         GTestSubprocessFlags  test_flags)
4112 {
4113   GError *error = NULL;
4114   GPtrArray *argv;
4115   GSpawnFlags flags;
4116   int stdout_fd, stderr_fd;
4117   GPid pid;
4118
4119   /* Sanity check that they used GTestSubprocessFlags, not GTestTrapFlags */
4120   g_assert ((test_flags & (G_TEST_TRAP_INHERIT_STDIN | G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR)) == 0);
4121
4122   if (test_path)
4123     {
4124       if (!g_test_suite_case_exists (g_test_get_root (), test_path))
4125         g_error ("g_test_trap_subprocess: test does not exist: %s", test_path);
4126     }
4127   else
4128     {
4129       test_path = test_run_name;
4130     }
4131
4132   if (g_test_verbose ())
4133     {
4134       if (test_tap_log)
4135         g_print ("subprocess: %s\n", test_path);
4136       else
4137         g_print ("GTest: subprocess: %s\n", test_path);
4138     }
4139
4140   test_trap_clear ();
4141   test_trap_last_subprocess = g_strdup (test_path);
4142
4143   if (test_argv0 == NULL)
4144     g_error ("g_test_trap_subprocess() requires argv0 to be passed to g_test_init()");
4145
4146   argv = g_ptr_array_new ();
4147   g_ptr_array_add (argv, (char *) test_argv0);
4148   g_ptr_array_add (argv, "-q");
4149   g_ptr_array_add (argv, "-p");
4150   g_ptr_array_add (argv, (char *)test_path);
4151   g_ptr_array_add (argv, "--GTestSubprocess");
4152   if (test_log_fd != -1)
4153     {
4154       char log_fd_buf[128];
4155
4156       g_ptr_array_add (argv, "--GTestLogFD");
4157       g_snprintf (log_fd_buf, sizeof (log_fd_buf), "%d", test_log_fd);
4158       g_ptr_array_add (argv, log_fd_buf);
4159     }
4160   g_ptr_array_add (argv, NULL);
4161
4162   flags = G_SPAWN_DO_NOT_REAP_CHILD;
4163   if (test_log_fd != -1)
4164     flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
4165   if (test_flags & G_TEST_TRAP_INHERIT_STDIN)
4166     flags |= G_SPAWN_CHILD_INHERITS_STDIN;
4167
4168   if (!g_spawn_async_with_pipes (test_initial_cwd,
4169                                  (char **)argv->pdata,
4170                                  NULL, flags,
4171                                  NULL, NULL,
4172                                  &pid, NULL, &stdout_fd, &stderr_fd,
4173                                  &error))
4174     {
4175       g_error ("g_test_trap_subprocess() failed: %s",
4176                error->message);
4177     }
4178   g_ptr_array_free (argv, TRUE);
4179
4180   wait_for_child (pid,
4181                   stdout_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDOUT),
4182                   stderr_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDERR),
4183                   usec_timeout);
4184 }
4185
4186 /**
4187  * g_test_subprocess:
4188  *
4189  * Returns %TRUE (after g_test_init() has been called) if the test
4190  * program is running under g_test_trap_subprocess().
4191  *
4192  * Returns: %TRUE if the test program is running under
4193  * g_test_trap_subprocess().
4194  *
4195  * Since: 2.38
4196  */
4197 gboolean
4198 g_test_subprocess (void)
4199 {
4200   return test_in_subprocess;
4201 }
4202
4203 /**
4204  * g_test_trap_has_passed:
4205  *
4206  * Check the result of the last g_test_trap_subprocess() call.
4207  *
4208  * Returns: %TRUE if the last test subprocess terminated successfully.
4209  *
4210  * Since: 2.16
4211  */
4212 gboolean
4213 g_test_trap_has_passed (void)
4214 {
4215 #ifdef G_OS_UNIX
4216   return (WIFEXITED (test_trap_last_status) &&
4217       WEXITSTATUS (test_trap_last_status) == 0);
4218 #else
4219   return test_trap_last_status == 0;
4220 #endif
4221 }
4222
4223 /**
4224  * g_test_trap_reached_timeout:
4225  *
4226  * Check the result of the last g_test_trap_subprocess() call.
4227  *
4228  * Returns: %TRUE if the last test subprocess got killed due to a timeout.
4229  *
4230  * Since: 2.16
4231  */
4232 gboolean
4233 g_test_trap_reached_timeout (void)
4234 {
4235 #ifdef G_OS_UNIX
4236   return (WIFSIGNALED (test_trap_last_status) &&
4237       WTERMSIG (test_trap_last_status) == SIGALRM);
4238 #else
4239   return test_trap_last_status == G_TEST_STATUS_TIMED_OUT;
4240 #endif
4241 }
4242
4243 static gboolean
4244 log_child_output (const gchar *process_id)
4245 {
4246   gchar *escaped;
4247
4248 #ifdef G_OS_UNIX
4249   if (WIFEXITED (test_trap_last_status)) /* normal exit */
4250     {
4251       if (WEXITSTATUS (test_trap_last_status) == 0)
4252         g_test_message ("child process (%s) exit status: 0 (success)",
4253             process_id);
4254       else
4255         g_test_message ("child process (%s) exit status: %d (error)",
4256             process_id, WEXITSTATUS (test_trap_last_status));
4257     }
4258   else if (WIFSIGNALED (test_trap_last_status) &&
4259       WTERMSIG (test_trap_last_status) == SIGALRM)
4260     {
4261       g_test_message ("child process (%s) timed out", process_id);
4262     }
4263   else if (WIFSIGNALED (test_trap_last_status))
4264     {
4265       const gchar *maybe_dumped_core = "";
4266
4267 #ifdef WCOREDUMP
4268       if (WCOREDUMP (test_trap_last_status))
4269         maybe_dumped_core = ", core dumped";
4270 #endif
4271
4272       g_test_message ("child process (%s) killed by signal %d (%s)%s",
4273           process_id, WTERMSIG (test_trap_last_status),
4274           g_strsignal (WTERMSIG (test_trap_last_status)),
4275           maybe_dumped_core);
4276     }
4277   else
4278     {
4279       g_test_message ("child process (%s) unknown wait status %d",
4280           process_id, test_trap_last_status);
4281     }
4282 #else
4283   if (test_trap_last_status == 0)
4284     g_test_message ("child process (%s) exit status: 0 (success)",
4285         process_id);
4286   else
4287     g_test_message ("child process (%s) exit status: %d (error)",
4288         process_id, test_trap_last_status);
4289 #endif
4290
4291   escaped = g_strescape (test_trap_last_stdout, NULL);
4292   g_test_message ("child process (%s) stdout: \"%s\"", process_id, escaped);
4293   g_free (escaped);
4294
4295   escaped = g_strescape (test_trap_last_stderr, NULL);
4296   g_test_message ("child process (%s) stderr: \"%s\"", process_id, escaped);
4297   g_free (escaped);
4298
4299   /* so we can use short-circuiting:
4300    * logged_child_output = logged_child_output || log_child_output (...) */
4301   return TRUE;
4302 }
4303
4304 void
4305 g_test_trap_assertions (const char     *domain,
4306                         const char     *file,
4307                         int             line,
4308                         const char     *func,
4309                         guint64         assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
4310                         const char     *pattern)
4311 {
4312   gboolean must_pass = assertion_flags == 0;
4313   gboolean must_fail = assertion_flags == 1;
4314   gboolean match_result = 0 == (assertion_flags & 1);
4315   gboolean logged_child_output = FALSE;
4316   const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
4317   const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
4318   const char *match_error = match_result ? "failed to match" : "contains invalid match";
4319   char *process_id;
4320
4321 #ifdef G_OS_UNIX
4322   if (test_trap_last_subprocess != NULL)
4323     {
4324       process_id = g_strdup_printf ("%s [%d]", test_trap_last_subprocess,
4325                                     test_trap_last_pid);
4326     }
4327   else if (test_trap_last_pid != 0)
4328     process_id = g_strdup_printf ("%d", test_trap_last_pid);
4329 #else
4330   if (test_trap_last_subprocess != NULL)
4331     process_id = g_strdup (test_trap_last_subprocess);
4332 #endif
4333   else
4334     g_error ("g_test_trap_ assertion with no trapped test");
4335
4336   if (must_pass && !g_test_trap_has_passed())
4337     {
4338       char *msg;
4339
4340       logged_child_output = logged_child_output || log_child_output (process_id);
4341
4342       msg = g_strdup_printf ("child process (%s) failed unexpectedly", process_id);
4343       g_assertion_message (domain, file, line, func, msg);
4344       g_free (msg);
4345     }
4346   if (must_fail && g_test_trap_has_passed())
4347     {
4348       char *msg;
4349
4350       logged_child_output = logged_child_output || log_child_output (process_id);
4351
4352       msg = g_strdup_printf ("child process (%s) did not fail as expected", process_id);
4353       g_assertion_message (domain, file, line, func, msg);
4354       g_free (msg);
4355     }
4356   if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
4357     {
4358       char *msg;
4359
4360       logged_child_output = logged_child_output || log_child_output (process_id);
4361
4362       g_test_message ("stdout was:\n%s", test_trap_last_stdout);
4363
4364       msg = g_strdup_printf ("stdout of child process (%s) %s: %s",
4365                              process_id, match_error, stdout_pattern);
4366       g_assertion_message (domain, file, line, func, msg);
4367       g_free (msg);
4368     }
4369   if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
4370     {
4371       char *msg;
4372
4373       logged_child_output = logged_child_output || log_child_output (process_id);
4374
4375       g_test_message ("stderr was:\n%s", test_trap_last_stderr);
4376
4377       msg = g_strdup_printf ("stderr of child process (%s) %s: %s",
4378                              process_id, match_error, stderr_pattern);
4379       g_assertion_message (domain, file, line, func, msg);
4380       g_free (msg);
4381     }
4382
4383   (void) logged_child_output;  /* shut up scan-build about the final unread assignment */
4384
4385   g_free (process_id);
4386 }
4387
4388 static void
4389 gstring_overwrite_int (GString *gstring,
4390                        guint    pos,
4391                        guint32  vuint)
4392 {
4393   vuint = g_htonl (vuint);
4394   g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
4395 }
4396
4397 static void
4398 gstring_append_int (GString *gstring,
4399                     guint32  vuint)
4400 {
4401   vuint = g_htonl (vuint);
4402   g_string_append_len (gstring, (const gchar*) &vuint, 4);
4403 }
4404
4405 static void
4406 gstring_append_double (GString *gstring,
4407                        double   vdouble)
4408 {
4409   union { double vdouble; guint64 vuint64; } u;
4410   u.vdouble = vdouble;
4411   u.vuint64 = GUINT64_TO_BE (u.vuint64);
4412   g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
4413 }
4414
4415 static guint8*
4416 g_test_log_dump (GTestLogMsg *msg,
4417                  guint       *len)
4418 {
4419   GString *gstring = g_string_sized_new (1024);
4420   guint ui;
4421   gstring_append_int (gstring, 0);              /* message length */
4422   gstring_append_int (gstring, msg->log_type);
4423   gstring_append_int (gstring, msg->n_strings);
4424   gstring_append_int (gstring, msg->n_nums);
4425   gstring_append_int (gstring, 0);      /* reserved */
4426   for (ui = 0; ui < msg->n_strings; ui++)
4427     {
4428       guint l = strlen (msg->strings[ui]);
4429       gstring_append_int (gstring, l);
4430       g_string_append_len (gstring, msg->strings[ui], l);
4431     }
4432   for (ui = 0; ui < msg->n_nums; ui++)
4433     gstring_append_double (gstring, msg->nums[ui]);
4434   *len = gstring->len;
4435   gstring_overwrite_int (gstring, 0, *len);     /* message length */
4436   return (guint8*) g_string_free (gstring, FALSE);
4437 }
4438
4439 static inline long double
4440 net_double (const gchar **ipointer)
4441 {
4442   union { guint64 vuint64; double vdouble; } u;
4443   guint64 aligned_int64;
4444   memcpy (&aligned_int64, *ipointer, 8);
4445   *ipointer += 8;
4446   u.vuint64 = GUINT64_FROM_BE (aligned_int64);
4447   return u.vdouble;
4448 }
4449
4450 static inline guint32
4451 net_int (const gchar **ipointer)
4452 {
4453   guint32 aligned_int;
4454   memcpy (&aligned_int, *ipointer, 4);
4455   *ipointer += 4;
4456   return g_ntohl (aligned_int);
4457 }
4458
4459 static gboolean
4460 g_test_log_extract (GTestLogBuffer *tbuffer)
4461 {
4462   const gchar *p = tbuffer->data->str;
4463   GTestLogMsg msg;
4464   guint mlength;
4465   if (tbuffer->data->len < 4 * 5)
4466     return FALSE;
4467   mlength = net_int (&p);
4468   if (tbuffer->data->len < mlength)
4469     return FALSE;
4470   msg.log_type = net_int (&p);
4471   msg.n_strings = net_int (&p);
4472   msg.n_nums = net_int (&p);
4473   if (net_int (&p) == 0)
4474     {
4475       guint ui;
4476       msg.strings = g_new0 (gchar*, msg.n_strings + 1);
4477       msg.nums = g_new0 (long double, msg.n_nums);
4478       for (ui = 0; ui < msg.n_strings; ui++)
4479         {
4480           guint sl = net_int (&p);
4481           msg.strings[ui] = g_strndup (p, sl);
4482           p += sl;
4483         }
4484       for (ui = 0; ui < msg.n_nums; ui++)
4485         msg.nums[ui] = net_double (&p);
4486       if (p <= tbuffer->data->str + mlength)
4487         {
4488           g_string_erase (tbuffer->data, 0, mlength);
4489           tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup2 (&msg, sizeof (msg)));
4490           return TRUE;
4491         }
4492
4493       g_free (msg.nums);
4494       g_strfreev (msg.strings);
4495     }
4496
4497   g_error ("corrupt log stream from test program");
4498   return FALSE;
4499 }
4500
4501 /**
4502  * g_test_log_buffer_new:
4503  *
4504  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
4505  */
4506 GTestLogBuffer*
4507 g_test_log_buffer_new (void)
4508 {
4509   GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
4510   tb->data = g_string_sized_new (1024);
4511   return tb;
4512 }
4513
4514 /**
4515  * g_test_log_buffer_free:
4516  *
4517  * Internal function for gtester to free test log messages, no ABI guarantees provided.
4518  */
4519 void
4520 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
4521 {
4522   g_return_if_fail (tbuffer != NULL);
4523   while (tbuffer->msgs)
4524     g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
4525   g_string_free (tbuffer->data, TRUE);
4526   g_free (tbuffer);
4527 }
4528
4529 /**
4530  * g_test_log_buffer_push:
4531  *
4532  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
4533  */
4534 void
4535 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
4536                         guint           n_bytes,
4537                         const guint8   *bytes)
4538 {
4539   g_return_if_fail (tbuffer != NULL);
4540   if (n_bytes)
4541     {
4542       gboolean more_messages;
4543       g_return_if_fail (bytes != NULL);
4544       g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
4545       do
4546         more_messages = g_test_log_extract (tbuffer);
4547       while (more_messages);
4548     }
4549 }
4550
4551 /**
4552  * g_test_log_buffer_pop:
4553  *
4554  * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
4555  */
4556 GTestLogMsg*
4557 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
4558 {
4559   GTestLogMsg *msg = NULL;
4560   g_return_val_if_fail (tbuffer != NULL, NULL);
4561   if (tbuffer->msgs)
4562     {
4563       GSList *slist = g_slist_last (tbuffer->msgs);
4564       msg = slist->data;
4565       tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
4566     }
4567   return msg;
4568 }
4569
4570 /**
4571  * g_test_log_msg_free:
4572  *
4573  * Internal function for gtester to free test log messages, no ABI guarantees provided.
4574  */
4575 void
4576 g_test_log_msg_free (GTestLogMsg *tmsg)
4577 {
4578   g_return_if_fail (tmsg != NULL);
4579   g_strfreev (tmsg->strings);
4580   g_free (tmsg->nums);
4581   g_free (tmsg);
4582 }
4583
4584 static gchar *
4585 g_test_build_filename_va (GTestFileType  file_type,
4586                           const gchar   *first_path,
4587                           va_list        ap)
4588 {
4589   const gchar *pathv[16];
4590   gsize num_path_segments;
4591
4592   if (file_type == G_TEST_DIST)
4593     pathv[0] = test_disted_files_dir;
4594   else if (file_type == G_TEST_BUILT)
4595     pathv[0] = test_built_files_dir;
4596   else
4597     g_assert_not_reached ();
4598
4599   pathv[1] = first_path;
4600
4601   for (num_path_segments = 2; num_path_segments < G_N_ELEMENTS (pathv); num_path_segments++)
4602     {
4603       pathv[num_path_segments] = va_arg (ap, const char *);
4604       if (pathv[num_path_segments] == NULL)
4605         break;
4606     }
4607
4608   g_assert_cmpint (num_path_segments, <, G_N_ELEMENTS (pathv));
4609
4610   return g_build_filenamev ((gchar **) pathv);
4611 }
4612
4613 /**
4614  * g_test_build_filename:
4615  * @file_type: the type of file (built vs. distributed)
4616  * @first_path: the first segment of the pathname
4617  * @...: %NULL-terminated additional path segments
4618  *
4619  * Creates the pathname to a data file that is required for a test.
4620  *
4621  * This function is conceptually similar to g_build_filename() except
4622  * that the first argument has been replaced with a #GTestFileType
4623  * argument.
4624  *
4625  * The data file should either have been distributed with the module
4626  * containing the test (%G_TEST_DIST) or built as part of the build
4627  * system of that module (%G_TEST_BUILT).
4628  *
4629  * In order for this function to work in srcdir != builddir situations,
4630  * the G_TEST_SRCDIR and G_TEST_BUILDDIR environment variables need to
4631  * have been defined.  As of 2.38, this is done by the glib.mk
4632  * included in GLib.  Please ensure that your copy is up to date before
4633  * using this function.
4634  *
4635  * In case neither variable is set, this function will fall back to
4636  * using the dirname portion of argv[0], possibly removing ".libs".
4637  * This allows for casual running of tests directly from the commandline
4638  * in the srcdir == builddir case and should also support running of
4639  * installed tests, assuming the data files have been installed in the
4640  * same relative path as the test binary.
4641  *
4642  * Returns: the path of the file, to be freed using g_free()
4643  *
4644  * Since: 2.38
4645  **/
4646 /**
4647  * GTestFileType:
4648  * @G_TEST_DIST: a file that was included in the distribution tarball
4649  * @G_TEST_BUILT: a file that was built on the compiling machine
4650  *
4651  * The type of file to return the filename for, when used with
4652  * g_test_build_filename().
4653  *
4654  * These two options correspond rather directly to the 'dist' and
4655  * 'built' terminology that automake uses and are explicitly used to
4656  * distinguish between the 'srcdir' and 'builddir' being separate.  All
4657  * files in your project should either be dist (in the
4658  * `EXTRA_DIST` or `dist_schema_DATA`
4659  * sense, in which case they will always be in the srcdir) or built (in
4660  * the `BUILT_SOURCES` sense, in which case they will
4661  * always be in the builddir).
4662  *
4663  * Note: as a general rule of automake, files that are generated only as
4664  * part of the build-from-git process (but then are distributed with the
4665  * tarball) always go in srcdir (even if doing a srcdir != builddir
4666  * build from git) and are considered as distributed files.
4667  *
4668  * Since: 2.38
4669  **/
4670 gchar *
4671 g_test_build_filename (GTestFileType  file_type,
4672                        const gchar   *first_path,
4673                        ...)
4674 {
4675   gchar *result;
4676   va_list ap;
4677
4678   g_assert (g_test_initialized ());
4679
4680   va_start (ap, first_path);
4681   result = g_test_build_filename_va (file_type, first_path, ap);
4682   va_end (ap);
4683
4684   return result;
4685 }
4686
4687 /**
4688  * g_test_get_dir:
4689  * @file_type: the type of file (built vs. distributed)
4690  *
4691  * Gets the pathname of the directory containing test files of the type
4692  * specified by @file_type.
4693  *
4694  * This is approximately the same as calling g_test_build_filename("."),
4695  * but you don't need to free the return value.
4696  *
4697  * Returns: (type filename): the path of the directory, owned by GLib
4698  *
4699  * Since: 2.38
4700  **/
4701 const gchar *
4702 g_test_get_dir (GTestFileType file_type)
4703 {
4704   g_assert (g_test_initialized ());
4705
4706   if (file_type == G_TEST_DIST)
4707     return test_disted_files_dir;
4708   else if (file_type == G_TEST_BUILT)
4709     return test_built_files_dir;
4710
4711   g_assert_not_reached ();
4712 }
4713
4714 /**
4715  * g_test_get_filename:
4716  * @file_type: the type of file (built vs. distributed)
4717  * @first_path: the first segment of the pathname
4718  * @...: %NULL-terminated additional path segments
4719  *
4720  * Gets the pathname to a data file that is required for a test.
4721  *
4722  * This is the same as g_test_build_filename() with two differences.
4723  * The first difference is that you must only use this function from within
4724  * a testcase function.  The second difference is that you need not free
4725  * the return value — it will be automatically freed when the testcase
4726  * finishes running.
4727  *
4728  * It is safe to use this function from a thread inside of a testcase
4729  * but you must ensure that all such uses occur before the main testcase
4730  * function returns (ie: it is best to ensure that all threads have been
4731  * joined).
4732  *
4733  * Returns: the path, automatically freed at the end of the testcase
4734  *
4735  * Since: 2.38
4736  **/
4737 const gchar *
4738 g_test_get_filename (GTestFileType  file_type,
4739                      const gchar   *first_path,
4740                      ...)
4741 {
4742   gchar *result;
4743   GSList *node;
4744   va_list ap;
4745
4746   g_assert (g_test_initialized ());
4747   if (test_filename_free_list == NULL)
4748     g_error ("g_test_get_filename() can only be used within testcase functions");
4749
4750   va_start (ap, first_path);
4751   result = g_test_build_filename_va (file_type, first_path, ap);
4752   va_end (ap);
4753
4754   node = g_slist_prepend (NULL, result);
4755   do
4756     node->next = *test_filename_free_list;
4757   while (!g_atomic_pointer_compare_and_exchange (test_filename_free_list, node->next, node));
4758
4759   return result;
4760 }
4761
4762 /**
4763  * g_test_get_path:
4764  *
4765  * Gets the test path for the test currently being run.
4766  *
4767  * In essence, it will be the same string passed as the first argument to
4768  * e.g. g_test_add() when the test was added.
4769  *
4770  * This function returns a valid string only within a test function.
4771  *
4772  * Note that this is a test path, not a file system path.
4773  *
4774  * Returns: the test path for the test currently being run
4775  *
4776  * Since: 2.68
4777  **/
4778 const char *
4779 g_test_get_path (void)
4780 {
4781   return test_run_name;
4782 }