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

source code of gtk/subprojects/glib/glib/gtestutils.c