Coverage Report

Created: 2025-09-05 06:29

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