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