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