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