Coverage Report

Created: 2026-07-25 06:37

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