Coverage Report

Created: 2025-10-13 06:07

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