Coverage Report

Created: 2025-06-13 06:21

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