Coverage Report

Created: 2025-07-23 06:42

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