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