gtestutils.c 111 KB
Newer Older
1
/* GLib testing utilities
2
3
 * Copyright (C) 2007 Imendio AB
 * Authors: Tim Janik, Sven Herzberg
4
5
6
7
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
8
 * version 2.1 of the License, or (at your option) any later version.
9
10
11
12
13
14
15
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
17
 */
18

Tim Janik's avatar
Tim Janik committed
19
#include "config.h"
20

21
#include "gtestutils.h"
Alexander Larsson's avatar
Alexander Larsson committed
22
#include "gfileutils.h"
23

24
#include <sys/types.h>
25
#ifdef G_OS_UNIX
26
#include <sys/wait.h>
27
#include <sys/time.h>
28
#include <fcntl.h>
29
#include <unistd.h>
30
#include <glib/gstdio.h>
31
#endif
Tim Janik's avatar
Tim Janik committed
32
33
#include <string.h>
#include <stdlib.h>
Matthias Clasen's avatar
Matthias Clasen committed
34
#include <stdio.h>
35
36
37
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
38
39
#ifdef G_OS_WIN32
#include <io.h>
40
#include <windows.h>
41
#endif
42
43
44
45
46
#include <errno.h>
#include <signal.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif /* HAVE_SYS_SELECT_H */
47
48
49
50
51

#include "gmain.h"
#include "gpattern.h"
#include "grand.h"
#include "gstrfuncs.h"
52
#include "gstrfuncsprivate.h"
53
#include "gtimer.h"
54
#include "gslice.h"
55
56
#include "gspawn.h"
#include "glib-private.h"
57

58

Matthias Clasen's avatar
Matthias Clasen committed
59
60
61
62
/**
 * SECTION:testing
 * @title: Testing
 * @short_description: a test framework
Matthias Clasen's avatar
Matthias Clasen committed
63
 * @see_also: [gtester][gtester], [gtester-report][gtester-report]
Matthias Clasen's avatar
Matthias Clasen committed
64
65
66
67
68
69
 *
 * GLib provides a framework for writing and maintaining unit tests
 * in parallel to the code they are testing. The API is designed according
 * to established concepts found in the other test frameworks (JUnit, NUnit,
 * RUnit), which in turn is based on smalltalk unit testing concepts.
 *
70
71
72
73
74
75
76
77
78
79
80
81
82
 * - Test case: Tests (test methods) are grouped together with their
 *   fixture into test cases.
 *
 * - Fixture: A test fixture consists of fixture data and setup and
 *   teardown methods to establish the environment for the test
 *   functions. We use fresh fixtures, i.e. fixtures are newly set
 *   up and torn down around each test invocation to avoid dependencies
 *   between tests.
 *
 * - Test suite: Test cases can be grouped into test suites, to allow
 *   subsets of the available tests to be run. Test suites can be
 *   grouped into other test suites as well.
 *
Matthias Clasen's avatar
Matthias Clasen committed
83
84
 * The API is designed to handle creation and registration of test suites
 * and test cases implicitly. A simple call like
85
 * |[<!-- language="C" --> 
Matthias Clasen's avatar
Matthias Clasen committed
86
87
88
89
90
 *   g_test_add_func ("/misc/assertions", test_assertions);
 * ]|
 * creates a test suite called "misc" with a single test case named
 * "assertions", which consists of running the test_assertions function.
 *
91
 * In addition to the traditional g_assert_true(), the test framework provides
92
 * an extended set of assertions for comparisons: g_assert_cmpfloat(),
93
94
 * g_assert_cmpfloat_with_epsilon(), g_assert_cmpint(), g_assert_cmpuint(),
 * g_assert_cmphex(), g_assert_cmpstr(), and g_assert_cmpmem(). The
95
 * advantage of these variants over plain g_assert_true() is that the assertion
96
97
 * messages can be more elaborate, and include the values of the compared
 * entities.
Matthias Clasen's avatar
Matthias Clasen committed
98
 *
99
100
101
102
 * Note that g_assert() should not be used in unit tests, since it is a no-op
 * when compiling with `G_DISABLE_ASSERT`. Use g_assert() in production code,
 * and g_assert_true() in unit tests.
 *
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
 * A full example of creating a test suite with two tests using fixtures:
 * |[<!-- language="C" -->
 * #include <glib.h>
 * #include <locale.h>
 *
 * typedef struct {
 *   MyObject *obj;
 *   OtherObject *helper;
 * } MyObjectFixture;
 *
 * static void
 * my_object_fixture_set_up (MyObjectFixture *fixture,
 *                           gconstpointer user_data)
 * {
 *   fixture->obj = my_object_new ();
 *   my_object_set_prop1 (fixture->obj, "some-value");
 *   my_object_do_some_complex_setup (fixture->obj, user_data);
 *
 *   fixture->helper = other_object_new ();
 * }
 *
 * static void
 * my_object_fixture_tear_down (MyObjectFixture *fixture,
 *                              gconstpointer user_data)
 * {
 *   g_clear_object (&fixture->helper);
 *   g_clear_object (&fixture->obj);
 * }
 *
 * static void
 * test_my_object_test1 (MyObjectFixture *fixture,
 *                       gconstpointer user_data)
 * {
 *   g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "initial-value");
 * }
 *
 * static void
 * test_my_object_test2 (MyObjectFixture *fixture,
 *                       gconstpointer user_data)
 * {
 *   my_object_do_some_work_using_helper (fixture->obj, fixture->helper);
 *   g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "updated-value");
 * }
 *
 * int
 * main (int argc, char *argv[])
 * {
 *   setlocale (LC_ALL, "");
 *
 *   g_test_init (&argc, &argv, NULL);
 *   g_test_bug_base ("http://bugzilla.gnome.org/show_bug.cgi?id=");
 *
 *   // Define the tests.
 *   g_test_add ("/my-object/test1", MyObjectFixture, "some-user-data",
 *               my_object_fixture_set_up, test_my_object_test1,
 *               my_object_fixture_tear_down);
 *   g_test_add ("/my-object/test2", MyObjectFixture, "some-user-data",
 *               my_object_fixture_set_up, test_my_object_test2,
 *               my_object_fixture_tear_down);
 *
 *   return g_test_run ();
 * }
 * ]|
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
 *
 * ### Integrating GTest in your project
 *
 * If you are using the [Meson](http://mesonbuild.com) build system, you will
 * typically use the provided `test()` primitive to call the test binaries,
 * e.g.:
 *
 * |[<!-- language="plain" -->
 *   test(
 *     'foo',
 *     executable('foo', 'foo.c', dependencies: deps),
 *     env: [
 *       'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
 *       'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
 *     ],
 *   )
 *
 *   test(
 *     'bar',
 *     executable('bar', 'bar.c', dependencies: deps),
 *     env: [
 *       'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
 *       'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
 *     ],
 *   )
 * ]|
 *
 * If you are using Autotools, you're strongly encouraged to use the Automake
 * [TAP](https://testanything.org/) harness; GLib provides template files for
 * easily integrating with it:
 *
 *   - [glib-tap.mk](https://git.gnome.org/browse/glib/tree/glib-tap.mk)
 *   - [tap-test](https://git.gnome.org/browse/glib/tree/tap-test)
 *   - [tap-driver.sh](https://git.gnome.org/browse/glib/tree/tap-driver.sh)
 *
 * You can copy these files in your own project's root directory, and then
 * set up your `Makefile.am` file to reference them, for instance:
 *
 * |[<!-- language="plain" -->
 * include $(top_srcdir)/glib-tap.mk
 *
 * # test binaries
 * test_programs = \
 *   foo \
 *   bar
 *
 * # data distributed in the tarball
 * dist_test_data = \
 *   foo.data.txt \
 *   bar.data.txt
 *
 * # data not distributed in the tarball
 * test_data = \
 *   blah.data.txt
 * ]|
 *
 * Make sure to distribute the TAP files, using something like the following
 * in your top-level `Makefile.am`:
 *
 * |[<!-- language="plain" -->
 * EXTRA_DIST += \
 *   tap-driver.sh \
 *   tap-test
 * ]|
 *
 * `glib-tap.mk` will be distributed implicitly due to being included in a
 * `Makefile.am`. All three files should be added to version control.
 *
 * If you don't have access to the Autotools TAP harness, you can use the
 * [gtester][gtester] and [gtester-report][gtester-report] tools, and use
 * the [glib.mk](https://git.gnome.org/browse/glib/tree/glib.mk) Automake
 * template provided by GLib.
Matthias Clasen's avatar
Matthias Clasen committed
238
239
 */

240
241
242
243
244
245
246
247
248
249
/**
 * g_test_initialized:
 *
 * Returns %TRUE if g_test_init() has been called.
 *
 * Returns: %TRUE if g_test_init() has been called.
 *
 * Since: 2.36
 */

Matthias Clasen's avatar
Matthias Clasen committed
250
251
252
253
/**
 * g_test_quick:
 *
 * Returns %TRUE if tests are run in quick mode.
254
255
 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
 * there is no "medium speed".
Matthias Clasen's avatar
Matthias Clasen committed
256
 *
257
258
259
260
 * By default, tests are run in quick mode. In tests that use
 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
 * can be used to change this.
 *
Matthias Clasen's avatar
Matthias Clasen committed
261
262
263
264
265
266
267
 * Returns: %TRUE if in quick mode
 */

/**
 * g_test_slow:
 *
 * Returns %TRUE if tests are run in slow mode.
268
269
 * Exactly one of g_test_quick() and g_test_slow() is active in any run;
 * there is no "medium speed".
Matthias Clasen's avatar
Matthias Clasen committed
270
 *
271
272
273
274
 * By default, tests are run in quick mode. In tests that use
 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
 * can be used to change this.
 *
275
 * Returns: the opposite of g_test_quick()
Matthias Clasen's avatar
Matthias Clasen committed
276
277
278
279
280
 */

/**
 * g_test_thorough:
 *
281
282
 * Returns %TRUE if tests are run in thorough mode, equivalent to
 * g_test_slow().
Matthias Clasen's avatar
Matthias Clasen committed
283
 *
284
285
286
287
 * By default, tests are run in quick mode. In tests that use
 * g_test_init(), the options `-m quick`, `-m slow` and `-m thorough`
 * can be used to change this.
 *
288
 * Returns: the same thing as g_test_slow()
Matthias Clasen's avatar
Matthias Clasen committed
289
290
291
292
293
294
295
 */

/**
 * g_test_perf:
 *
 * Returns %TRUE if tests are run in performance mode.
 *
296
297
298
299
 * By default, tests are run in quick mode. In tests that use
 * g_test_init(), the option `-m perf` enables performance tests, while
 * `-m quick` disables them.
 *
Matthias Clasen's avatar
Matthias Clasen committed
300
301
302
 * Returns: %TRUE if in performance mode
 */

303
304
305
306
/**
 * g_test_undefined:
 *
 * Returns %TRUE if tests may provoke assertions and other formally-undefined
307
 * behaviour, to verify that appropriate warnings are given. It might, in some
308
309
310
311
 * cases, be useful to turn this off with if running tests under valgrind;
 * in tests that use g_test_init(), the option `-m no-undefined` disables
 * those tests, while `-m undefined` explicitly enables them (the default
 * behaviour).
312
313
314
315
 *
 * Returns: %TRUE if tests may provoke programming errors
 */

Matthias Clasen's avatar
Matthias Clasen committed
316
317
318
319
/**
 * g_test_verbose:
 *
 * Returns %TRUE if tests are run in verbose mode.
320
321
 * In tests that use g_test_init(), the option `--verbose` enables this,
 * while `-q` or `--quiet` disables it.
322
 * The default is neither g_test_verbose() nor g_test_quiet().
Matthias Clasen's avatar
Matthias Clasen committed
323
324
325
326
327
328
329
330
 *
 * Returns: %TRUE if in verbose mode
 */

/**
 * g_test_quiet:
 *
 * Returns %TRUE if tests are run in quiet mode.
331
332
 * In tests that use g_test_init(), the option `-q` or `--quiet` enables
 * this, while `--verbose` disables it.
333
 * The default is neither g_test_verbose() nor g_test_quiet().
Matthias Clasen's avatar
Matthias Clasen committed
334
 *
335
 * Returns: %TRUE if in quiet mode
Matthias Clasen's avatar
Matthias Clasen committed
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
 */

/**
 * g_test_queue_unref:
 * @gobject: the object to unref
 *
 * Enqueue an object to be released with g_object_unref() during
 * the next teardown phase. This is equivalent to calling
 * g_test_queue_destroy() with a destroy callback of g_object_unref().
 *
 * Since: 2.16
 */

/**
 * GTestTrapFlags:
 * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
Matthias Clasen's avatar
Matthias Clasen committed
352
353
354
 *     `/dev/null` so it cannot be observed on the console during test
 *     runs. The actual output is still captured though to allow later
 *     tests with g_test_trap_assert_stdout().
Matthias Clasen's avatar
Matthias Clasen committed
355
 * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
Matthias Clasen's avatar
Matthias Clasen committed
356
357
358
 *     `/dev/null` so it cannot be observed on the console during test
 *     runs. The actual output is still captured though to allow later
 *     tests with g_test_trap_assert_stderr().
Matthias Clasen's avatar
Matthias Clasen committed
359
 * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
360
 *     child process is shared with stdin of its parent process.
Matthias Clasen's avatar
Matthias Clasen committed
361
 *     It is redirected to `/dev/null` otherwise.
Matthias Clasen's avatar
Matthias Clasen committed
362
 *
363
 * Test traps are guards around forked tests.
Matthias Clasen's avatar
Matthias Clasen committed
364
 * These flags determine what traps to set.
365
366
367
 *
 * Deprecated: #GTestTrapFlags is used only with g_test_trap_fork(),
 * which is deprecated. g_test_trap_subprocess() uses
368
 * #GTestSubprocessFlags.
369
370
371
372
373
374
 */

/**
 * GTestSubprocessFlags:
 * @G_TEST_SUBPROCESS_INHERIT_STDIN: If this flag is given, the child
 *     process will inherit the parent's stdin. Otherwise, the child's
Matthias Clasen's avatar
Matthias Clasen committed
375
 *     stdin is redirected to `/dev/null`.
376
377
378
379
380
381
382
383
384
385
386
387
388
 * @G_TEST_SUBPROCESS_INHERIT_STDOUT: If this flag is given, the child
 *     process will inherit the parent's stdout. Otherwise, the child's
 *     stdout will not be visible, but it will be captured to allow
 *     later tests with g_test_trap_assert_stdout().
 * @G_TEST_SUBPROCESS_INHERIT_STDERR: If this flag is given, the child
 *     process will inherit the parent's stderr. Otherwise, the child's
 *     stderr will not be visible, but it will be captured to allow
 *     later tests with g_test_trap_assert_stderr().
 *
 * Flags to pass to g_test_trap_subprocess() to control input and output.
 *
 * Note that in contrast with g_test_trap_fork(), the default is to
 * not show stdout and stderr.
Matthias Clasen's avatar
Matthias Clasen committed
389
390
391
392
393
 */

/**
 * g_test_trap_assert_passed:
 *
394
395
 * Assert that the last test subprocess passed.
 * See g_test_trap_subprocess().
Matthias Clasen's avatar
Matthias Clasen committed
396
397
398
399
400
401
402
 *
 * Since: 2.16
 */

/**
 * g_test_trap_assert_failed:
 *
403
404
 * Assert that the last test subprocess failed.
 * See g_test_trap_subprocess().
Matthias Clasen's avatar
Matthias Clasen committed
405
 *
406
407
408
 * This is sometimes used to test situations that are formally considered to
 * be undefined behaviour, like inputs that fail a g_return_if_fail()
 * check. In these situations you should skip the entire test, including the
409
 * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
410
411
 * to indicate that undefined behaviour may be tested.
 *
Matthias Clasen's avatar
Matthias Clasen committed
412
413
414
415
416
 * Since: 2.16
 */

/**
 * g_test_trap_assert_stdout:
Matthias Clasen's avatar
Matthias Clasen committed
417
 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
Matthias Clasen's avatar
Matthias Clasen committed
418
 *
419
420
 * Assert that the stdout output of the last test subprocess matches
 * @soutpattern. See g_test_trap_subprocess().
Matthias Clasen's avatar
Matthias Clasen committed
421
422
423
424
425
426
 *
 * Since: 2.16
 */

/**
 * g_test_trap_assert_stdout_unmatched:
Matthias Clasen's avatar
Matthias Clasen committed
427
 * @soutpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
Matthias Clasen's avatar
Matthias Clasen committed
428
 *
429
430
 * Assert that the stdout output of the last test subprocess
 * does not match @soutpattern. See g_test_trap_subprocess().
Matthias Clasen's avatar
Matthias Clasen committed
431
432
433
434
435
436
 *
 * Since: 2.16
 */

/**
 * g_test_trap_assert_stderr:
Matthias Clasen's avatar
Matthias Clasen committed
437
 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
Matthias Clasen's avatar
Matthias Clasen committed
438
 *
439
440
 * Assert that the stderr output of the last test subprocess
 * matches @serrpattern. See  g_test_trap_subprocess().
Matthias Clasen's avatar
Matthias Clasen committed
441
 *
442
443
444
445
446
447
 * This is sometimes used to test situations that are formally
 * considered to be undefined behaviour, like code that hits a
 * g_assert() or g_error(). In these situations you should skip the
 * entire test, including the call to g_test_trap_subprocess(), unless
 * g_test_undefined() returns %TRUE to indicate that undefined
 * behaviour may be tested.
448
 *
Matthias Clasen's avatar
Matthias Clasen committed
449
450
451
452
453
 * Since: 2.16
 */

/**
 * g_test_trap_assert_stderr_unmatched:
Matthias Clasen's avatar
Matthias Clasen committed
454
 * @serrpattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
Matthias Clasen's avatar
Matthias Clasen committed
455
 *
456
457
 * Assert that the stderr output of the last test subprocess
 * does not match @serrpattern. See g_test_trap_subprocess().
Matthias Clasen's avatar
Matthias Clasen committed
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
 *
 * Since: 2.16
 */

/**
 * g_test_rand_bit:
 *
 * Get a reproducible random bit (0 or 1), see g_test_rand_int()
 * for details on test case random numbers.
 *
 * Since: 2.16
 */

/**
 * g_assert:
 * @expr: the expression to check
 *
 * Debugging macro to terminate the application if the assertion
 * fails. If the assertion fails (i.e. the expression is not true),
 * an error message is logged and the application is terminated.
 *
 * The macro can be turned off in final releases of code by defining
480
 * `G_DISABLE_ASSERT` when compiling the application, so code must
481
482
483
484
 * not depend on any side effects from @expr. Similarly, it must not be used
 * in unit tests, otherwise the unit tests will be ineffective if compiled with
 * `G_DISABLE_ASSERT`. Use g_assert_true() and related macros in unit tests
 * instead.
Matthias Clasen's avatar
Matthias Clasen committed
485
486
487
488
489
490
491
492
493
494
 */

/**
 * g_assert_not_reached:
 *
 * Debugging macro to terminate the application if it is ever
 * reached. If it is reached, an error message is logged and the
 * application is terminated.
 *
 * The macro can be turned off in final releases of code by defining
495
496
 * `G_DISABLE_ASSERT` when compiling the application. Hence, it should not be
 * used in unit tests, where assertions should always be effective.
Matthias Clasen's avatar
Matthias Clasen committed
497
498
 */

499
500
501
502
503
504
/**
 * g_assert_true:
 * @expr: the expression to check
 *
 * Debugging macro to check that an expression is true.
 *
505
506
507
508
 * If the assertion fails (i.e. the expression is not true),
 * an error message is logged and the application is either
 * terminated or the testcase marked as failed.
 *
509
510
511
512
 * Note that unlike g_assert(), this macro is unaffected by whether
 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
 * conversely, g_assert() should not be used in tests.
 *
513
514
 * See g_test_set_nonfatal_assertions().
 *
515
516
517
518
519
520
521
522
523
 * Since: 2.38
 */

/**
 * g_assert_false:
 * @expr: the expression to check
 *
 * Debugging macro to check an expression is false.
 *
524
525
526
527
 * If the assertion fails (i.e. the expression is not false),
 * an error message is logged and the application is either
 * terminated or the testcase marked as failed.
 *
528
529
530
531
 * Note that unlike g_assert(), this macro is unaffected by whether
 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
 * conversely, g_assert() should not be used in tests.
 *
532
533
 * See g_test_set_nonfatal_assertions().
 *
534
535
536
537
538
539
540
541
542
 * Since: 2.38
 */

/**
 * g_assert_null:
 * @expr: the expression to check
 *
 * Debugging macro to check an expression is %NULL.
 *
543
544
545
546
 * If the assertion fails (i.e. the expression is not %NULL),
 * an error message is logged and the application is either
 * terminated or the testcase marked as failed.
 *
547
548
549
550
 * Note that unlike g_assert(), this macro is unaffected by whether
 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
 * conversely, g_assert() should not be used in tests.
 *
551
552
 * See g_test_set_nonfatal_assertions().
 *
553
554
555
 * Since: 2.38
 */

556
557
558
559
560
561
562
563
564
565
/**
 * g_assert_nonnull:
 * @expr: the expression to check
 *
 * Debugging macro to check an expression is not %NULL.
 *
 * If the assertion fails (i.e. the expression is %NULL),
 * an error message is logged and the application is either
 * terminated or the testcase marked as failed.
 *
566
567
568
569
 * Note that unlike g_assert(), this macro is unaffected by whether
 * `G_DISABLE_ASSERT` is defined. Hence it should only be used in tests and,
 * conversely, g_assert() should not be used in tests.
 *
570
571
572
573
574
 * See g_test_set_nonfatal_assertions().
 *
 * Since: 2.40
 */

Matthias Clasen's avatar
Matthias Clasen committed
575
576
577
578
/**
 * g_assert_cmpstr:
 * @s1: a string (may be %NULL)
 * @cmp: The comparison operator to use.
579
 *     One of ==, !=, <, >, <=, >=.
Matthias Clasen's avatar
Matthias Clasen committed
580
581
 * @s2: another string (may be %NULL)
 *
582
583
584
585
 * Debugging macro to compare two strings. If the comparison fails,
 * an error message is logged and the application is either terminated
 * or the testcase marked as failed.
 * The strings are compared using g_strcmp0().
Matthias Clasen's avatar
Matthias Clasen committed
586
 *
Matthias Clasen's avatar
Matthias Clasen committed
587
588
 * The effect of `g_assert_cmpstr (s1, op, s2)` is
 * the same as `g_assert_true (g_strcmp0 (s1, s2) op 0)`.
Matthias Clasen's avatar
Matthias Clasen committed
589
590
591
 * The advantage of this macro is that it can produce a message that
 * includes the actual values of @s1 and @s2.
 *
592
 * |[<!-- language="C" --> 
Matthias Clasen's avatar
Matthias Clasen committed
593
594
595
596
597
598
599
600
601
602
 *   g_assert_cmpstr (mystring, ==, "fubar");
 * ]|
 *
 * Since: 2.16
 */

/**
 * g_assert_cmpint:
 * @n1: an integer
 * @cmp: The comparison operator to use.
603
 *     One of ==, !=, <, >, <=, >=.
Matthias Clasen's avatar
Matthias Clasen committed
604
605
 * @n2: another integer
 *
606
 * Debugging macro to compare two integers.
Matthias Clasen's avatar
Matthias Clasen committed
607
 *
Matthias Clasen's avatar
Matthias Clasen committed
608
609
 * The effect of `g_assert_cmpint (n1, op, n2)` is
 * the same as `g_assert_true (n1 op n2)`. The advantage
Matthias Clasen's avatar
Matthias Clasen committed
610
611
612
613
614
615
616
617
618
619
 * of this macro is that it can produce a message that includes the
 * actual values of @n1 and @n2.
 *
 * Since: 2.16
 */

/**
 * g_assert_cmpuint:
 * @n1: an unsigned integer
 * @cmp: The comparison operator to use.
620
 *     One of ==, !=, <, >, <=, >=.
Matthias Clasen's avatar
Matthias Clasen committed
621
622
 * @n2: another unsigned integer
 *
623
 * Debugging macro to compare two unsigned integers.
Matthias Clasen's avatar
Matthias Clasen committed
624
 *
Matthias Clasen's avatar
Matthias Clasen committed
625
626
 * The effect of `g_assert_cmpuint (n1, op, n2)` is
 * the same as `g_assert_true (n1 op n2)`. The advantage
Matthias Clasen's avatar
Matthias Clasen committed
627
628
629
630
631
632
633
634
635
636
 * of this macro is that it can produce a message that includes the
 * actual values of @n1 and @n2.
 *
 * Since: 2.16
 */

/**
 * g_assert_cmphex:
 * @n1: an unsigned integer
 * @cmp: The comparison operator to use.
637
 *     One of ==, !=, <, >, <=, >=.
Matthias Clasen's avatar
Matthias Clasen committed
638
639
 * @n2: another unsigned integer
 *
640
 * Debugging macro to compare to unsigned integers.
Matthias Clasen's avatar
Matthias Clasen committed
641
642
643
644
645
646
647
648
649
650
651
 *
 * This is a variant of g_assert_cmpuint() that displays the numbers
 * in hexadecimal notation in the message.
 *
 * Since: 2.16
 */

/**
 * g_assert_cmpfloat:
 * @n1: an floating point number
 * @cmp: The comparison operator to use.
652
 *     One of ==, !=, <, >, <=, >=.
Matthias Clasen's avatar
Matthias Clasen committed
653
654
 * @n2: another floating point number
 *
655
 * Debugging macro to compare two floating point numbers.
Matthias Clasen's avatar
Matthias Clasen committed
656
 *
Matthias Clasen's avatar
Matthias Clasen committed
657
658
 * The effect of `g_assert_cmpfloat (n1, op, n2)` is
 * the same as `g_assert_true (n1 op n2)`. The advantage
Matthias Clasen's avatar
Matthias Clasen committed
659
660
661
662
663
664
 * of this macro is that it can produce a message that includes the
 * actual values of @n1 and @n2.
 *
 * Since: 2.16
 */

665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
/**
 * g_assert_cmpfloat_with_epsilon:
 * @n1: an floating point number
 * @n2: another floating point number
 * @epsilon: a numeric value that expresses the expected tolerance
 *   between @n1 and @n2
 *
 * Debugging macro to compare two floating point numbers within an epsilon.
 *
 * The effect of `g_assert_cmpfloat_with_epsilon (n1, n2, epsilon)` is
 * the same as `g_assert_true (abs (n1 - n2) < epsilon)`. The advantage
 * of this macro is that it can produce a message that includes the
 * actual values of @n1 and @n2.
 *
 * Since: 2.58
 */

682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
/**
 * g_assert_cmpmem:
 * @m1: pointer to a buffer
 * @l1: length of @m1
 * @m2: pointer to another buffer
 * @l2: length of @m2
 *
 * Debugging macro to compare memory regions. If the comparison fails,
 * an error message is logged and the application is either terminated
 * or the testcase marked as failed.
 *
 * The effect of `g_assert_cmpmem (m1, l1, m2, l2)` is
 * the same as `g_assert_true (l1 == l2 && memcmp (m1, m2, l1) == 0)`.
 * The advantage of this macro is that it can produce a message that
 * includes the actual values of @l1 and @l2.
 *
 * |[<!-- language="C" -->
 *   g_assert_cmpmem (buf->data, buf->len, expected, sizeof (expected));
 * ]|
 *
 * Since: 2.46
 */

Matthias Clasen's avatar
Matthias Clasen committed
705
706
707
708
/**
 * g_assert_no_error:
 * @err: a #GError, possibly %NULL
 *
709
 * Debugging macro to check that a #GError is not set.
Matthias Clasen's avatar
Matthias Clasen committed
710
 *
Matthias Clasen's avatar
Matthias Clasen committed
711
712
 * The effect of `g_assert_no_error (err)` is
 * the same as `g_assert_true (err == NULL)`. The advantage
Matthias Clasen's avatar
Matthias Clasen committed
713
714
715
716
717
718
719
720
721
722
723
724
 * of this macro is that it can produce a message that includes
 * the error message and code.
 *
 * Since: 2.20
 */

/**
 * g_assert_error:
 * @err: a #GError, possibly %NULL
 * @dom: the expected error domain (a #GQuark)
 * @c: the expected error code
 *
725
726
 * Debugging macro to check that a method has returned
 * the correct #GError.
Matthias Clasen's avatar
Matthias Clasen committed
727
 *
Matthias Clasen's avatar
Matthias Clasen committed
728
 * The effect of `g_assert_error (err, dom, c)` is
729
730
 * the same as `g_assert_true (err != NULL && err->domain
 * == dom && err->code == c)`. The advantage of this
Matthias Clasen's avatar
Matthias Clasen committed
731
732
733
734
735
 * macro is that it can produce a message that includes the incorrect
 * error message and code.
 *
 * This can only be used to test for a specific error. If you want to
 * test that @err is set, but don't care what it's set to, just use
Matthias Clasen's avatar
Matthias Clasen committed
736
 * `g_assert (err != NULL)`
Matthias Clasen's avatar
Matthias Clasen committed
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
 *
 * Since: 2.20
 */

/**
 * GTestCase:
 *
 * An opaque structure representing a test case.
 */

/**
 * GTestSuite:
 *
 * An opaque structure representing a test suite.
 */


754
755
756
/* Global variable for storing assertion messages; this is the counterpart to
 * glibc's (private) __abort_msg variable, and allows developers and crash
 * analysis systems like Apport and ABRT to fish out assertion messages from
Matthias Clasen's avatar
Matthias Clasen committed
757
758
 * core dumps, instead of having to catch them on screen output.
 */
Allison Karlitskaya's avatar
Allison Karlitskaya committed
759
GLIB_VAR char *__glib_assert_msg;
760
char *__glib_assert_msg = NULL;
Tim Janik's avatar
Tim Janik committed
761

762
763
764
/* --- constants --- */
#define G_TEST_STATUS_TIMED_OUT 1024

Tim Janik's avatar
Tim Janik committed
765
766
767
768
769
/* --- structures --- */
struct GTestCase
{
  gchar  *name;
  guint   fixture_size;
770
771
772
773
  void   (*fixture_setup)    (void*, gconstpointer);
  void   (*fixture_test)     (void*, gconstpointer);
  void   (*fixture_teardown) (void*, gconstpointer);
  gpointer test_data;
Tim Janik's avatar
Tim Janik committed
774
775
776
777
778
779
780
};
struct GTestSuite
{
  gchar  *name;
  GSList *suites;
  GSList *cases;
};
781
782
783
784
785
786
787
typedef struct DestroyEntry DestroyEntry;
struct DestroyEntry
{
  DestroyEntry *next;
  GDestroyNotify destroy_func;
  gpointer       destroy_data;
};
Tim Janik's avatar
Tim Janik committed
788

789
/* --- prototypes --- */
790
791
792
793
794
795
796
797
798
static void     test_run_seed                   (const gchar *rseed);
static void     test_trap_clear                 (void);
static guint8*  g_test_log_dump                 (GTestLogMsg *msg,
                                                 guint       *len);
static void     gtest_default_log_handler       (const gchar    *log_domain,
                                                 GLogLevelFlags  log_level,
                                                 const gchar    *message,
                                                 gpointer        unused_data);

799

800
801
802
803
804
805
static const char * const g_test_result_names[] = {
  "OK",
  "SKIP",
  "FAIL",
  "TODO"
};
806

Tim Janik's avatar
Tim Janik committed
807
/* --- variables --- */
Tim Janik's avatar
Tim Janik committed
808
static int         test_log_fd = -1;
Tim Janik's avatar
Tim Janik committed
809
810
811
static gboolean    test_mode_fatal = TRUE;
static gboolean    g_test_run_once = TRUE;
static gboolean    test_run_list = FALSE;
Tim Janik's avatar
Tim Janik committed
812
813
static gchar      *test_run_seedstr = NULL;
static GRand      *test_run_rand = NULL;
Tim Janik's avatar
Tim Janik committed
814
static gchar      *test_run_name = "";
815
static GSList    **test_filename_free_list;
Tim Janik's avatar
Tim Janik committed
816
static guint       test_run_forks = 0;
817
static guint       test_run_count = 0;
818
static guint       test_count = 0;
819
static guint       test_skipped_count = 0;
820
static GTestResult test_run_success = G_TEST_RUN_FAILURE;
821
static gchar      *test_run_msg = NULL;
822
static guint       test_startup_skip_count = 0;
Tim Janik's avatar
Tim Janik committed
823
824
static GTimer     *test_user_timer = NULL;
static double      test_user_stamp = 0;
Tim Janik's avatar
Tim Janik committed
825
static GSList     *test_paths = NULL;
826
static GSList     *test_paths_skipped = NULL;
Tim Janik's avatar
Tim Janik committed
827
static GTestSuite *test_suite_root = NULL;
828
static int         test_trap_last_status = 0;  /* unmodified platform-specific status */
829
830
static GPid        test_trap_last_pid = 0;
static char       *test_trap_last_subprocess = NULL;
831
832
static char       *test_trap_last_stdout = NULL;
static char       *test_trap_last_stderr = NULL;
833
static char       *test_uri_base = NULL;
Tim Janik's avatar
Tim Janik committed
834
static gboolean    test_debug_log = FALSE;
835
static gboolean    test_tap_log = FALSE;
836
static gboolean    test_nonfatal_assertions = FALSE;
837
static DestroyEntry *test_destroy_queue = NULL;
838
static char       *test_argv0 = NULL;
839
840
841
static char       *test_argv0_dirname;
static const char *test_disted_files_dir;
static const char *test_built_files_dir;
842
static char       *test_initial_cwd = NULL;
843
static gboolean    test_in_forked_child = FALSE;
844
static gboolean    test_in_subprocess = FALSE;
845
static GTestConfig mutable_test_config_vars = {
846
  FALSE,        /* test_initialized */
847
848
849
850
  TRUE,         /* test_quick */
  FALSE,        /* test_perf */
  FALSE,        /* test_verbose */
  FALSE,        /* test_quiet */
851
  TRUE,         /* test_undefined */
852
};
853
const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
854
static gboolean  no_g_set_prgname = FALSE;
Tim Janik's avatar
Tim Janik committed
855
856

/* --- functions --- */
Tim Janik's avatar
Tim Janik committed
857
858
const char*
g_test_log_type_name (GTestLogType log_type)
Tim Janik's avatar
Tim Janik committed
859
{
Tim Janik's avatar
Tim Janik committed
860
  switch (log_type)
Tim Janik's avatar
Tim Janik committed
861
    {
862
863
    case G_TEST_LOG_NONE:               return "none";
    case G_TEST_LOG_ERROR:              return "error";
Tim Janik's avatar
Tim Janik committed
864
865
    case G_TEST_LOG_START_BINARY:       return "binary";
    case G_TEST_LOG_LIST_CASE:          return "list";
866
    case G_TEST_LOG_SKIP_CASE:          return "skip";
Tim Janik's avatar
Tim Janik committed
867
868
869
870
    case G_TEST_LOG_START_CASE:         return "start";
    case G_TEST_LOG_STOP_CASE:          return "stop";
    case G_TEST_LOG_MIN_RESULT:         return "minperf";
    case G_TEST_LOG_MAX_RESULT:         return "maxperf";
871
    case G_TEST_LOG_MESSAGE:            return "message";
872
873
    case G_TEST_LOG_START_SUITE:        return "start suite";
    case G_TEST_LOG_STOP_SUITE:         return "stop suite";
Tim Janik's avatar
Tim Janik committed
874
    }
875
  return "???";
Tim Janik's avatar
Tim Janik committed
876
877
878
}

static void
879
880
881
g_test_log_send (guint         n_bytes,
                 const guint8 *buffer)
{
Tim Janik's avatar
Tim Janik committed
882
883
884
885
886
887
888
  if (test_log_fd >= 0)
    {
      int r;
      do
        r = write (test_log_fd, buffer, n_bytes);
      while (r < 0 && errno == EINTR);
    }
889
890
  if (test_debug_log)
    {
891
      GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
892
893
894
895
      GTestLogMsg *msg;
      guint ui;
      g_test_log_buffer_push (lbuffer, n_bytes, buffer);
      msg = g_test_log_buffer_pop (lbuffer);
896
897
      g_warn_if_fail (msg != NULL);
      g_warn_if_fail (lbuffer->data->len == 0);
898
899
      g_test_log_buffer_free (lbuffer);
      /* print message */
Tim Janik's avatar
Tim Janik committed
900
      g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
901
902
903
904
905
906
      for (ui = 0; ui < msg->n_strings; ui++)
        g_printerr (":{%s}", msg->strings[ui]);
      if (msg->n_nums)
        {
          g_printerr (":(");
          for (ui = 0; ui < msg->n_nums; ui++)
907
908
909
910
911
912
            {
              if ((long double) (long) msg->nums[ui] == msg->nums[ui])
                g_printerr ("%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
              else
                g_printerr ("%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
            }
913
914
915
916
917
918
919
920
921
          g_printerr (")");
        }
      g_printerr (":LOG*}\n");
      g_test_log_msg_free (msg);
    }
}

static void
g_test_log (GTestLogType lbit,
Tim Janik's avatar
Tim Janik committed
922
923
924
925
926
            const gchar *string1,
            const gchar *string2,
            guint        n_args,
            long double *largs)
{
927
  GTestResult result;
928
  gboolean fail;
929
930
931
932
  GTestLogMsg msg;
  gchar *astrings[3] = { NULL, NULL, NULL };
  guint8 *dbuffer;
  guint32 dbufferlen;
Tim Janik's avatar
Tim Janik committed
933
934
935

  switch (lbit)
    {
936
    case G_TEST_LOG_START_BINARY:
937
938
      if (test_tap_log)
        g_print ("# random seed: %s\n", string2);
939
      else if (g_test_verbose ())
940
941
        g_print ("GTest: random seed: %s\n", string2);
      break;
942
    case G_TEST_LOG_START_SUITE:
943
944
945
946
      if (test_tap_log)
        {
          if (string1[0] != 0)
            g_print ("# Start of %s tests\n", string1);
947
948
          else
            g_print ("1..%d\n", test_count);
949
        }
950
951
      break;
    case G_TEST_LOG_STOP_SUITE:
952
953
954
955
956
      if (test_tap_log)
        {
          if (string1[0] != 0)
            g_print ("# End of %s tests\n", string1);
        }
957
      break;
Tim Janik's avatar
Tim Janik committed
958
    case G_TEST_LOG_STOP_CASE:
959
960
      result = largs[0];
      fail = result == G_TEST_RUN_FAILURE;
961
962
      if (test_tap_log)
        {
963
964
965
966
967
968
969
970
971
972
973
974
975
976
          const gchar *ok;

          /* The TAP representation for an expected failure starts with
           * "not ok", even though it does not actually count as failing
           * due to the use of the TODO directive. "ok # TODO" would mean
           * a test that was expected to fail unexpectedly succeeded,
           * for which GTestResult does not currently have a
           * representation. */
          if (fail || result == G_TEST_RUN_INCOMPLETE)
            ok = "not ok";
          else
            ok = "ok";

          g_print ("%s %d %s", ok, test_run_count, string1);
977
          if (result == G_TEST_RUN_INCOMPLETE)
978
            g_print (" # TODO %s\n", string2 ? string2 : "");
979
          else if (result == G_TEST_RUN_SKIPPED)
980
981
982
983
            g_print (" # SKIP %s\n", string2 ? string2 : "");
          else
            g_print ("\n");
        }
984
      else if (g_test_verbose ())
985
        g_print ("GTest: result: %s\n", g_test_result_names[result]);
986
      else if (!g_test_quiet ())
987
        g_print ("%s\n", g_test_result_names[result]);
Tim Janik's avatar
Tim Janik committed
988
      if (fail && test_mode_fatal)
989
990
991
        {
          if (test_tap_log)
            g_print ("Bail out!\n");
992
          g_abort ();
993
        }
994
      if (result == G_TEST_RUN_SKIPPED || result == G_TEST_RUN_INCOMPLETE)
995
        test_skipped_count++;
Tim Janik's avatar
Tim Janik committed
996
997
      break;
    case G_TEST_LOG_MIN_RESULT:
998
999
      if (test_tap_log)
        g_print ("# min perf: %s\n", string1);
1000
      else if (g_test_verbose ())
Tim Janik's avatar
Tim Janik committed
1001
1002
1003
        g_print ("(MINPERF:%s)\n", string1);
      break;
    case G_TEST_LOG_MAX_RESULT:
1004
1005
      if (test_tap_log)
        g_print ("# max perf: %s\n", string1);
1006
      else if (g_test_verbose ())
Tim Janik's avatar
Tim Janik committed
1007
1008
        g_print ("(MAXPERF:%s)\n", string1);
      break;
1009
    case G_TEST_LOG_MESSAGE:
1010
1011
      if (test_tap_log)
        g_print ("# %s\n", string1);
1012
      else if (g_test_verbose ())
1013
1014
        g_print ("(MSG: %s)\n", string1);
      break;
1015
1016
1017
    case G_TEST_LOG_ERROR:
      if (test_tap_log)
        g_print ("Bail out! %s\n", string1);
1018
      else if (g_test_verbose ())
1019
1020
        g_print ("(ERROR: %s)\n", string1);
      break;
Tim Janik's avatar
Tim Janik committed
1021
1022
1023
    default: ;
    }

1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
  msg.log_type = lbit;
  msg.n_strings = (string1 != NULL) + (string1 && string2);
  msg.strings = astrings;
  astrings[0] = (gchar*) string1;
  astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
  msg.n_nums = n_args;
  msg.nums = largs;
  dbuffer = g_test_log_dump (&msg, &dbufferlen);
  g_test_log_send (dbufferlen, dbuffer);
  g_free (dbuffer);
Tim Janik's avatar
Tim Janik committed
1034
1035
1036
1037

  switch (lbit)
    {
    case G_TEST_LOG_START_CASE:
1038
1039
      if (test_tap_log)
        ;
1040
      else if (g_test_verbose ())
1041
        g_print ("GTest: run: %s\n", string1);
1042
      else if (!g_test_quiet ())
Tim Janik's avatar
Tim Janik committed
1043
1044
1045
1046
1047
1048
        g_print ("%s: ", string1);
      break;
    default: ;
    }
}

1049
1050
1051
/* We intentionally parse the command line without GOptionContext
 * because otherwise you would never be able to test it.
 */
Tim Janik's avatar
Tim Janik committed
1052
1053
1054
1055
1056
1057
1058
static void
parse_args (gint    *argc_p,
            gchar ***argv_p)
{
  guint argc = *argc_p;
  gchar **argv = *argv_p;
  guint i, e;
1059
1060
1061
1062

  test_argv0 = argv[0];
  test_initial_cwd = g_get_current_dir ();

Tim Janik's avatar
Tim Janik committed
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
  /* parse known args */
  for (i = 1; i < argc; i++)
    {
      if (strcmp (argv[i], "--g-fatal-warnings") == 0)
        {
          GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
          fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
          g_log_set_always_fatal (fatal_mask);
          argv[i] = NULL;
        }
      else if (strcmp (argv[i], "--keep-going") == 0 ||
               strcmp (argv[i], "-k") == 0)
        {
          test_mode_fatal = FALSE;
          argv[i] = NULL;
        }
Tim Janik's avatar
Tim Janik committed
1079
1080
1081
1082
1083
      else if (strcmp (argv[i], "--debug-log") == 0)
        {
          test_debug_log = TRUE;
          argv[i] = NULL;
        }
1084
1085
1086
1087
1088
      else if (strcmp (argv[i], "--tap") == 0)
        {
          test_tap_log = TRUE;
          argv[i] = NULL;
        }
Tim Janik's avatar
Tim Janik committed
1089
      else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
Tim Janik's avatar
Tim Janik committed
1090
        {
Tim Janik's avatar
Tim Janik committed
1091
          gchar *equal = argv[i] + 12;
Tim Janik's avatar
Tim Janik committed
1092
          if (*equal == '=')
Tim Janik's avatar
Tim Janik committed
1093
            test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
Tim Janik's avatar
Tim Janik committed
1094
1095
1096
          else if (i + 1 < argc)
            {
              argv[i++] = NULL;
Tim Janik's avatar
Tim Janik committed
1097
              test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
Tim Janik's avatar
Tim Janik committed
1098
1099
1100
            }
          argv[i] = NULL;
        }
1101
      else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
1102
        {
1103
          gchar *equal = argv[i] + 16;
1104
          if (*equal == '=')
1105
            test_startup_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
1106
1107
1108
          else if (i + 1 < argc)
            {
              argv[i++] = NULL;
1109
              test_startup_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
1110
1111
1112
            }
          argv[i] = NULL;
        }
1113
1114
1115
      else if (strcmp ("--GTestSubprocess", argv[i]) == 0)
        {
          test_in_subprocess = TRUE;
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
          /* We typically expect these child processes to crash, and some
           * tests spawn a *lot* of them.  Avoid spamming system crash
           * collection programs such as systemd-coredump and abrt.
           */
#ifdef HAVE_SYS_RESOURCE_H
          {
            struct rlimit limit = { 0, 0 };
            (void) setrlimit (RLIMIT_CORE, &limit);
          }
#endif
1126
1127
          argv[i] = NULL;
        }
1128
      else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
1129
        {
1130
          gchar *equal = argv[i] + 2;
Tim Janik's avatar
Tim Janik committed
1131
          if (*equal == '=')
1132
            test_paths = g_slist_prepend (test_paths, equal + 1);
Tim Janik's avatar
Tim Janik committed
1133
1134
1135
          else if (i + 1 < argc)
            {
              argv[i++] = NULL;
1136
              test_paths = g_slist_prepend (test_paths, argv[i]);
Tim Janik's avatar
Tim Janik committed
1137
1138
1139
            }
          argv[i] = NULL;
        }
1140
      else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
1141
1142
1143
        {
          gchar *equal = argv[i] + 2;
          if (*equal == '=')
1144
            test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
1145
1146
1147
          else if (i + 1 < argc)
            {
              argv[i++] = NULL;
1148
              test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
1149
1150
1151
            }
          argv[i] = NULL;
        }
Tim Janik's avatar
Tim Janik committed
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
      else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
        {
          gchar *equal = argv[i] + 2;
          const gchar *mode = "";
          if (*equal == '=')
            mode = equal + 1;
          else if (i + 1 < argc)
            {
              argv[i++] = NULL;
              mode = argv[i];
            }
          if (strcmp (mode, "perf") == 0)
1164
            mutable_test_config_vars.test_perf = TRUE;
Tim Janik's avatar
Tim Janik committed
1165
          else if (strcmp (mode, "slow") == 0)
1166
            mutable_test_config_vars.test_quick = FALSE;
1167
1168
          else if (strcmp (mode, "thorough") == 0)
            mutable_test_config_vars.test_quick = FALSE;
Tim Janik's avatar
Tim Janik committed
1169
1170
          else if (strcmp (mode, "quick") == 0)
            {
1171
1172
              mutable_test_config_vars.test_quick = TRUE;
              mutable_test_config_vars.test_perf = FALSE;
Tim Janik's avatar
Tim Janik committed
1173
            }
1174
1175
1176
1177
          else if (strcmp (mode, "undefined") == 0)
            mutable_test_config_vars.test_undefined = TRUE;
          else if (strcmp (mode, "no-undefined") == 0)
            mutable_test_config_vars.test_undefined = FALSE;
Tim Janik's avatar
Tim Janik committed
1178
1179
1180
1181
1182
1183
          else
            g_error ("unknown test mode: -m %s", mode);
          argv[i] = NULL;
        }
      else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
        {
1184
1185
          mutable_test_config_vars.test_quiet = TRUE;
          mutable_test_config_vars.test_verbose = FALSE;
Tim Janik's avatar
Tim Janik committed
1186
1187
1188
1189
          argv[i] = NULL;
        }
      else if (strcmp ("--verbose", argv[i]) == 0)
        {
1190
1191
          mutable_test_config_vars.test_quiet = FALSE;
          mutable_test_config_vars.test_verbose = TRUE;
Tim Janik's avatar
Tim Janik committed
1192
1193
1194
1195
1196
1197
1198
          argv[i] = NULL;
        }
      else if (strcmp ("-l", argv[i]) == 0)
        {
          test_run_list = TRUE;
          argv[i] = NULL;
        }
Tim Janik's avatar
Tim Janik committed
1199
      else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
Tim Janik's avatar
Tim Janik committed
1200
        {
Tim Janik's avatar
Tim Janik committed
1201
          gchar *equal = argv[i] + 6;
Tim Janik's avatar
Tim Janik committed
1202
          if (*equal == '=')
Tim Janik's avatar
Tim Janik committed
1203
            test_run_seedstr = equal + 1;
Tim Janik's avatar
Tim Janik committed
1204
1205
1206
          else if (i + 1 < argc)
            {
              argv[i++] = NULL;
Tim Janik's avatar
Tim Janik committed
1207
              test_run_seedstr = argv[i];
Tim Janik's avatar
Tim Janik committed
1208
1209
1210
            }
          argv[i] = NULL;
        }
Matthias Clasen's avatar
Matthias Clasen committed
1211
1212
1213
      else if (strcmp ("-?", argv[i]) == 0 ||
               strcmp ("-h", argv[i]) == 0 ||
               strcmp ("--help", argv[i]) == 0)
1214
1215
1216
1217
        {
          printf ("Usage:\n"
                  "  %s [OPTION...]\n\n"
                  "Help Options:\n"
Matthias Clasen's avatar
Matthias Clasen committed
1218
                  "  -h, --help                     Show help options\n\n"
1219
                  "Test Options:\n"
Matthias Clasen's avatar
Matthias Clasen committed
1220
                  "  --g-fatal-warnings             Make all warnings fatal\n"
1221
                  "  -l                             List test cases available in a test executable\n"
Matthias Clasen's avatar
Matthias Clasen committed
1222
1223
1224
                  "  -m {perf|slow|thorough|quick}  Execute tests according to mode\n"
                  "  -m {undefined|no-undefined}    Execute tests according to mode\n"
                  "  -p TESTPATH                    Only start test cases matching TESTPATH\n"
1225
                  "  -s TESTPATH                    Skip all tests matching TESTPATH\n"
1226
                  "  --seed=SEEDSTRING              Start tests with random seed SEEDSTRING\n"
1227
                  "  --debug-log                    debug test logging output\n"
Matthias Clasen's avatar
Matthias Clasen committed
1228
1229
                  "  -q, --quiet                    Run tests quietly\n"
                  "  --verbose                      Run tests verbosely\n",
1230
1231
1232
                  argv[0]);
          exit (0);
        }
Tim Janik's avatar
Tim Janik committed
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
    }
  /* collapse argv */
  e = 1;
  for (i = 1; i < argc; i++)
    if (argv[i])
      {
        argv[e++] = argv[i];
        if (i >= e)
          argv[i] = NULL;
      }
  *argc_p = e;
}

1246
1247
1248
1249
1250
1251
/**
 * g_test_init:
 * @argc: Address of the @argc parameter of the main() function.
 *        Changed if any arguments were handled.
 * @argv: Address of the @argv parameter of main().
 *        Any parameters understood by g_test_init() stripped before return.
1252
 * @...: %NULL-terminated list of special options. Currently the only
Matthias Clasen's avatar
Matthias Clasen committed
1253
 *       defined option is `"no_g_set_prgname"`, which
1254
 *       will cause g_test_init() to not call g_set_prgname().
1255
1256
1257
1258
 *
 * Initialize the GLib testing framework, e.g. by seeding the
 * test random number generator, the name for g_get_prgname()
 * and parsing test related command line args.
1259
 *
1260
 * So far, the following arguments are understood:
1261
 *
Matthias Clasen's avatar
Matthias Clasen committed
1262
1263
 * - `-l`: List test cases available in a test executable.
 * - `--seed=SEED`: Provide a random seed to reproduce test
1264
 *   runs using random numbers.
Matthias Clasen's avatar
Matthias Clasen committed
1265
1266
1267
 * - `--verbose`: Run tests verbosely.
 * - `-q`, `--quiet`: Run tests quietly.
 * - `-p PATH`: Execute all tests matching the given path.
1268
 * - `-s PATH`: Skip all tests matching the given path.
1269
1270
 *   This can also be used to force a test to run that would otherwise
 *   be skipped (ie, a test whose name contains "/subprocess").
Matthias Clasen's avatar
Matthias Clasen committed
1271
 * - `-m {perf|slow|thorough|quick|undefined|no-undefined}`: Execute tests according to these test modes:
1272
 *
1273
 *   `perf`: Performance tests, may take long and report results (off by default).
1274
 *
1275
1276
 *   `slow`, `thorough`: Slow and thorough tests, may take quite long and maximize coverage
 *   (off by default).
1277
 *
1278
 *   `quick`: Quick tests, should run really quickly and give good coverage (the default).
1279
 *
Matthias Clasen's avatar
Matthias Clasen committed
1280
 *   `undefined`: Tests for undefined behaviour, may provoke programming errors
Matthias Clasen's avatar
Matthias Clasen committed
1281
 *   under g_test_trap_subprocess() or g_test_expect_message() to check
1282
 *   that appropriate assertions or warnings are given (the default).
1283
 *
Matthias Clasen's avatar
Matthias Clasen committed
1284
 *   `no-undefined`: Avoid tests for undefined behaviour
1285
 *
Matthias Clasen's avatar
Matthias Clasen committed
1286
 * - `--debug-log`: Debug test logging output.
1287
 *
1288
1289
1290
1291
1292
1293
 * Since 2.58, if tests are compiled with `G_DISABLE_ASSERT` defined,
 * g_test_init() will print an error and exit. This is to prevent no-op tests
 * from being executed, as g_assert() is commonly (erroneously) used in unit
 * tests, and is a no-op when compiled with `G_DISABLE_ASSERT`. Ensure your
 * tests are compiled without `G_DISABLE_ASSERT` defined.
 *
1294
 * Since: 2.16
1295
 */
Tim Janik's avatar