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