Add g_assert_true, g_assert_false and g_assert_null
[platform/upstream/glib.git] / glib / gtestutils.c
1 /* GLib testing utilities
2  * Copyright (C) 2007 Imendio AB
3  * Authors: Tim Janik, Sven Herzberg
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 #include "config.h"
22
23 #include "gtestutils.h"
24 #include "gmessages-private.h"
25 #include "gfileutils.h"
26
27 #include <sys/types.h>
28 #ifdef G_OS_UNIX
29 #include <sys/wait.h>
30 #include <sys/time.h>
31 #include <fcntl.h>
32 #include <glib/gstdio.h>
33 #endif
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #ifdef HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40 #ifdef HAVE_SYS_RESOURCE_H
41 #include <sys/resource.h>
42 #endif
43 #ifdef G_OS_WIN32
44 #include <io.h>
45 #include <windows.h>
46 #endif
47 #include <errno.h>
48 #include <signal.h>
49 #ifdef HAVE_SYS_SELECT_H
50 #include <sys/select.h>
51 #endif /* HAVE_SYS_SELECT_H */
52
53 #include "gmain.h"
54 #include "gpattern.h"
55 #include "grand.h"
56 #include "gstrfuncs.h"
57 #include "gtimer.h"
58 #include "gslice.h"
59 #include "gspawn.h"
60 #include "glib-private.h"
61 #include "gmessages-private.h"
62
63
64 /**
65  * SECTION:testing
66  * @title: Testing
67  * @short_description: a test framework
68  * @see_also: <link linkend="gtester">gtester</link>,
69  *            <link linkend="gtester-report">gtester-report</link>
70  *
71  * GLib provides a framework for writing and maintaining unit tests
72  * in parallel to the code they are testing. The API is designed according
73  * to established concepts found in the other test frameworks (JUnit, NUnit,
74  * RUnit), which in turn is based on smalltalk unit testing concepts.
75  *
76  * <variablelist>
77  *   <varlistentry>
78  *     <term>Test case</term>
79  *     <listitem>Tests (test methods) are grouped together with their
80  *       fixture into test cases.</listitem>
81  *   </varlistentry>
82  *   <varlistentry>
83  *     <term>Fixture</term>
84  *     <listitem>A test fixture consists of fixture data and setup and
85  *       teardown methods to establish the environment for the test
86  *       functions. We use fresh fixtures, i.e. fixtures are newly set
87  *       up and torn down around each test invocation to avoid dependencies
88  *       between tests.</listitem>
89  *   </varlistentry>
90  *   <varlistentry>
91  *     <term>Test suite</term>
92  *     <listitem>Test cases can be grouped into test suites, to allow
93  *       subsets of the available tests to be run. Test suites can be
94  *       grouped into other test suites as well.</listitem>
95  *   </varlistentry>
96  * </variablelist>
97  * The API is designed to handle creation and registration of test suites
98  * and test cases implicitly. A simple call like
99  * |[
100  *   g_test_add_func ("/misc/assertions", test_assertions);
101  * ]|
102  * creates a test suite called "misc" with a single test case named
103  * "assertions", which consists of running the test_assertions function.
104  *
105  * In addition to the traditional g_assert(), the test framework provides
106  * an extended set of assertions for string and numerical comparisons:
107  * g_assert_cmpfloat(), g_assert_cmpint(), g_assert_cmpuint(),
108  * g_assert_cmphex(), g_assert_cmpstr(). The advantage of these variants
109  * over plain g_assert() is that the assertion messages can be more
110  * elaborate, and include the values of the compared entities.
111  *
112  * GLib ships with two utilities called gtester and gtester-report to
113  * facilitate running tests and producing nicely formatted test reports.
114  */
115
116 /**
117  * g_test_initialized:
118  *
119  * Returns %TRUE if g_test_init() has been called.
120  *
121  * Returns: %TRUE if g_test_init() has been called.
122  *
123  * Since: 2.36
124  */
125
126 /**
127  * g_test_quick:
128  *
129  * Returns %TRUE if tests are run in quick mode.
130  * Exactly one of g_test_quick() and g_test_slow() is active in any run;
131  * there is no "medium speed".
132  *
133  * Returns: %TRUE if in quick mode
134  */
135
136 /**
137  * g_test_slow:
138  *
139  * Returns %TRUE if tests are run in slow mode.
140  * Exactly one of g_test_quick() and g_test_slow() is active in any run;
141  * there is no "medium speed".
142  *
143  * Returns: the opposite of g_test_quick()
144  */
145
146 /**
147  * g_test_thorough:
148  *
149  * Returns %TRUE if tests are run in thorough mode, equivalent to
150  * g_test_slow().
151  *
152  * Returns: the same thing as g_test_slow()
153  */
154
155 /**
156  * g_test_perf:
157  *
158  * Returns %TRUE if tests are run in performance mode.
159  *
160  * Returns: %TRUE if in performance mode
161  */
162
163 /**
164  * g_test_undefined:
165  *
166  * Returns %TRUE if tests may provoke assertions and other formally-undefined
167  * behaviour, to verify that appropriate warnings are given. It might, in some
168  * cases, be useful to turn this off if running tests under valgrind.
169  *
170  * Returns: %TRUE if tests may provoke programming errors
171  */
172
173 /**
174  * g_test_verbose:
175  *
176  * Returns %TRUE if tests are run in verbose mode.
177  * The default is neither g_test_verbose() nor g_test_quiet().
178  *
179  * Returns: %TRUE if in verbose mode
180  */
181
182 /**
183  * g_test_quiet:
184  *
185  * Returns %TRUE if tests are run in quiet mode.
186  * The default is neither g_test_verbose() nor g_test_quiet().
187  *
188  * Returns: %TRUE if in quiet mode
189  */
190
191 /**
192  * g_test_queue_unref:
193  * @gobject: the object to unref
194  *
195  * Enqueue an object to be released with g_object_unref() during
196  * the next teardown phase. This is equivalent to calling
197  * g_test_queue_destroy() with a destroy callback of g_object_unref().
198  *
199  * Since: 2.16
200  */
201
202 /**
203  * GTestTrapFlags:
204  * @G_TEST_TRAP_SILENCE_STDOUT: Redirect stdout of the test child to
205  *     <filename>/dev/null</filename> so it cannot be observed on the
206  *     console during test runs. The actual output is still captured
207  *     though to allow later tests with g_test_trap_assert_stdout().
208  * @G_TEST_TRAP_SILENCE_STDERR: Redirect stderr of the test child to
209  *     <filename>/dev/null</filename> so it cannot be observed on the
210  *     console during test runs. The actual output is still captured
211  *     though to allow later tests with g_test_trap_assert_stderr().
212  * @G_TEST_TRAP_INHERIT_STDIN: If this flag is given, stdin of the
213  *     child process is shared with stdin of its parent process.
214  *     It is redirected to <filename>/dev/null</filename> otherwise.
215  *
216  * Test traps are guards around forked tests.
217  * These flags determine what traps to set.
218  *
219  * Deprecated: #GTestTrapFlags is used only with g_test_trap_fork(),
220  * which is deprecated. g_test_trap_subprocess() uses
221  * #GTestTrapSubprocessFlags.
222  */
223
224 /**
225  * GTestSubprocessFlags:
226  * @G_TEST_SUBPROCESS_INHERIT_STDIN: If this flag is given, the child
227  *     process will inherit the parent's stdin. Otherwise, the child's
228  *     stdin is redirected to <filename>/dev/null</filename>.
229  * @G_TEST_SUBPROCESS_INHERIT_STDOUT: If this flag is given, the child
230  *     process will inherit the parent's stdout. Otherwise, the child's
231  *     stdout will not be visible, but it will be captured to allow
232  *     later tests with g_test_trap_assert_stdout().
233  * @G_TEST_SUBPROCESS_INHERIT_STDERR: If this flag is given, the child
234  *     process will inherit the parent's stderr. Otherwise, the child's
235  *     stderr will not be visible, but it will be captured to allow
236  *     later tests with g_test_trap_assert_stderr().
237  *
238  * Flags to pass to g_test_trap_subprocess() to control input and output.
239  *
240  * Note that in contrast with g_test_trap_fork(), the default is to
241  * not show stdout and stderr.
242  */
243
244 /**
245  * g_test_trap_assert_passed:
246  *
247  * Assert that the last test subprocess passed.
248  * See g_test_trap_subprocess().
249  *
250  * Since: 2.16
251  */
252
253 /**
254  * g_test_trap_assert_failed:
255  *
256  * Assert that the last test subprocess failed.
257  * See g_test_trap_subprocess().
258  *
259  * This is sometimes used to test situations that are formally considered to
260  * be undefined behaviour, like inputs that fail a g_return_if_fail()
261  * check. In these situations you should skip the entire test, including the
262  * call to g_test_trap_subprocess(), unless g_test_undefined() returns %TRUE
263  * to indicate that undefined behaviour may be tested.
264  *
265  * Since: 2.16
266  */
267
268 /**
269  * g_test_trap_assert_stdout:
270  * @soutpattern: a glob-style
271  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
272  *
273  * Assert that the stdout output of the last test subprocess matches
274  * @soutpattern. See g_test_trap_subprocess().
275  *
276  * Since: 2.16
277  */
278
279 /**
280  * g_test_trap_assert_stdout_unmatched:
281  * @soutpattern: a glob-style
282  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
283  *
284  * Assert that the stdout output of the last test subprocess
285  * does not match @soutpattern. See g_test_trap_subprocess().
286  *
287  * Since: 2.16
288  */
289
290 /**
291  * g_test_trap_assert_stderr:
292  * @serrpattern: a glob-style
293  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
294  *
295  * Assert that the stderr output of the last test subprocess
296  * matches @serrpattern. See  g_test_trap_subprocess().
297  *
298  * This is sometimes used to test situations that are formally
299  * considered to be undefined behaviour, like code that hits a
300  * g_assert() or g_error(). In these situations you should skip the
301  * entire test, including the call to g_test_trap_subprocess(), unless
302  * g_test_undefined() returns %TRUE to indicate that undefined
303  * behaviour may be tested.
304  *
305  * Since: 2.16
306  */
307
308 /**
309  * g_test_trap_assert_stderr_unmatched:
310  * @serrpattern: a glob-style
311  *     <link linkend="glib-Glob-style-pattern-matching">pattern</link>
312  *
313  * Assert that the stderr output of the last test subprocess
314  * does not match @serrpattern. See g_test_trap_subprocess().
315  *
316  * Since: 2.16
317  */
318
319 /**
320  * g_test_rand_bit:
321  *
322  * Get a reproducible random bit (0 or 1), see g_test_rand_int()
323  * for details on test case random numbers.
324  *
325  * Since: 2.16
326  */
327
328 /**
329  * g_assert:
330  * @expr: the expression to check
331  *
332  * Debugging macro to terminate the application if the assertion
333  * fails. If the assertion fails (i.e. the expression is not true),
334  * an error message is logged and the application is terminated.
335  *
336  * The macro can be turned off in final releases of code by defining
337  * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
338  */
339
340 /**
341  * g_assert_not_reached:
342  *
343  * Debugging macro to terminate the application if it is ever
344  * reached. If it is reached, an error message is logged and the
345  * application is terminated.
346  *
347  * The macro can be turned off in final releases of code by defining
348  * <envar>G_DISABLE_ASSERT</envar> when compiling the application.
349  */
350
351 /**
352  * g_assert_true:
353  * @expr: the expression to check
354  *
355  * Debugging macro to check that an expression is true.
356  *
357  * Since: 2.38
358  */
359
360 /**
361  * g_assert_false:
362  * @expr: the expression to check
363  *
364  * Debugging macro to check an expression is false.
365  *
366  * Since: 2.38
367  */
368
369 /**
370  * g_assert_null:
371  * @expr: the expression to check
372  *
373  * Debugging macro to check an expression is %NULL.
374  *
375  * Since: 2.38
376  */
377
378 /**
379  * g_assert_cmpstr:
380  * @s1: a string (may be %NULL)
381  * @cmp: The comparison operator to use.
382  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
383  * @s2: another string (may be %NULL)
384  *
385  * Debugging macro to terminate the application with a warning
386  * message if a string comparison fails. The strings are compared
387  * using g_strcmp0().
388  *
389  * The effect of <literal>g_assert_cmpstr (s1, op, s2)</literal> is
390  * the same as <literal>g_assert (g_strcmp0 (s1, s2) op 0)</literal>.
391  * The advantage of this macro is that it can produce a message that
392  * includes the actual values of @s1 and @s2.
393  *
394  * |[
395  *   g_assert_cmpstr (mystring, ==, "fubar");
396  * ]|
397  *
398  * Since: 2.16
399  */
400
401 /**
402  * g_assert_cmpint:
403  * @n1: an integer
404  * @cmp: The comparison operator to use.
405  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
406  * @n2: another integer
407  *
408  * Debugging macro to terminate the application with a warning
409  * message if an integer comparison fails.
410  *
411  * The effect of <literal>g_assert_cmpint (n1, op, n2)</literal> is
412  * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
413  * of this macro is that it can produce a message that includes the
414  * actual values of @n1 and @n2.
415  *
416  * Since: 2.16
417  */
418
419 /**
420  * g_assert_cmpuint:
421  * @n1: an unsigned integer
422  * @cmp: The comparison operator to use.
423  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
424  * @n2: another unsigned integer
425  *
426  * Debugging macro to terminate the application with a warning
427  * message if an unsigned integer comparison fails.
428  *
429  * The effect of <literal>g_assert_cmpuint (n1, op, n2)</literal> is
430  * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
431  * of this macro is that it can produce a message that includes the
432  * actual values of @n1 and @n2.
433  *
434  * Since: 2.16
435  */
436
437 /**
438  * g_assert_cmphex:
439  * @n1: an unsigned integer
440  * @cmp: The comparison operator to use.
441  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
442  * @n2: another unsigned integer
443  *
444  * Debugging macro to terminate the application with a warning
445  * message if an unsigned integer comparison fails.
446  *
447  * This is a variant of g_assert_cmpuint() that displays the numbers
448  * in hexadecimal notation in the message.
449  *
450  * Since: 2.16
451  */
452
453 /**
454  * g_assert_cmpfloat:
455  * @n1: an floating point number
456  * @cmp: The comparison operator to use.
457  *     One of ==, !=, &lt;, &gt;, &lt;=, &gt;=.
458  * @n2: another floating point number
459  *
460  * Debugging macro to terminate the application with a warning
461  * message if a floating point number comparison fails.
462  *
463  * The effect of <literal>g_assert_cmpfloat (n1, op, n2)</literal> is
464  * the same as <literal>g_assert (n1 op n2)</literal>. The advantage
465  * of this macro is that it can produce a message that includes the
466  * actual values of @n1 and @n2.
467  *
468  * Since: 2.16
469  */
470
471 /**
472  * g_assert_no_error:
473  * @err: a #GError, possibly %NULL
474  *
475  * Debugging macro to terminate the application with a warning
476  * message if a method has returned a #GError.
477  *
478  * The effect of <literal>g_assert_no_error (err)</literal> is
479  * the same as <literal>g_assert (err == NULL)</literal>. The advantage
480  * of this macro is that it can produce a message that includes
481  * the error message and code.
482  *
483  * Since: 2.20
484  */
485
486 /**
487  * g_assert_error:
488  * @err: a #GError, possibly %NULL
489  * @dom: the expected error domain (a #GQuark)
490  * @c: the expected error code
491  *
492  * Debugging macro to terminate the application with a warning
493  * message if a method has not returned the correct #GError.
494  *
495  * The effect of <literal>g_assert_error (err, dom, c)</literal> is
496  * the same as <literal>g_assert (err != NULL &amp;&amp; err->domain
497  * == dom &amp;&amp; err->code == c)</literal>. The advantage of this
498  * macro is that it can produce a message that includes the incorrect
499  * error message and code.
500  *
501  * This can only be used to test for a specific error. If you want to
502  * test that @err is set, but don't care what it's set to, just use
503  * <literal>g_assert (err != NULL)</literal>
504  *
505  * Since: 2.20
506  */
507
508 /**
509  * GTestCase:
510  *
511  * An opaque structure representing a test case.
512  */
513
514 /**
515  * GTestSuite:
516  *
517  * An opaque structure representing a test suite.
518  */
519
520
521 /* Global variable for storing assertion messages; this is the counterpart to
522  * glibc's (private) __abort_msg variable, and allows developers and crash
523  * analysis systems like Apport and ABRT to fish out assertion messages from
524  * core dumps, instead of having to catch them on screen output.
525  */
526 GLIB_VAR char *__glib_assert_msg;
527 char *__glib_assert_msg = NULL;
528
529 /* --- constants --- */
530 #define G_TEST_STATUS_TIMED_OUT 1024
531
532 /* --- structures --- */
533 struct GTestCase
534 {
535   gchar  *name;
536   guint   fixture_size;
537   void   (*fixture_setup)    (void*, gconstpointer);
538   void   (*fixture_test)     (void*, gconstpointer);
539   void   (*fixture_teardown) (void*, gconstpointer);
540   gpointer test_data;
541 };
542 struct GTestSuite
543 {
544   gchar  *name;
545   GSList *suites;
546   GSList *cases;
547 };
548 typedef struct DestroyEntry DestroyEntry;
549 struct DestroyEntry
550 {
551   DestroyEntry *next;
552   GDestroyNotify destroy_func;
553   gpointer       destroy_data;
554 };
555
556 /* --- prototypes --- */
557 static void     test_run_seed                   (const gchar *rseed);
558 static void     test_trap_clear                 (void);
559 static guint8*  g_test_log_dump                 (GTestLogMsg *msg,
560                                                  guint       *len);
561 static void     gtest_default_log_handler       (const gchar    *log_domain,
562                                                  GLogLevelFlags  log_level,
563                                                  const gchar    *message,
564                                                  gpointer        unused_data);
565
566
567 typedef enum {
568   G_TEST_RUN_SUCCESS,
569   G_TEST_RUN_SKIPPED,
570   G_TEST_RUN_FAILURE,
571   G_TEST_RUN_INCOMPLETE
572 } GTestResult;
573
574 /* --- variables --- */
575 static int         test_log_fd = -1;
576 static gboolean    test_mode_fatal = TRUE;
577 static gboolean    g_test_run_once = TRUE;
578 static gboolean    test_run_list = FALSE;
579 static gchar      *test_run_seedstr = NULL;
580 static GRand      *test_run_rand = NULL;
581 static gchar      *test_run_name = "";
582 static GSList    **test_filename_free_list;
583 static guint       test_run_forks = 0;
584 static guint       test_run_count = 0;
585 static GTestResult test_run_success = G_TEST_RUN_FAILURE;
586 static gchar      *test_run_msg = NULL;
587 static guint       test_skip_count = 0;
588 static GTimer     *test_user_timer = NULL;
589 static double      test_user_stamp = 0;
590 static GSList     *test_paths = NULL;
591 static GSList     *test_paths_skipped = NULL;
592 static GTestSuite *test_suite_root = NULL;
593 static int         test_trap_last_status = 0;
594 static GPid        test_trap_last_pid = 0;
595 static char       *test_trap_last_subprocess = NULL;
596 static char       *test_trap_last_stdout = NULL;
597 static char       *test_trap_last_stderr = NULL;
598 static char       *test_uri_base = NULL;
599 static gboolean    test_debug_log = FALSE;
600 static gboolean    test_tap_log = FALSE;
601 static DestroyEntry *test_destroy_queue = NULL;
602 static char       *test_argv0 = NULL;
603 static char       *test_argv0_dirname;
604 static const char *test_disted_files_dir;
605 static const char *test_built_files_dir;
606 static char       *test_initial_cwd = NULL;
607 static gboolean    test_in_subprocess = FALSE;
608 static GTestConfig mutable_test_config_vars = {
609   FALSE,        /* test_initialized */
610   TRUE,         /* test_quick */
611   FALSE,        /* test_perf */
612   FALSE,        /* test_verbose */
613   FALSE,        /* test_quiet */
614   TRUE,         /* test_undefined */
615 };
616 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
617
618 /* --- functions --- */
619 const char*
620 g_test_log_type_name (GTestLogType log_type)
621 {
622   switch (log_type)
623     {
624     case G_TEST_LOG_NONE:               return "none";
625     case G_TEST_LOG_ERROR:              return "error";
626     case G_TEST_LOG_START_BINARY:       return "binary";
627     case G_TEST_LOG_LIST_CASE:          return "list";
628     case G_TEST_LOG_SKIP_CASE:          return "skip";
629     case G_TEST_LOG_START_CASE:         return "start";
630     case G_TEST_LOG_STOP_CASE:          return "stop";
631     case G_TEST_LOG_MIN_RESULT:         return "minperf";
632     case G_TEST_LOG_MAX_RESULT:         return "maxperf";
633     case G_TEST_LOG_MESSAGE:            return "message";
634     case G_TEST_LOG_START_SUITE:        return "start suite";
635     case G_TEST_LOG_STOP_SUITE:         return "stop suite";
636     }
637   return "???";
638 }
639
640 static void
641 g_test_log_send (guint         n_bytes,
642                  const guint8 *buffer)
643 {
644   if (test_log_fd >= 0)
645     {
646       int r;
647       do
648         r = write (test_log_fd, buffer, n_bytes);
649       while (r < 0 && errno == EINTR);
650     }
651   if (test_debug_log)
652     {
653       GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
654       GTestLogMsg *msg;
655       guint ui;
656       g_test_log_buffer_push (lbuffer, n_bytes, buffer);
657       msg = g_test_log_buffer_pop (lbuffer);
658       g_warn_if_fail (msg != NULL);
659       g_warn_if_fail (lbuffer->data->len == 0);
660       g_test_log_buffer_free (lbuffer);
661       /* print message */
662       g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
663       for (ui = 0; ui < msg->n_strings; ui++)
664         g_printerr (":{%s}", msg->strings[ui]);
665       if (msg->n_nums)
666         {
667           g_printerr (":(");
668           for (ui = 0; ui < msg->n_nums; ui++)
669             {
670               if ((long double) (long) msg->nums[ui] == msg->nums[ui])
671                 g_printerr ("%s%ld", ui ? ";" : "", (long) msg->nums[ui]);
672               else
673                 g_printerr ("%s%.16g", ui ? ";" : "", (double) msg->nums[ui]);
674             }
675           g_printerr (")");
676         }
677       g_printerr (":LOG*}\n");
678       g_test_log_msg_free (msg);
679     }
680 }
681
682 static void
683 g_test_log (GTestLogType lbit,
684             const gchar *string1,
685             const gchar *string2,
686             guint        n_args,
687             long double *largs)
688 {
689   gboolean fail;
690   GTestLogMsg msg;
691   gchar *astrings[3] = { NULL, NULL, NULL };
692   guint8 *dbuffer;
693   guint32 dbufferlen;
694
695   switch (lbit)
696     {
697     case G_TEST_LOG_START_BINARY:
698       if (test_tap_log)
699         g_print ("# random seed: %s\n", string2);
700       else if (g_test_verbose())
701         g_print ("GTest: random seed: %s\n", string2);
702       break;
703     case G_TEST_LOG_START_SUITE:
704       if (test_tap_log)
705         {
706           if (string1[0] != 0)
707             g_print ("# Start of %s tests\n", string1);
708         }
709       break;
710     case G_TEST_LOG_STOP_SUITE:
711       if (test_tap_log)
712         {
713           if (string1[0] != 0)
714             g_print ("# End of %s tests\n", string1);
715           else
716             g_print ("1..%d\n", test_run_count);
717         }
718       break;
719     case G_TEST_LOG_STOP_CASE:
720       fail = largs[0] != G_TEST_RUN_SUCCESS && largs[0] != G_TEST_RUN_SKIPPED;
721       if (test_tap_log)
722         {
723           g_print ("%s %d %s", fail ? "not ok" : "ok", test_run_count, string1);
724           if (largs[0] == G_TEST_RUN_INCOMPLETE)
725             g_print (" # TODO %s\n", string2 ? string2 : "");
726           else if (largs[0] == G_TEST_RUN_SKIPPED)
727             g_print (" # SKIP %s\n", string2 ? string2 : "");
728           else
729             g_print ("\n");
730         }
731       else if (g_test_verbose())
732         g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
733       else if (!g_test_quiet())
734         g_print ("%s\n", fail ? "FAIL" : "OK");
735       if (fail && test_mode_fatal)
736         {
737           if (test_tap_log)
738             g_print ("Bail out!\n");
739           abort();
740         }
741       break;
742     case G_TEST_LOG_MIN_RESULT:
743       if (test_tap_log)
744         g_print ("# min perf: %s\n", string1);
745       else if (g_test_verbose())
746         g_print ("(MINPERF:%s)\n", string1);
747       break;
748     case G_TEST_LOG_MAX_RESULT:
749       if (test_tap_log)
750         g_print ("# max perf: %s\n", string1);
751       else if (g_test_verbose())
752         g_print ("(MAXPERF:%s)\n", string1);
753       break;
754     case G_TEST_LOG_MESSAGE:
755     case G_TEST_LOG_ERROR:
756       if (test_tap_log)
757         g_print ("# %s\n", string1);
758       else if (g_test_verbose())
759         g_print ("(MSG: %s)\n", string1);
760       break;
761     default: ;
762     }
763
764   msg.log_type = lbit;
765   msg.n_strings = (string1 != NULL) + (string1 && string2);
766   msg.strings = astrings;
767   astrings[0] = (gchar*) string1;
768   astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
769   msg.n_nums = n_args;
770   msg.nums = largs;
771   dbuffer = g_test_log_dump (&msg, &dbufferlen);
772   g_test_log_send (dbufferlen, dbuffer);
773   g_free (dbuffer);
774
775   switch (lbit)
776     {
777     case G_TEST_LOG_START_CASE:
778       if (test_tap_log)
779         ;
780       else if (g_test_verbose())
781         g_print ("GTest: run: %s\n", string1);
782       else if (!g_test_quiet())
783         g_print ("%s: ", string1);
784       break;
785     default: ;
786     }
787 }
788
789 /* We intentionally parse the command line without GOptionContext
790  * because otherwise you would never be able to test it.
791  */
792 static void
793 parse_args (gint    *argc_p,
794             gchar ***argv_p)
795 {
796   guint argc = *argc_p;
797   gchar **argv = *argv_p;
798   guint i, e;
799
800   test_argv0 = argv[0];
801   test_initial_cwd = g_get_current_dir ();
802
803   /* parse known args */
804   for (i = 1; i < argc; i++)
805     {
806       if (strcmp (argv[i], "--g-fatal-warnings") == 0)
807         {
808           GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
809           fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
810           g_log_set_always_fatal (fatal_mask);
811           argv[i] = NULL;
812         }
813       else if (strcmp (argv[i], "--keep-going") == 0 ||
814                strcmp (argv[i], "-k") == 0)
815         {
816           test_mode_fatal = FALSE;
817           argv[i] = NULL;
818         }
819       else if (strcmp (argv[i], "--debug-log") == 0)
820         {
821           test_debug_log = TRUE;
822           argv[i] = NULL;
823         }
824       else if (strcmp (argv[i], "--tap") == 0)
825         {
826           test_tap_log = TRUE;
827           argv[i] = NULL;
828         }
829       else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
830         {
831           gchar *equal = argv[i] + 12;
832           if (*equal == '=')
833             test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
834           else if (i + 1 < argc)
835             {
836               argv[i++] = NULL;
837               test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
838             }
839           argv[i] = NULL;
840         }
841       else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
842         {
843           gchar *equal = argv[i] + 16;
844           if (*equal == '=')
845             test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
846           else if (i + 1 < argc)
847             {
848               argv[i++] = NULL;
849               test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
850             }
851           argv[i] = NULL;
852         }
853       else if (strcmp ("--GTestSubprocess", argv[i]) == 0)
854         {
855           test_in_subprocess = TRUE;
856           /* We typically expect these child processes to crash, and some
857            * tests spawn a *lot* of them.  Avoid spamming system crash
858            * collection programs such as systemd-coredump and abrt.
859            */
860 #ifdef HAVE_SYS_RESOURCE_H
861           {
862             struct rlimit limit = { 0, 0 };
863             (void) setrlimit (RLIMIT_CORE, &limit);
864           }
865 #endif
866           _g_log_set_exit_on_fatal ();
867           argv[i] = NULL;
868         }
869       else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
870         {
871           gchar *equal = argv[i] + 2;
872           if (*equal == '=')
873             test_paths = g_slist_prepend (test_paths, equal + 1);
874           else if (i + 1 < argc)
875             {
876               argv[i++] = NULL;
877               test_paths = g_slist_prepend (test_paths, argv[i]);
878             }
879           argv[i] = NULL;
880         }
881       else if (strcmp ("-s", argv[i]) == 0 || strncmp ("-s=", argv[i], 3) == 0)
882         {
883           gchar *equal = argv[i] + 2;
884           if (*equal == '=')
885             test_paths_skipped = g_slist_prepend (test_paths_skipped, equal + 1);
886           else if (i + 1 < argc)
887             {
888               argv[i++] = NULL;
889               test_paths_skipped = g_slist_prepend (test_paths_skipped, argv[i]);
890             }
891           argv[i] = NULL;
892         }
893       else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
894         {
895           gchar *equal = argv[i] + 2;
896           const gchar *mode = "";
897           if (*equal == '=')
898             mode = equal + 1;
899           else if (i + 1 < argc)
900             {
901               argv[i++] = NULL;
902               mode = argv[i];
903             }
904           if (strcmp (mode, "perf") == 0)
905             mutable_test_config_vars.test_perf = TRUE;
906           else if (strcmp (mode, "slow") == 0)
907             mutable_test_config_vars.test_quick = FALSE;
908           else if (strcmp (mode, "thorough") == 0)
909             mutable_test_config_vars.test_quick = FALSE;
910           else if (strcmp (mode, "quick") == 0)
911             {
912               mutable_test_config_vars.test_quick = TRUE;
913               mutable_test_config_vars.test_perf = FALSE;
914             }
915           else if (strcmp (mode, "undefined") == 0)
916             mutable_test_config_vars.test_undefined = TRUE;
917           else if (strcmp (mode, "no-undefined") == 0)
918             mutable_test_config_vars.test_undefined = FALSE;
919           else
920             g_error ("unknown test mode: -m %s", mode);
921           argv[i] = NULL;
922         }
923       else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
924         {
925           mutable_test_config_vars.test_quiet = TRUE;
926           mutable_test_config_vars.test_verbose = FALSE;
927           argv[i] = NULL;
928         }
929       else if (strcmp ("--verbose", argv[i]) == 0)
930         {
931           mutable_test_config_vars.test_quiet = FALSE;
932           mutable_test_config_vars.test_verbose = TRUE;
933           argv[i] = NULL;
934         }
935       else if (strcmp ("-l", argv[i]) == 0)
936         {
937           test_run_list = TRUE;
938           argv[i] = NULL;
939         }
940       else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
941         {
942           gchar *equal = argv[i] + 6;
943           if (*equal == '=')
944             test_run_seedstr = equal + 1;
945           else if (i + 1 < argc)
946             {
947               argv[i++] = NULL;
948               test_run_seedstr = argv[i];
949             }
950           argv[i] = NULL;
951         }
952       else if (strcmp ("-?", argv[i]) == 0 ||
953                strcmp ("-h", argv[i]) == 0 ||
954                strcmp ("--help", argv[i]) == 0)
955         {
956           printf ("Usage:\n"
957                   "  %s [OPTION...]\n\n"
958                   "Help Options:\n"
959                   "  -h, --help                     Show help options\n\n"
960                   "Test Options:\n"
961                   "  --g-fatal-warnings             Make all warnings fatal\n"
962                   "  -l                             List test cases available in a test executable\n"
963                   "  -m {perf|slow|thorough|quick}  Execute tests according to mode\n"
964                   "  -m {undefined|no-undefined}    Execute tests according to mode\n"
965                   "  -p TESTPATH                    Only start test cases matching TESTPATH\n"
966                   "  -s TESTPATH                    Skip all tests matching TESTPATH\n"
967                   "  -seed=SEEDSTRING               Start tests with random seed SEEDSTRING\n"
968                   "  --debug-log                    debug test logging output\n"
969                   "  -q, --quiet                    Run tests quietly\n"
970                   "  --verbose                      Run tests verbosely\n",
971                   argv[0]);
972           exit (0);
973         }
974     }
975   /* collapse argv */
976   e = 1;
977   for (i = 1; i < argc; i++)
978     if (argv[i])
979       {
980         argv[e++] = argv[i];
981         if (i >= e)
982           argv[i] = NULL;
983       }
984   *argc_p = e;
985 }
986
987 /**
988  * g_test_init:
989  * @argc: Address of the @argc parameter of the main() function.
990  *        Changed if any arguments were handled.
991  * @argv: Address of the @argv parameter of main().
992  *        Any parameters understood by g_test_init() stripped before return.
993  * @...: Reserved for future extension. Currently, you must pass %NULL.
994  *
995  * Initialize the GLib testing framework, e.g. by seeding the
996  * test random number generator, the name for g_get_prgname()
997  * and parsing test related command line args.
998  * So far, the following arguments are understood:
999  * <variablelist>
1000  *   <varlistentry>
1001  *     <term><option>-l</option></term>
1002  *     <listitem><para>
1003  *       List test cases available in a test executable.
1004  *     </para></listitem>
1005  *   </varlistentry>
1006  *   <varlistentry>
1007  *     <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
1008  *     <listitem><para>
1009  *       Provide a random seed to reproduce test runs using random numbers.
1010  *     </para></listitem>
1011  *     </varlistentry>
1012  *     <varlistentry>
1013  *       <term><option>--verbose</option></term>
1014  *       <listitem><para>Run tests verbosely.</para></listitem>
1015  *     </varlistentry>
1016  *     <varlistentry>
1017  *       <term><option>-q</option>, <option>--quiet</option></term>
1018  *       <listitem><para>Run tests quietly.</para></listitem>
1019  *     </varlistentry>
1020  *     <varlistentry>
1021  *       <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
1022  *       <listitem><para>
1023  *         Execute all tests matching <replaceable>TESTPATH</replaceable>.
1024  *         This can also be used to force a test to run that would otherwise
1025  *         be skipped (ie, a test whose name contains "/subprocess").
1026  *       </para></listitem>
1027  *     </varlistentry>
1028  *     <varlistentry>
1029  *       <term><option>-m {perf|slow|thorough|quick|undefined|no-undefined}</option></term>
1030  *       <listitem><para>
1031  *         Execute tests according to these test modes:
1032  *         <variablelist>
1033  *           <varlistentry>
1034  *             <term>perf</term>
1035  *             <listitem><para>
1036  *               Performance tests, may take long and report results.
1037  *             </para></listitem>
1038  *           </varlistentry>
1039  *           <varlistentry>
1040  *             <term>slow, thorough</term>
1041  *             <listitem><para>
1042  *               Slow and thorough tests, may take quite long and
1043  *               maximize coverage.
1044  *             </para></listitem>
1045  *           </varlistentry>
1046  *           <varlistentry>
1047  *             <term>quick</term>
1048  *             <listitem><para>
1049  *               Quick tests, should run really quickly and give good coverage.
1050  *             </para></listitem>
1051  *           </varlistentry>
1052  *           <varlistentry>
1053  *             <term>undefined</term>
1054  *             <listitem><para>
1055  *               Tests for undefined behaviour, may provoke programming errors
1056  *               under g_test_trap_subprocess() or g_test_expect_messages() to check
1057  *               that appropriate assertions or warnings are given
1058  *             </para></listitem>
1059  *           </varlistentry>
1060  *           <varlistentry>
1061  *             <term>no-undefined</term>
1062  *             <listitem><para>
1063  *               Avoid tests for undefined behaviour
1064  *             </para></listitem>
1065  *           </varlistentry>
1066  *         </variablelist>
1067  *       </para></listitem>
1068  *     </varlistentry>
1069  *     <varlistentry>
1070  *       <term><option>--debug-log</option></term>
1071  *       <listitem><para>Debug test logging output.</para></listitem>
1072  *     </varlistentry>
1073  *  </variablelist>
1074  *
1075  * Since: 2.16
1076  */
1077 void
1078 g_test_init (int    *argc,
1079              char ***argv,
1080              ...)
1081 {
1082   static char seedstr[4 + 4 * 8 + 1];
1083   va_list args;
1084   gpointer vararg1;
1085   /* make warnings and criticals fatal for all test programs */
1086   GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
1087   fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
1088   g_log_set_always_fatal (fatal_mask);
1089   /* check caller args */
1090   g_return_if_fail (argc != NULL);
1091   g_return_if_fail (argv != NULL);
1092   g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
1093   mutable_test_config_vars.test_initialized = TRUE;
1094
1095   va_start (args, argv);
1096   vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
1097   va_end (args);
1098   g_return_if_fail (vararg1 == NULL);
1099
1100   /* setup random seed string */
1101   g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
1102   test_run_seedstr = seedstr;
1103
1104   /* parse args, sets up mode, changes seed, etc. */
1105   parse_args (argc, argv);
1106   if (!g_get_prgname())
1107     g_set_prgname ((*argv)[0]);
1108
1109   /* verify GRand reliability, needed for reliable seeds */
1110   if (1)
1111     {
1112       GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
1113       guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
1114       /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
1115       if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
1116         g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
1117       g_rand_free (rg);
1118     }
1119
1120   /* check rand seed */
1121   test_run_seed (test_run_seedstr);
1122
1123   /* report program start */
1124   g_log_set_default_handler (gtest_default_log_handler, NULL);
1125   g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
1126
1127   test_argv0_dirname = g_path_get_dirname (test_argv0);
1128
1129   /* Make sure we get the real dirname that the test was run from */
1130   if (g_str_has_suffix (test_argv0_dirname, "/.libs"))
1131     {
1132       gchar *tmp;
1133       tmp = g_path_get_dirname (test_argv0_dirname);
1134       g_free (test_argv0_dirname);
1135       test_argv0_dirname = tmp;
1136     }
1137
1138   test_disted_files_dir = g_getenv ("G_TEST_SRCDIR");
1139   if (!test_disted_files_dir)
1140     test_disted_files_dir = test_argv0_dirname;
1141
1142   test_built_files_dir = g_getenv ("G_TEST_BUILDDIR");
1143   if (!test_built_files_dir)
1144     test_built_files_dir = test_argv0_dirname;
1145 }
1146
1147 static void
1148 test_run_seed (const gchar *rseed)
1149 {
1150   guint seed_failed = 0;
1151   if (test_run_rand)
1152     g_rand_free (test_run_rand);
1153   test_run_rand = NULL;
1154   while (strchr (" \t\v\r\n\f", *rseed))
1155     rseed++;
1156   if (strncmp (rseed, "R02S", 4) == 0)  /* seed for random generator 02 (GRand-2.2) */
1157     {
1158       const char *s = rseed + 4;
1159       if (strlen (s) >= 32)             /* require 4 * 8 chars */
1160         {
1161           guint32 seedarray[4];
1162           gchar *p, hexbuf[9] = { 0, };
1163           memcpy (hexbuf, s + 0, 8);
1164           seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
1165           seed_failed += p != NULL && *p != 0;
1166           memcpy (hexbuf, s + 8, 8);
1167           seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
1168           seed_failed += p != NULL && *p != 0;
1169           memcpy (hexbuf, s + 16, 8);
1170           seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
1171           seed_failed += p != NULL && *p != 0;
1172           memcpy (hexbuf, s + 24, 8);
1173           seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
1174           seed_failed += p != NULL && *p != 0;
1175           if (!seed_failed)
1176             {
1177               test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
1178               return;
1179             }
1180         }
1181     }
1182   g_error ("Unknown or invalid random seed: %s", rseed);
1183 }
1184
1185 /**
1186  * g_test_rand_int:
1187  *
1188  * Get a reproducible random integer number.
1189  *
1190  * The random numbers generated by the g_test_rand_*() family of functions
1191  * change with every new test program start, unless the --seed option is
1192  * given when starting test programs.
1193  *
1194  * For individual test cases however, the random number generator is
1195  * reseeded, to avoid dependencies between tests and to make --seed
1196  * effective for all test cases.
1197  *
1198  * Returns: a random number from the seeded random number generator.
1199  *
1200  * Since: 2.16
1201  */
1202 gint32
1203 g_test_rand_int (void)
1204 {
1205   return g_rand_int (test_run_rand);
1206 }
1207
1208 /**
1209  * g_test_rand_int_range:
1210  * @begin: the minimum value returned by this function
1211  * @end:   the smallest value not to be returned by this function
1212  *
1213  * Get a reproducible random integer number out of a specified range,
1214  * see g_test_rand_int() for details on test case random numbers.
1215  *
1216  * Returns: a number with @begin <= number < @end.
1217  * 
1218  * Since: 2.16
1219  */
1220 gint32
1221 g_test_rand_int_range (gint32          begin,
1222                        gint32          end)
1223 {
1224   return g_rand_int_range (test_run_rand, begin, end);
1225 }
1226
1227 /**
1228  * g_test_rand_double:
1229  *
1230  * Get a reproducible random floating point number,
1231  * see g_test_rand_int() for details on test case random numbers.
1232  *
1233  * Returns: a random number from the seeded random number generator.
1234  *
1235  * Since: 2.16
1236  */
1237 double
1238 g_test_rand_double (void)
1239 {
1240   return g_rand_double (test_run_rand);
1241 }
1242
1243 /**
1244  * g_test_rand_double_range:
1245  * @range_start: the minimum value returned by this function
1246  * @range_end: the minimum value not returned by this function
1247  *
1248  * Get a reproducible random floating pointer number out of a specified range,
1249  * see g_test_rand_int() for details on test case random numbers.
1250  *
1251  * Returns: a number with @range_start <= number < @range_end.
1252  *
1253  * Since: 2.16
1254  */
1255 double
1256 g_test_rand_double_range (double          range_start,
1257                           double          range_end)
1258 {
1259   return g_rand_double_range (test_run_rand, range_start, range_end);
1260 }
1261
1262 /**
1263  * g_test_timer_start:
1264  *
1265  * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
1266  * to be done. Call this function again to restart the timer.
1267  *
1268  * Since: 2.16
1269  */
1270 void
1271 g_test_timer_start (void)
1272 {
1273   if (!test_user_timer)
1274     test_user_timer = g_timer_new();
1275   test_user_stamp = 0;
1276   g_timer_start (test_user_timer);
1277 }
1278
1279 /**
1280  * g_test_timer_elapsed:
1281  *
1282  * Get the time since the last start of the timer with g_test_timer_start().
1283  *
1284  * Returns: the time since the last start of the timer, as a double
1285  *
1286  * Since: 2.16
1287  */
1288 double
1289 g_test_timer_elapsed (void)
1290 {
1291   test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
1292   return test_user_stamp;
1293 }
1294
1295 /**
1296  * g_test_timer_last:
1297  *
1298  * Report the last result of g_test_timer_elapsed().
1299  *
1300  * Returns: the last result of g_test_timer_elapsed(), as a double
1301  *
1302  * Since: 2.16
1303  */
1304 double
1305 g_test_timer_last (void)
1306 {
1307   return test_user_stamp;
1308 }
1309
1310 /**
1311  * g_test_minimized_result:
1312  * @minimized_quantity: the reported value
1313  * @format: the format string of the report message
1314  * @...: arguments to pass to the printf() function
1315  *
1316  * Report the result of a performance or measurement test.
1317  * The test should generally strive to minimize the reported
1318  * quantities (smaller values are better than larger ones),
1319  * this and @minimized_quantity can determine sorting
1320  * order for test result reports.
1321  *
1322  * Since: 2.16
1323  */
1324 void
1325 g_test_minimized_result (double          minimized_quantity,
1326                          const char     *format,
1327                          ...)
1328 {
1329   long double largs = minimized_quantity;
1330   gchar *buffer;
1331   va_list args;
1332
1333   va_start (args, format);
1334   buffer = g_strdup_vprintf (format, args);
1335   va_end (args);
1336
1337   g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
1338   g_free (buffer);
1339 }
1340
1341 /**
1342  * g_test_maximized_result:
1343  * @maximized_quantity: the reported value
1344  * @format: the format string of the report message
1345  * @...: arguments to pass to the printf() function
1346  *
1347  * Report the result of a performance or measurement test.
1348  * The test should generally strive to maximize the reported
1349  * quantities (larger values are better than smaller ones),
1350  * this and @maximized_quantity can determine sorting
1351  * order for test result reports.
1352  *
1353  * Since: 2.16
1354  */
1355 void
1356 g_test_maximized_result (double          maximized_quantity,
1357                          const char     *format,
1358                          ...)
1359 {
1360   long double largs = maximized_quantity;
1361   gchar *buffer;
1362   va_list args;
1363
1364   va_start (args, format);
1365   buffer = g_strdup_vprintf (format, args);
1366   va_end (args);
1367
1368   g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
1369   g_free (buffer);
1370 }
1371
1372 /**
1373  * g_test_message:
1374  * @format: the format string
1375  * @...:    printf-like arguments to @format
1376  *
1377  * Add a message to the test report.
1378  *
1379  * Since: 2.16
1380  */
1381 void
1382 g_test_message (const char *format,
1383                 ...)
1384 {
1385   gchar *buffer;
1386   va_list args;
1387
1388   va_start (args, format);
1389   buffer = g_strdup_vprintf (format, args);
1390   va_end (args);
1391
1392   g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
1393   g_free (buffer);
1394 }
1395
1396 /**
1397  * g_test_bug_base:
1398  * @uri_pattern: the base pattern for bug URIs
1399  *
1400  * Specify the base URI for bug reports.
1401  *
1402  * The base URI is used to construct bug report messages for
1403  * g_test_message() when g_test_bug() is called.
1404  * Calling this function outside of a test case sets the
1405  * default base URI for all test cases. Calling it from within
1406  * a test case changes the base URI for the scope of the test
1407  * case only.
1408  * Bug URIs are constructed by appending a bug specific URI
1409  * portion to @uri_pattern, or by replacing the special string
1410  * '\%s' within @uri_pattern if that is present.
1411  *
1412  * Since: 2.16
1413  */
1414 void
1415 g_test_bug_base (const char *uri_pattern)
1416 {
1417   g_free (test_uri_base);
1418   test_uri_base = g_strdup (uri_pattern);
1419 }
1420
1421 /**
1422  * g_test_bug:
1423  * @bug_uri_snippet: Bug specific bug tracker URI portion.
1424  *
1425  * This function adds a message to test reports that
1426  * associates a bug URI with a test case.
1427  * Bug URIs are constructed from a base URI set with g_test_bug_base()
1428  * and @bug_uri_snippet.
1429  *
1430  * Since: 2.16
1431  */
1432 void
1433 g_test_bug (const char *bug_uri_snippet)
1434 {
1435   char *c;
1436
1437   g_return_if_fail (test_uri_base != NULL);
1438   g_return_if_fail (bug_uri_snippet != NULL);
1439
1440   c = strstr (test_uri_base, "%s");
1441   if (c)
1442     {
1443       char *b = g_strndup (test_uri_base, c - test_uri_base);
1444       char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
1445       g_free (b);
1446       g_test_message ("Bug Reference: %s", s);
1447       g_free (s);
1448     }
1449   else
1450     g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
1451 }
1452
1453 /**
1454  * g_test_get_root:
1455  *
1456  * Get the toplevel test suite for the test path API.
1457  *
1458  * Returns: the toplevel #GTestSuite
1459  *
1460  * Since: 2.16
1461  */
1462 GTestSuite*
1463 g_test_get_root (void)
1464 {
1465   if (!test_suite_root)
1466     {
1467       test_suite_root = g_test_create_suite ("root");
1468       g_free (test_suite_root->name);
1469       test_suite_root->name = g_strdup ("");
1470     }
1471
1472   return test_suite_root;
1473 }
1474
1475 /**
1476  * g_test_run:
1477  *
1478  * Runs all tests under the toplevel suite which can be retrieved
1479  * with g_test_get_root(). Similar to g_test_run_suite(), the test
1480  * cases to be run are filtered according to
1481  * test path arguments (-p <replaceable>testpath</replaceable>) as 
1482  * parsed by g_test_init().
1483  * g_test_run_suite() or g_test_run() may only be called once
1484  * in a program.
1485  *
1486  * Returns: 0 on success
1487  *
1488  * Since: 2.16
1489  */
1490 int
1491 g_test_run (void)
1492 {
1493   return g_test_run_suite (g_test_get_root());
1494 }
1495
1496 /**
1497  * g_test_create_case:
1498  * @test_name:     the name for the test case
1499  * @data_size:     the size of the fixture data structure
1500  * @test_data:     test data argument for the test functions
1501  * @data_setup:    the function to set up the fixture data
1502  * @data_test:     the actual test function
1503  * @data_teardown: the function to teardown the fixture data
1504  *
1505  * Create a new #GTestCase, named @test_name, this API is fairly
1506  * low level, calling g_test_add() or g_test_add_func() is preferable.
1507  * When this test is executed, a fixture structure of size @data_size
1508  * will be allocated and filled with 0s. Then @data_setup is called
1509  * to initialize the fixture. After fixture setup, the actual test
1510  * function @data_test is called. Once the test run completed, the
1511  * fixture structure is torn down  by calling @data_teardown and
1512  * after that the memory is released.
1513  *
1514  * Splitting up a test run into fixture setup, test function and
1515  * fixture teardown is most usful if the same fixture is used for
1516  * multiple tests. In this cases, g_test_create_case() will be
1517  * called with the same fixture, but varying @test_name and
1518  * @data_test arguments.
1519  *
1520  * Returns: a newly allocated #GTestCase.
1521  *
1522  * Since: 2.16
1523  */
1524 GTestCase*
1525 g_test_create_case (const char       *test_name,
1526                     gsize             data_size,
1527                     gconstpointer     test_data,
1528                     GTestFixtureFunc  data_setup,
1529                     GTestFixtureFunc  data_test,
1530                     GTestFixtureFunc  data_teardown)
1531 {
1532   GTestCase *tc;
1533
1534   g_return_val_if_fail (test_name != NULL, NULL);
1535   g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
1536   g_return_val_if_fail (test_name[0] != 0, NULL);
1537   g_return_val_if_fail (data_test != NULL, NULL);
1538
1539   tc = g_slice_new0 (GTestCase);
1540   tc->name = g_strdup (test_name);
1541   tc->test_data = (gpointer) test_data;
1542   tc->fixture_size = data_size;
1543   tc->fixture_setup = (void*) data_setup;
1544   tc->fixture_test = (void*) data_test;
1545   tc->fixture_teardown = (void*) data_teardown;
1546
1547   return tc;
1548 }
1549
1550 static gint
1551 find_suite (gconstpointer l, gconstpointer s)
1552 {
1553   const GTestSuite *suite = l;
1554   const gchar *str = s;
1555
1556   return strcmp (suite->name, str);
1557 }
1558
1559 /**
1560  * GTestFixtureFunc:
1561  * @fixture: the test fixture
1562  * @user_data: the data provided when registering the test
1563  *
1564  * The type used for functions that operate on test fixtures.  This is
1565  * used for the fixture setup and teardown functions as well as for the
1566  * testcases themselves.
1567  *
1568  * @user_data is a pointer to the data that was given when registering
1569  * the test case.
1570  *
1571  * @fixture will be a pointer to the area of memory allocated by the
1572  * test framework, of the size requested.  If the requested size was
1573  * zero then @fixture will be equal to @user_data.
1574  *
1575  * Since: 2.28
1576  */
1577 void
1578 g_test_add_vtable (const char       *testpath,
1579                    gsize             data_size,
1580                    gconstpointer     test_data,
1581                    GTestFixtureFunc  data_setup,
1582                    GTestFixtureFunc  fixture_test_func,
1583                    GTestFixtureFunc  data_teardown)
1584 {
1585   gchar **segments;
1586   guint ui;
1587   GTestSuite *suite;
1588
1589   g_return_if_fail (testpath != NULL);
1590   g_return_if_fail (g_path_is_absolute (testpath));
1591   g_return_if_fail (fixture_test_func != NULL);
1592
1593   if (g_slist_find_custom (test_paths_skipped, testpath, (GCompareFunc)g_strcmp0))
1594     return;
1595
1596   suite = g_test_get_root();
1597   segments = g_strsplit (testpath, "/", -1);
1598   for (ui = 0; segments[ui] != NULL; ui++)
1599     {
1600       const char *seg = segments[ui];
1601       gboolean islast = segments[ui + 1] == NULL;
1602       if (islast && !seg[0])
1603         g_error ("invalid test case path: %s", testpath);
1604       else if (!seg[0])
1605         continue;       /* initial or duplicate slash */
1606       else if (!islast)
1607         {
1608           GSList *l;
1609           GTestSuite *csuite;
1610           l = g_slist_find_custom (suite->suites, seg, find_suite);
1611           if (l)
1612             {
1613               csuite = l->data;
1614             }
1615           else
1616             {
1617               csuite = g_test_create_suite (seg);
1618               g_test_suite_add_suite (suite, csuite);
1619             }
1620           suite = csuite;
1621         }
1622       else /* islast */
1623         {
1624           GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
1625           g_test_suite_add (suite, tc);
1626         }
1627     }
1628   g_strfreev (segments);
1629 }
1630
1631 /**
1632  * g_test_fail:
1633  *
1634  * Indicates that a test failed. This function can be called
1635  * multiple times from the same test. You can use this function
1636  * if your test failed in a recoverable way.
1637  * 
1638  * Do not use this function if the failure of a test could cause
1639  * other tests to malfunction.
1640  *
1641  * Calling this function will not stop the test from running, you
1642  * need to return from the test function yourself. So you can
1643  * produce additional diagnostic messages or even continue running
1644  * the test.
1645  *
1646  * If not called from inside a test, this function does nothing.
1647  *
1648  * Since: 2.30
1649  **/
1650 void
1651 g_test_fail (void)
1652 {
1653   test_run_success = G_TEST_RUN_FAILURE;
1654 }
1655
1656 /**
1657  * g_test_incomplete:
1658  * @msg: (allow-none): explanation
1659  *
1660  * Indicates that a test failed because of some incomplete
1661  * functionality. This function can be called multiple times
1662  * from the same test.
1663  *
1664  * Calling this function will not stop the test from running, you
1665  * need to return from the test function yourself. So you can
1666  * produce additional diagnostic messages or even continue running
1667  * the test.
1668  *
1669  * If not called from inside a test, this function does nothing.
1670  *
1671  * Since: 2.38
1672  */
1673 void
1674 g_test_incomplete (const gchar *msg)
1675 {
1676   test_run_success = G_TEST_RUN_INCOMPLETE;
1677   g_free (test_run_msg);
1678   test_run_msg = g_strdup (msg);
1679 }
1680
1681 /**
1682  * g_test_skip:
1683  * @msg: (allow-none): explanation
1684  *
1685  * Indicates that a test was skipped.
1686  *
1687  * Calling this function will not stop the test from running, you
1688  * need to return from the test function yourself. So you can
1689  * produce additional diagnostic messages or even continue running
1690  * the test.
1691  *
1692  * If not called from inside a test, this function does nothing.
1693  *
1694  * Since: 2.38
1695  */
1696 void
1697 g_test_skip (const gchar *msg)
1698 {
1699   test_run_success = G_TEST_RUN_SKIPPED;
1700   g_free (test_run_msg);
1701   test_run_msg = g_strdup (msg);
1702 }
1703
1704 /**
1705  * g_test_failed:
1706  *
1707  * Returns whether a test has already failed. This will
1708  * be the case when g_test_fail(), g_test_incomplete()
1709  * or g_test_skip() have been called, but also if an
1710  * assertion has failed.
1711  *
1712  * This can be useful to return early from a test if
1713  * continuing after a failed assertion might be harmful.
1714  *
1715  * The return value of this function is only meaningful
1716  * if it is called from inside a test function.
1717  *
1718  * Returns: %TRUE if the test has failed
1719  *
1720  * Since: 2.38
1721  */
1722 gboolean
1723 g_test_failed (void)
1724 {
1725   return test_run_success != G_TEST_RUN_SUCCESS;
1726 }
1727
1728 /**
1729  * GTestFunc:
1730  *
1731  * The type used for test case functions.
1732  *
1733  * Since: 2.28
1734  */
1735
1736 /**
1737  * g_test_add_func:
1738  * @testpath:   /-separated test case path name for the test.
1739  * @test_func:  The test function to invoke for this test.
1740  *
1741  * Create a new test case, similar to g_test_create_case(). However
1742  * the test is assumed to use no fixture, and test suites are automatically
1743  * created on the fly and added to the root fixture, based on the
1744  * slash-separated portions of @testpath.
1745  *
1746  * If @testpath includes the component "subprocess" anywhere in it,
1747  * the test will be skipped by default, and only run if explicitly
1748  * required via the <option>-p</option> command-line option or
1749  * g_test_trap_subprocess().
1750  *
1751  * Since: 2.16
1752  */
1753 void
1754 g_test_add_func (const char *testpath,
1755                  GTestFunc   test_func)
1756 {
1757   g_return_if_fail (testpath != NULL);
1758   g_return_if_fail (testpath[0] == '/');
1759   g_return_if_fail (test_func != NULL);
1760   g_test_add_vtable (testpath, 0, NULL, NULL, (GTestFixtureFunc) test_func, NULL);
1761 }
1762
1763 /**
1764  * GTestDataFunc:
1765  * @user_data: the data provided when registering the test
1766  *
1767  * The type used for test case functions that take an extra pointer
1768  * argument.
1769  *
1770  * Since: 2.28
1771  */
1772
1773 /**
1774  * g_test_add_data_func:
1775  * @testpath:   /-separated test case path name for the test.
1776  * @test_data:  Test data argument for the test function.
1777  * @test_func:  The test function to invoke for this test.
1778  *
1779  * Create a new test case, similar to g_test_create_case(). However
1780  * the test is assumed to use no fixture, and test suites are automatically
1781  * created on the fly and added to the root fixture, based on the
1782  * slash-separated portions of @testpath. The @test_data argument
1783  * will be passed as first argument to @test_func.
1784  *
1785  * If @testpath includes the component "subprocess" anywhere in it,
1786  * the test will be skipped by default, and only run if explicitly
1787  * required via the <option>-p</option> command-line option or
1788  * g_test_trap_subprocess().
1789  *
1790  * Since: 2.16
1791  */
1792 void
1793 g_test_add_data_func (const char     *testpath,
1794                       gconstpointer   test_data,
1795                       GTestDataFunc   test_func)
1796 {
1797   g_return_if_fail (testpath != NULL);
1798   g_return_if_fail (testpath[0] == '/');
1799   g_return_if_fail (test_func != NULL);
1800
1801   g_test_add_vtable (testpath, 0, test_data, NULL, (GTestFixtureFunc) test_func, NULL);
1802 }
1803
1804 /**
1805  * g_test_add_data_func_full:
1806  * @testpath: /-separated test case path name for the test.
1807  * @test_data: Test data argument for the test function.
1808  * @test_func: The test function to invoke for this test.
1809  * @data_free_func: #GDestroyNotify for @test_data.
1810  *
1811  * Create a new test case, as with g_test_add_data_func(), but freeing
1812  * @test_data after the test run is complete.
1813  *
1814  * Since: 2.34
1815  */
1816 void
1817 g_test_add_data_func_full (const char     *testpath,
1818                            gpointer        test_data,
1819                            GTestDataFunc   test_func,
1820                            GDestroyNotify  data_free_func)
1821 {
1822   g_return_if_fail (testpath != NULL);
1823   g_return_if_fail (testpath[0] == '/');
1824   g_return_if_fail (test_func != NULL);
1825
1826   g_test_add_vtable (testpath, 0, test_data, NULL,
1827                      (GTestFixtureFunc) test_func,
1828                      (GTestFixtureFunc) data_free_func);
1829 }
1830
1831 static gboolean
1832 g_test_suite_case_exists (GTestSuite *suite,
1833                           const char *test_path)
1834 {
1835   GSList *iter;
1836   char *slash;
1837   GTestCase *tc;
1838
1839   test_path++;
1840   slash = strchr (test_path, '/');
1841
1842   if (slash)
1843     {
1844       for (iter = suite->suites; iter; iter = iter->next)
1845         {
1846           GTestSuite *child_suite = iter->data;
1847
1848           if (!strncmp (child_suite->name, test_path, slash - test_path))
1849             if (g_test_suite_case_exists (child_suite, slash))
1850               return TRUE;
1851         }
1852     }
1853   else
1854     {
1855       for (iter = suite->cases; iter; iter = iter->next)
1856         {
1857           tc = iter->data;
1858           if (!strcmp (tc->name, test_path))
1859             return TRUE;
1860         }
1861     }
1862
1863   return FALSE;
1864 }
1865
1866 /**
1867  * g_test_create_suite:
1868  * @suite_name: a name for the suite
1869  *
1870  * Create a new test suite with the name @suite_name.
1871  *
1872  * Returns: A newly allocated #GTestSuite instance.
1873  *
1874  * Since: 2.16
1875  */
1876 GTestSuite*
1877 g_test_create_suite (const char *suite_name)
1878 {
1879   GTestSuite *ts;
1880   g_return_val_if_fail (suite_name != NULL, NULL);
1881   g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
1882   g_return_val_if_fail (suite_name[0] != 0, NULL);
1883   ts = g_slice_new0 (GTestSuite);
1884   ts->name = g_strdup (suite_name);
1885   return ts;
1886 }
1887
1888 /**
1889  * g_test_suite_add:
1890  * @suite: a #GTestSuite
1891  * @test_case: a #GTestCase
1892  *
1893  * Adds @test_case to @suite.
1894  *
1895  * Since: 2.16
1896  */
1897 void
1898 g_test_suite_add (GTestSuite     *suite,
1899                   GTestCase      *test_case)
1900 {
1901   g_return_if_fail (suite != NULL);
1902   g_return_if_fail (test_case != NULL);
1903
1904   suite->cases = g_slist_prepend (suite->cases, test_case);
1905 }
1906
1907 /**
1908  * g_test_suite_add_suite:
1909  * @suite:       a #GTestSuite
1910  * @nestedsuite: another #GTestSuite
1911  *
1912  * Adds @nestedsuite to @suite.
1913  *
1914  * Since: 2.16
1915  */
1916 void
1917 g_test_suite_add_suite (GTestSuite     *suite,
1918                         GTestSuite     *nestedsuite)
1919 {
1920   g_return_if_fail (suite != NULL);
1921   g_return_if_fail (nestedsuite != NULL);
1922
1923   suite->suites = g_slist_prepend (suite->suites, nestedsuite);
1924 }
1925
1926 /**
1927  * g_test_queue_free:
1928  * @gfree_pointer: the pointer to be stored.
1929  *
1930  * Enqueue a pointer to be released with g_free() during the next
1931  * teardown phase. This is equivalent to calling g_test_queue_destroy()
1932  * with a destroy callback of g_free().
1933  *
1934  * Since: 2.16
1935  */
1936 void
1937 g_test_queue_free (gpointer gfree_pointer)
1938 {
1939   if (gfree_pointer)
1940     g_test_queue_destroy (g_free, gfree_pointer);
1941 }
1942
1943 /**
1944  * g_test_queue_destroy:
1945  * @destroy_func:       Destroy callback for teardown phase.
1946  * @destroy_data:       Destroy callback data.
1947  *
1948  * This function enqueus a callback @destroy_func to be executed
1949  * during the next test case teardown phase. This is most useful
1950  * to auto destruct allocted test resources at the end of a test run.
1951  * Resources are released in reverse queue order, that means enqueueing
1952  * callback A before callback B will cause B() to be called before
1953  * A() during teardown.
1954  *
1955  * Since: 2.16
1956  */
1957 void
1958 g_test_queue_destroy (GDestroyNotify destroy_func,
1959                       gpointer       destroy_data)
1960 {
1961   DestroyEntry *dentry;
1962
1963   g_return_if_fail (destroy_func != NULL);
1964
1965   dentry = g_slice_new0 (DestroyEntry);
1966   dentry->destroy_func = destroy_func;
1967   dentry->destroy_data = destroy_data;
1968   dentry->next = test_destroy_queue;
1969   test_destroy_queue = dentry;
1970 }
1971
1972 static gboolean
1973 test_case_run (GTestCase *tc)
1974 {
1975   gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1976   GSList **old_free_list, *filename_free_list = NULL;
1977   gboolean success = G_TEST_RUN_SUCCESS;
1978
1979   old_free_list = test_filename_free_list;
1980   test_filename_free_list = &filename_free_list;
1981
1982   test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1983   if (strstr (test_run_name, "/subprocess"))
1984     {
1985       GSList *iter;
1986       gboolean found = FALSE;
1987
1988       for (iter = test_paths; iter; iter = iter->next)
1989         {
1990           if (!strcmp (test_run_name, iter->data))
1991             {
1992               found = TRUE;
1993               break;
1994             }
1995         }
1996
1997       if (!found)
1998         {
1999           if (g_test_verbose ())
2000             g_print ("GTest: skipping: %s\n", test_run_name);
2001           goto out;
2002         }
2003     }
2004
2005   if (++test_run_count <= test_skip_count)
2006     g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
2007   else if (test_run_list)
2008     {
2009       g_print ("%s\n", test_run_name);
2010       g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
2011     }
2012   else
2013     {
2014       GTimer *test_run_timer = g_timer_new();
2015       long double largs[3];
2016       void *fixture;
2017       g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
2018       test_run_forks = 0;
2019       test_run_success = G_TEST_RUN_SUCCESS;
2020       g_clear_pointer (&test_run_msg, g_free);
2021       g_test_log_set_fatal_handler (NULL, NULL);
2022       g_timer_start (test_run_timer);
2023       fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
2024       test_run_seed (test_run_seedstr);
2025       if (tc->fixture_setup)
2026         tc->fixture_setup (fixture, tc->test_data);
2027       tc->fixture_test (fixture, tc->test_data);
2028       test_trap_clear();
2029       while (test_destroy_queue)
2030         {
2031           DestroyEntry *dentry = test_destroy_queue;
2032           test_destroy_queue = dentry->next;
2033           dentry->destroy_func (dentry->destroy_data);
2034           g_slice_free (DestroyEntry, dentry);
2035         }
2036       if (tc->fixture_teardown)
2037         tc->fixture_teardown (fixture, tc->test_data);
2038       if (tc->fixture_size)
2039         g_free (fixture);
2040       g_timer_stop (test_run_timer);
2041       success = test_run_success;
2042       test_run_success = G_TEST_RUN_FAILURE;
2043       largs[0] = success; /* OK */
2044       largs[1] = test_run_forks;
2045       largs[2] = g_timer_elapsed (test_run_timer, NULL);
2046       g_test_log (G_TEST_LOG_STOP_CASE, test_run_name, test_run_msg, G_N_ELEMENTS (largs), largs);
2047       g_clear_pointer (&test_run_msg, g_free);
2048       g_timer_destroy (test_run_timer);
2049     }
2050
2051  out:
2052   g_slist_free_full (filename_free_list, g_free);
2053   test_filename_free_list = old_free_list;
2054   g_free (test_run_name);
2055   test_run_name = old_name;
2056   g_free (test_uri_base);
2057   test_uri_base = old_base;
2058
2059   return success == G_TEST_RUN_SUCCESS;
2060 }
2061
2062 static int
2063 g_test_run_suite_internal (GTestSuite *suite,
2064                            const char *path)
2065 {
2066   guint n_bad = 0, l;
2067   gchar *rest, *old_name = test_run_name;
2068   GSList *slist, *reversed;
2069
2070   g_return_val_if_fail (suite != NULL, -1);
2071
2072   g_test_log (G_TEST_LOG_START_SUITE, suite->name, NULL, 0, NULL);
2073
2074   while (path[0] == '/')
2075     path++;
2076   l = strlen (path);
2077   rest = strchr (path, '/');
2078   l = rest ? MIN (l, rest - path) : l;
2079   test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
2080   reversed = g_slist_reverse (g_slist_copy (suite->cases));
2081   for (slist = reversed; slist; slist = slist->next)
2082     {
2083       GTestCase *tc = slist->data;
2084       guint n = l ? strlen (tc->name) : 0;
2085       if (l == n && !rest && strncmp (path, tc->name, n) == 0)
2086         {
2087           if (!test_case_run (tc))
2088             n_bad++;
2089         }
2090     }
2091   g_slist_free (reversed);
2092   reversed = g_slist_reverse (g_slist_copy (suite->suites));
2093   for (slist = reversed; slist; slist = slist->next)
2094     {
2095       GTestSuite *ts = slist->data;
2096       guint n = l ? strlen (ts->name) : 0;
2097       if (l == n && strncmp (path, ts->name, n) == 0)
2098         n_bad += g_test_run_suite_internal (ts, rest ? rest : "");
2099     }
2100   g_slist_free (reversed);
2101   g_free (test_run_name);
2102   test_run_name = old_name;
2103
2104   g_test_log (G_TEST_LOG_STOP_SUITE, suite->name, NULL, 0, NULL);
2105
2106   return n_bad;
2107 }
2108
2109 /**
2110  * g_test_run_suite:
2111  * @suite: a #GTestSuite
2112  *
2113  * Execute the tests within @suite and all nested #GTestSuites.
2114  * The test suites to be executed are filtered according to
2115  * test path arguments (-p <replaceable>testpath</replaceable>) 
2116  * as parsed by g_test_init().
2117  * g_test_run_suite() or g_test_run() may only be called once
2118  * in a program.
2119  *
2120  * Returns: 0 on success
2121  *
2122  * Since: 2.16
2123  */
2124 int
2125 g_test_run_suite (GTestSuite *suite)
2126 {
2127   GSList *my_test_paths;
2128   guint n_bad = 0;
2129
2130   g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
2131   g_return_val_if_fail (g_test_run_once == TRUE, -1);
2132
2133   g_test_run_once = FALSE;
2134
2135   if (test_paths)
2136     my_test_paths = g_slist_copy (test_paths);
2137   else
2138     my_test_paths = g_slist_prepend (NULL, "");
2139
2140   while (my_test_paths)
2141     {
2142       const char *rest, *path = my_test_paths->data;
2143       guint l, n = strlen (suite->name);
2144       my_test_paths = g_slist_delete_link (my_test_paths, my_test_paths);
2145       while (path[0] == '/')
2146         path++;
2147       if (!n) /* root suite, run unconditionally */
2148         {
2149           n_bad += g_test_run_suite_internal (suite, path);
2150           continue;
2151         }
2152       /* regular suite, match path */
2153       rest = strchr (path, '/');
2154       l = strlen (path);
2155       l = rest ? MIN (l, rest - path) : l;
2156       if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
2157         n_bad += g_test_run_suite_internal (suite, rest ? rest : "");
2158     }
2159
2160   return n_bad;
2161 }
2162
2163 static void
2164 gtest_default_log_handler (const gchar    *log_domain,
2165                            GLogLevelFlags  log_level,
2166                            const gchar    *message,
2167                            gpointer        unused_data)
2168 {
2169   const gchar *strv[16];
2170   gboolean fatal = FALSE;
2171   gchar *msg;
2172   guint i = 0;
2173
2174   if (log_domain)
2175     {
2176       strv[i++] = log_domain;
2177       strv[i++] = "-";
2178     }
2179   if (log_level & G_LOG_FLAG_FATAL)
2180     {
2181       strv[i++] = "FATAL-";
2182       fatal = TRUE;
2183     }
2184   if (log_level & G_LOG_FLAG_RECURSION)
2185     strv[i++] = "RECURSIVE-";
2186   if (log_level & G_LOG_LEVEL_ERROR)
2187     strv[i++] = "ERROR";
2188   if (log_level & G_LOG_LEVEL_CRITICAL)
2189     strv[i++] = "CRITICAL";
2190   if (log_level & G_LOG_LEVEL_WARNING)
2191     strv[i++] = "WARNING";
2192   if (log_level & G_LOG_LEVEL_MESSAGE)
2193     strv[i++] = "MESSAGE";
2194   if (log_level & G_LOG_LEVEL_INFO)
2195     strv[i++] = "INFO";
2196   if (log_level & G_LOG_LEVEL_DEBUG)
2197     strv[i++] = "DEBUG";
2198   strv[i++] = ": ";
2199   strv[i++] = message;
2200   strv[i++] = NULL;
2201
2202   msg = g_strjoinv ("", (gchar**) strv);
2203   g_test_log (fatal ? G_TEST_LOG_ERROR : G_TEST_LOG_MESSAGE, msg, NULL, 0, NULL);
2204   g_log_default_handler (log_domain, log_level, message, unused_data);
2205
2206   g_free (msg);
2207 }
2208
2209 void
2210 g_assertion_message (const char     *domain,
2211                      const char     *file,
2212                      int             line,
2213                      const char     *func,
2214                      const char     *message)
2215 {
2216   char lstr[32];
2217   char *s;
2218
2219   if (!message)
2220     message = "code should not be reached";
2221   g_snprintf (lstr, 32, "%d", line);
2222   s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
2223                    "ERROR:", file, ":", lstr, ":",
2224                    func, func[0] ? ":" : "",
2225                    " ", message, NULL);
2226   g_printerr ("**\n%s\n", s);
2227
2228   /* store assertion message in global variable, so that it can be found in a
2229    * core dump */
2230   if (__glib_assert_msg != NULL)
2231       /* free the old one */
2232       free (__glib_assert_msg);
2233   __glib_assert_msg = (char*) malloc (strlen (s) + 1);
2234   strcpy (__glib_assert_msg, s);
2235
2236   g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
2237   g_free (s);
2238   _g_log_abort ();
2239 }
2240
2241 void
2242 g_assertion_message_expr (const char     *domain,
2243                           const char     *file,
2244                           int             line,
2245                           const char     *func,
2246                           const char     *expr)
2247 {
2248   char *s;
2249   if (!expr)
2250     s = g_strdup ("code should not be reached");
2251   else
2252     s = g_strconcat ("assertion failed: (", expr, ")", NULL);
2253   g_assertion_message (domain, file, line, func, s);
2254   g_free (s);
2255 }
2256
2257 void
2258 g_assertion_message_cmpnum (const char     *domain,
2259                             const char     *file,
2260                             int             line,
2261                             const char     *func,
2262                             const char     *expr,
2263                             long double     arg1,
2264                             const char     *cmp,
2265                             long double     arg2,
2266                             char            numtype)
2267 {
2268   char *s = NULL;
2269
2270   switch (numtype)
2271     {
2272     case 'i':   s = g_strdup_printf ("assertion failed (%s): (%" G_GINT64_MODIFIER "i %s %" G_GINT64_MODIFIER "i)", expr, (gint64) arg1, cmp, (gint64) arg2); break;
2273     case 'x':   s = g_strdup_printf ("assertion failed (%s): (0x%08" G_GINT64_MODIFIER "x %s 0x%08" G_GINT64_MODIFIER "x)", expr, (guint64) arg1, cmp, (guint64) arg2); break;
2274     case 'f':   s = g_strdup_printf ("assertion failed (%s): (%.9g %s %.9g)", expr, (double) arg1, cmp, (double) arg2); break;
2275       /* ideally use: floats=%.7g double=%.17g */
2276     }
2277   g_assertion_message (domain, file, line, func, s);
2278   g_free (s);
2279 }
2280
2281 void
2282 g_assertion_message_cmpstr (const char     *domain,
2283                             const char     *file,
2284                             int             line,
2285                             const char     *func,
2286                             const char     *expr,
2287                             const char     *arg1,
2288                             const char     *cmp,
2289                             const char     *arg2)
2290 {
2291   char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
2292   a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
2293   a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
2294   g_free (t1);
2295   g_free (t2);
2296   s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
2297   g_free (a1);
2298   g_free (a2);
2299   g_assertion_message (domain, file, line, func, s);
2300   g_free (s);
2301 }
2302
2303 void
2304 g_assertion_message_error (const char     *domain,
2305                            const char     *file,
2306                            int             line,
2307                            const char     *func,
2308                            const char     *expr,
2309                            const GError   *error,
2310                            GQuark          error_domain,
2311                            int             error_code)
2312 {
2313   GString *gstring;
2314
2315   /* This is used by both g_assert_error() and g_assert_no_error(), so there
2316    * are three cases: expected an error but got the wrong error, expected
2317    * an error but got no error, and expected no error but got an error.
2318    */
2319
2320   gstring = g_string_new ("assertion failed ");
2321   if (error_domain)
2322       g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
2323                               g_quark_to_string (error_domain), error_code);
2324   else
2325     g_string_append_printf (gstring, "(%s == NULL): ", expr);
2326
2327   if (error)
2328       g_string_append_printf (gstring, "%s (%s, %d)", error->message,
2329                               g_quark_to_string (error->domain), error->code);
2330   else
2331     g_string_append_printf (gstring, "%s is NULL", expr);
2332
2333   g_assertion_message (domain, file, line, func, gstring->str);
2334   g_string_free (gstring, TRUE);
2335 }
2336
2337 /**
2338  * g_strcmp0:
2339  * @str1: (allow-none): a C string or %NULL
2340  * @str2: (allow-none): another C string or %NULL
2341  *
2342  * Compares @str1 and @str2 like strcmp(). Handles %NULL
2343  * gracefully by sorting it before non-%NULL strings.
2344  * Comparing two %NULL pointers returns 0.
2345  *
2346  * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2.
2347  *
2348  * Since: 2.16
2349  */
2350 int
2351 g_strcmp0 (const char     *str1,
2352            const char     *str2)
2353 {
2354   if (!str1)
2355     return -(str1 != str2);
2356   if (!str2)
2357     return str1 != str2;
2358   return strcmp (str1, str2);
2359 }
2360
2361 static void
2362 test_trap_clear (void)
2363 {
2364   test_trap_last_status = 0;
2365   test_trap_last_pid = 0;
2366   g_clear_pointer (&test_trap_last_subprocess, g_free);
2367   g_clear_pointer (&test_trap_last_stdout, g_free);
2368   g_clear_pointer (&test_trap_last_stderr, g_free);
2369 }
2370
2371 #ifdef G_OS_UNIX
2372
2373 static int
2374 sane_dup2 (int fd1,
2375            int fd2)
2376 {
2377   int ret;
2378   do
2379     ret = dup2 (fd1, fd2);
2380   while (ret < 0 && errno == EINTR);
2381   return ret;
2382 }
2383
2384 #endif
2385
2386 typedef struct {
2387   GPid pid;
2388   GMainLoop *loop;
2389   int child_status;
2390
2391   GIOChannel *stdout_io;
2392   gboolean echo_stdout;
2393   GString *stdout_str;
2394
2395   GIOChannel *stderr_io;
2396   gboolean echo_stderr;
2397   GString *stderr_str;
2398 } WaitForChildData;
2399
2400 static void
2401 check_complete (WaitForChildData *data)
2402 {
2403   if (data->child_status != -1 && data->stdout_io == NULL && data->stderr_io == NULL)
2404     g_main_loop_quit (data->loop);
2405 }
2406
2407 static void
2408 child_exited (GPid     pid,
2409               gint     status,
2410               gpointer user_data)
2411 {
2412   WaitForChildData *data = user_data;
2413
2414 #ifdef G_OS_UNIX
2415   if (WIFEXITED (status)) /* normal exit */
2416     data->child_status = WEXITSTATUS (status); /* 0..255 */
2417   else if (WIFSIGNALED (status) && WTERMSIG (status) == SIGALRM)
2418     data->child_status = G_TEST_STATUS_TIMED_OUT;
2419   else if (WIFSIGNALED (status))
2420     data->child_status = (WTERMSIG (status) << 12); /* signalled */
2421   else /* WCOREDUMP (status) */
2422     data->child_status = 512; /* coredump */
2423 #else
2424   data->child_status = status;
2425 #endif
2426
2427   check_complete (data);
2428 }
2429
2430 static gboolean
2431 child_timeout (gpointer user_data)
2432 {
2433   WaitForChildData *data = user_data;
2434
2435 #ifdef G_OS_WIN32
2436   TerminateProcess (data->pid, G_TEST_STATUS_TIMED_OUT);
2437 #else
2438   kill (data->pid, SIGALRM);
2439 #endif
2440
2441   return FALSE;
2442 }
2443
2444 static gboolean
2445 child_read (GIOChannel *io, GIOCondition cond, gpointer user_data)
2446 {
2447   WaitForChildData *data = user_data;
2448   GIOStatus status;
2449   gsize nread, nwrote, total;
2450   gchar buf[4096];
2451   FILE *echo_file = NULL;
2452
2453   status = g_io_channel_read_chars (io, buf, sizeof (buf), &nread, NULL);
2454   if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF)
2455     {
2456       // FIXME data->error = (status == G_IO_STATUS_ERROR);
2457       if (io == data->stdout_io)
2458         g_clear_pointer (&data->stdout_io, g_io_channel_unref);
2459       else
2460         g_clear_pointer (&data->stderr_io, g_io_channel_unref);
2461
2462       check_complete (data);
2463       return FALSE;
2464     }
2465   else if (status == G_IO_STATUS_AGAIN)
2466     return TRUE;
2467
2468   if (io == data->stdout_io)
2469     {
2470       g_string_append_len (data->stdout_str, buf, nread);
2471       if (data->echo_stdout)
2472         echo_file = stdout;
2473     }
2474   else
2475     {
2476       g_string_append_len (data->stderr_str, buf, nread);
2477       if (data->echo_stderr)
2478         echo_file = stderr;
2479     }
2480
2481   if (echo_file)
2482     {
2483       for (total = 0; total < nread; total += nwrote)
2484         {
2485           nwrote = fwrite (buf + total, 1, nread - total, echo_file);
2486           if (nwrote == 0)
2487             g_error ("write failed: %s", g_strerror (errno));
2488         }
2489     }
2490
2491   return TRUE;
2492 }
2493
2494 static void
2495 wait_for_child (GPid pid,
2496                 int stdout_fd, gboolean echo_stdout,
2497                 int stderr_fd, gboolean echo_stderr,
2498                 guint64 timeout)
2499 {
2500   WaitForChildData data;
2501   GMainContext *context;
2502   GSource *source;
2503
2504   data.pid = pid;
2505   data.child_status = -1;
2506
2507   context = g_main_context_new ();
2508   data.loop = g_main_loop_new (context, FALSE);
2509
2510   source = g_child_watch_source_new (pid);
2511   g_source_set_callback (source, (GSourceFunc) child_exited, &data, NULL);
2512   g_source_attach (source, context);
2513   g_source_unref (source);
2514
2515   data.echo_stdout = echo_stdout;
2516   data.stdout_str = g_string_new (NULL);
2517   data.stdout_io = g_io_channel_unix_new (stdout_fd);
2518   g_io_channel_set_close_on_unref (data.stdout_io, TRUE);
2519   g_io_channel_set_encoding (data.stdout_io, NULL, NULL);
2520   g_io_channel_set_buffered (data.stdout_io, FALSE);
2521   source = g_io_create_watch (data.stdout_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2522   g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2523   g_source_attach (source, context);
2524   g_source_unref (source);
2525
2526   data.echo_stderr = echo_stderr;
2527   data.stderr_str = g_string_new (NULL);
2528   data.stderr_io = g_io_channel_unix_new (stderr_fd);
2529   g_io_channel_set_close_on_unref (data.stderr_io, TRUE);
2530   g_io_channel_set_encoding (data.stderr_io, NULL, NULL);
2531   g_io_channel_set_buffered (data.stderr_io, FALSE);
2532   source = g_io_create_watch (data.stderr_io, G_IO_IN | G_IO_ERR | G_IO_HUP);
2533   g_source_set_callback (source, (GSourceFunc) child_read, &data, NULL);
2534   g_source_attach (source, context);
2535   g_source_unref (source);
2536
2537   if (timeout)
2538     {
2539       source = g_timeout_source_new (0);
2540       g_source_set_ready_time (source, g_get_monotonic_time () + timeout);
2541       g_source_set_callback (source, (GSourceFunc) child_timeout, &data, NULL);
2542       g_source_attach (source, context);
2543       g_source_unref (source);
2544     }
2545
2546   g_main_loop_run (data.loop);
2547   g_main_loop_unref (data.loop);
2548   g_main_context_unref (context);
2549
2550   test_trap_last_pid = pid;
2551   test_trap_last_status = data.child_status;
2552   test_trap_last_stdout = g_string_free (data.stdout_str, FALSE);
2553   test_trap_last_stderr = g_string_free (data.stderr_str, FALSE);
2554
2555   g_clear_pointer (&data.stdout_io, g_io_channel_unref);
2556   g_clear_pointer (&data.stderr_io, g_io_channel_unref);
2557 }
2558
2559 /**
2560  * g_test_trap_fork:
2561  * @usec_timeout:    Timeout for the forked test in micro seconds.
2562  * @test_trap_flags: Flags to modify forking behaviour.
2563  *
2564  * Fork the current test program to execute a test case that might
2565  * not return or that might abort.
2566  *
2567  * If @usec_timeout is non-0, the forked test case is aborted and
2568  * considered failing if its run time exceeds it.
2569  *
2570  * The forking behavior can be configured with the #GTestTrapFlags flags.
2571  *
2572  * In the following example, the test code forks, the forked child
2573  * process produces some sample output and exits successfully.
2574  * The forking parent process then asserts successful child program
2575  * termination and validates child program outputs.
2576  *
2577  * |[
2578  *   static void
2579  *   test_fork_patterns (void)
2580  *   {
2581  *     if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
2582  *       {
2583  *         g_print ("some stdout text: somagic17\n");
2584  *         g_printerr ("some stderr text: semagic43\n");
2585  *         exit (0); /&ast; successful test run &ast;/
2586  *       }
2587  *     g_test_trap_assert_passed ();
2588  *     g_test_trap_assert_stdout ("*somagic17*");
2589  *     g_test_trap_assert_stderr ("*semagic43*");
2590  *   }
2591  * ]|
2592  *
2593  * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
2594  *
2595  * Since: 2.16
2596  *
2597  * Deprecated: This function is implemented only on Unix platforms,
2598  * and is not always reliable due to problems inherent in
2599  * fork-without-exec. Use g_test_trap_subprocess() instead.
2600  */
2601 gboolean
2602 g_test_trap_fork (guint64        usec_timeout,
2603                   GTestTrapFlags test_trap_flags)
2604 {
2605 #ifdef G_OS_UNIX
2606   int stdout_pipe[2] = { -1, -1 };
2607   int stderr_pipe[2] = { -1, -1 };
2608
2609   test_trap_clear();
2610   if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0)
2611     g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
2612   test_trap_last_pid = fork ();
2613   if (test_trap_last_pid < 0)
2614     g_error ("failed to fork test program: %s", g_strerror (errno));
2615   if (test_trap_last_pid == 0)  /* child */
2616     {
2617       int fd0 = -1;
2618       close (stdout_pipe[0]);
2619       close (stderr_pipe[0]);
2620       if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
2621         fd0 = g_open ("/dev/null", O_RDONLY, 0);
2622       if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
2623         g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
2624       if (fd0 >= 3)
2625         close (fd0);
2626       if (stdout_pipe[1] >= 3)
2627         close (stdout_pipe[1]);
2628       if (stderr_pipe[1] >= 3)
2629         close (stderr_pipe[1]);
2630       return TRUE;
2631     }
2632   else                          /* parent */
2633     {
2634       test_run_forks++;
2635       close (stdout_pipe[1]);
2636       close (stderr_pipe[1]);
2637
2638       wait_for_child (test_trap_last_pid,
2639                       stdout_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT),
2640                       stderr_pipe[0], !(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR),
2641                       usec_timeout);
2642       return FALSE;
2643     }
2644 #else
2645   g_message ("Not implemented: g_test_trap_fork");
2646
2647   return FALSE;
2648 #endif
2649 }
2650
2651 /**
2652  * g_test_trap_subprocess:
2653  * @test_path:    Test to run in a subprocess
2654  * @usec_timeout: Timeout for the subprocess test in micro seconds.
2655  * @test_flags:   Flags to modify subprocess behaviour.
2656  *
2657  * Respawns the test program to run only @test_path in a subprocess.
2658  * This can be used for a test case that might not return, or that
2659  * might abort. @test_path will normally be the name of the parent
2660  * test, followed by "<literal>/subprocess/</literal>" and then a name
2661  * for the specific subtest (or just ending with
2662  * "<literal>/subprocess</literal>" if the test only has one child
2663  * test); tests with names of this form will automatically be skipped
2664  * in the parent process.
2665  *
2666  * If @usec_timeout is non-0, the test subprocess is aborted and
2667  * considered failing if its run time exceeds it.
2668  *
2669  * The subprocess behavior can be configured with the
2670  * #GTestSubprocessFlags flags.
2671  *
2672  * You can use methods such as g_test_trap_assert_passed(),
2673  * g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to
2674  * check the results of the subprocess. (But note that
2675  * g_test_trap_assert_stdout() and g_test_trap_assert_stderr()
2676  * cannot be used if @test_flags specifies that the child should
2677  * inherit the parent stdout/stderr.) 
2678  *
2679  * If your <literal>main ()</literal> needs to behave differently in
2680  * the subprocess, you can call g_test_subprocess() (after calling
2681  * g_test_init()) to see whether you are in a subprocess.
2682  *
2683  * The following example tests that calling
2684  * <literal>my_object_new(1000000)</literal> will abort with an error
2685  * message.
2686  *
2687  * |[
2688  *   static void
2689  *   test_create_large_object_subprocess (void)
2690  *   {
2691  *     my_object_new (1000000);
2692  *   }
2693  *
2694  *   static void
2695  *   test_create_large_object (void)
2696  *   {
2697  *     g_test_trap_subprocess ("/myobject/create_large_object/subprocess", 0, 0);
2698  *     g_test_trap_assert_failed ();
2699  *     g_test_trap_assert_stderr ("*ERROR*too large*");
2700  *   }
2701  *
2702  *   int
2703  *   main (int argc, char **argv)
2704  *   {
2705  *     g_test_init (&argc, &argv, NULL);
2706  *
2707  *     g_test_add_func ("/myobject/create_large_object",
2708  *                      test_create_large_object);
2709  *     /&ast; Because of the '/subprocess' in the name, this test will
2710  *      &ast; not be run by the g_test_run () call below.
2711  *      &ast;/
2712  *     g_test_add_func ("/myobject/create_large_object/subprocess",
2713  *                      test_create_large_object_subprocess);
2714  *
2715  *     return g_test_run ();
2716  *   }
2717  * ]|
2718  *
2719  * Since: 2.38
2720  */
2721 void
2722 g_test_trap_subprocess (const char           *test_path,
2723                         guint64               usec_timeout,
2724                         GTestSubprocessFlags  test_flags)
2725 {
2726   GError *error = NULL;
2727   GPtrArray *argv;
2728   GSpawnFlags flags;
2729   int stdout_fd, stderr_fd;
2730   GPid pid;
2731
2732   /* Sanity check that they used GTestSubprocessFlags, not GTestTrapFlags */
2733   g_assert ((test_flags & (G_TEST_TRAP_INHERIT_STDIN | G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR)) == 0);
2734
2735   if (!g_test_suite_case_exists (g_test_get_root (), test_path))
2736     g_error ("g_test_trap_subprocess: test does not exist: %s", test_path);
2737
2738   if (g_test_verbose ())
2739     g_print ("GTest: subprocess: %s\n", test_path);
2740
2741   test_trap_clear ();
2742   test_trap_last_subprocess = g_strdup (test_path);
2743
2744   argv = g_ptr_array_new ();
2745   g_ptr_array_add (argv, test_argv0);
2746   g_ptr_array_add (argv, "-q");
2747   g_ptr_array_add (argv, "-p");
2748   g_ptr_array_add (argv, (char *)test_path);
2749   g_ptr_array_add (argv, "--GTestSubprocess");
2750   if (test_log_fd != -1)
2751     {
2752       char log_fd_buf[128];
2753
2754       g_ptr_array_add (argv, "--GTestLogFD");
2755       g_snprintf (log_fd_buf, sizeof (log_fd_buf), "%d", test_log_fd);
2756       g_ptr_array_add (argv, log_fd_buf);
2757     }
2758   g_ptr_array_add (argv, NULL);
2759
2760   flags = G_SPAWN_DO_NOT_REAP_CHILD;
2761   if (test_flags & G_TEST_TRAP_INHERIT_STDIN)
2762     flags |= G_SPAWN_CHILD_INHERITS_STDIN;
2763
2764   if (!g_spawn_async_with_pipes (test_initial_cwd,
2765                                  (char **)argv->pdata,
2766                                  NULL, flags,
2767                                  NULL, NULL,
2768                                  &pid, NULL, &stdout_fd, &stderr_fd,
2769                                  &error))
2770     {
2771       g_error ("g_test_trap_subprocess() failed: %s\n",
2772                error->message);
2773     }
2774   g_ptr_array_free (argv, TRUE);
2775
2776   wait_for_child (pid,
2777                   stdout_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDOUT),
2778                   stderr_fd, !!(test_flags & G_TEST_SUBPROCESS_INHERIT_STDERR),
2779                   usec_timeout);
2780 }
2781
2782 /**
2783  * g_test_subprocess:
2784  *
2785  * Returns %TRUE (after g_test_init() has been called) if the test
2786  * program is running under g_test_trap_subprocess().
2787  *
2788  * Returns: %TRUE if the test program is running under
2789  * g_test_trap_subprocess().
2790  *
2791  * Since: 2.38
2792  */
2793 gboolean
2794 g_test_subprocess (void)
2795 {
2796   return test_in_subprocess;
2797 }
2798
2799 /**
2800  * g_test_trap_has_passed:
2801  *
2802  * Check the result of the last g_test_trap_subprocess() call.
2803  *
2804  * Returns: %TRUE if the last test subprocess terminated successfully.
2805  *
2806  * Since: 2.16
2807  */
2808 gboolean
2809 g_test_trap_has_passed (void)
2810 {
2811   return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
2812 }
2813
2814 /**
2815  * g_test_trap_reached_timeout:
2816  *
2817  * Check the result of the last g_test_trap_subprocess() call.
2818  *
2819  * Returns: %TRUE if the last test subprocess got killed due to a timeout.
2820  *
2821  * Since: 2.16
2822  */
2823 gboolean
2824 g_test_trap_reached_timeout (void)
2825 {
2826   return test_trap_last_status != G_TEST_STATUS_TIMED_OUT;
2827 }
2828
2829 void
2830 g_test_trap_assertions (const char     *domain,
2831                         const char     *file,
2832                         int             line,
2833                         const char     *func,
2834                         guint64         assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
2835                         const char     *pattern)
2836 {
2837   gboolean must_pass = assertion_flags == 0;
2838   gboolean must_fail = assertion_flags == 1;
2839   gboolean match_result = 0 == (assertion_flags & 1);
2840   const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
2841   const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
2842   const char *match_error = match_result ? "failed to match" : "contains invalid match";
2843   char *process_id;
2844
2845 #ifdef G_OS_UNIX
2846   if (test_trap_last_subprocess != NULL)
2847     {
2848       process_id = g_strdup_printf ("%s [%d]", test_trap_last_subprocess,
2849                                     test_trap_last_pid);
2850     }
2851   else if (test_trap_last_pid != 0)
2852     process_id = g_strdup_printf ("%d", test_trap_last_pid);
2853 #else
2854   if (test_trap_last_subprocess != NULL)
2855     process_id = g_strdup (test_trap_last_subprocess);
2856 #endif
2857   else
2858     g_error ("g_test_trap_ assertion with no trapped test");
2859
2860   if (must_pass && !g_test_trap_has_passed())
2861     {
2862       char *msg = g_strdup_printf ("child process (%s) failed unexpectedly", process_id);
2863       g_assertion_message (domain, file, line, func, msg);
2864       g_free (msg);
2865     }
2866   if (must_fail && g_test_trap_has_passed())
2867     {
2868       char *msg = g_strdup_printf ("child process (%s) did not fail as expected", process_id);
2869       g_assertion_message (domain, file, line, func, msg);
2870       g_free (msg);
2871     }
2872   if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
2873     {
2874       char *msg = g_strdup_printf ("stdout of child process (%s) %s: %s", process_id, match_error, stdout_pattern);
2875       g_assertion_message (domain, file, line, func, msg);
2876       g_free (msg);
2877     }
2878   if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
2879     {
2880       char *msg = g_strdup_printf ("stderr of child process (%s) %s: %s", process_id, match_error, stderr_pattern);
2881       g_assertion_message (domain, file, line, func, msg);
2882       g_free (msg);
2883     }
2884   g_free (process_id);
2885 }
2886
2887 static void
2888 gstring_overwrite_int (GString *gstring,
2889                        guint    pos,
2890                        guint32  vuint)
2891 {
2892   vuint = g_htonl (vuint);
2893   g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
2894 }
2895
2896 static void
2897 gstring_append_int (GString *gstring,
2898                     guint32  vuint)
2899 {
2900   vuint = g_htonl (vuint);
2901   g_string_append_len (gstring, (const gchar*) &vuint, 4);
2902 }
2903
2904 static void
2905 gstring_append_double (GString *gstring,
2906                        double   vdouble)
2907 {
2908   union { double vdouble; guint64 vuint64; } u;
2909   u.vdouble = vdouble;
2910   u.vuint64 = GUINT64_TO_BE (u.vuint64);
2911   g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
2912 }
2913
2914 static guint8*
2915 g_test_log_dump (GTestLogMsg *msg,
2916                  guint       *len)
2917 {
2918   GString *gstring = g_string_sized_new (1024);
2919   guint ui;
2920   gstring_append_int (gstring, 0);              /* message length */
2921   gstring_append_int (gstring, msg->log_type);
2922   gstring_append_int (gstring, msg->n_strings);
2923   gstring_append_int (gstring, msg->n_nums);
2924   gstring_append_int (gstring, 0);      /* reserved */
2925   for (ui = 0; ui < msg->n_strings; ui++)
2926     {
2927       guint l = strlen (msg->strings[ui]);
2928       gstring_append_int (gstring, l);
2929       g_string_append_len (gstring, msg->strings[ui], l);
2930     }
2931   for (ui = 0; ui < msg->n_nums; ui++)
2932     gstring_append_double (gstring, msg->nums[ui]);
2933   *len = gstring->len;
2934   gstring_overwrite_int (gstring, 0, *len);     /* message length */
2935   return (guint8*) g_string_free (gstring, FALSE);
2936 }
2937
2938 static inline long double
2939 net_double (const gchar **ipointer)
2940 {
2941   union { guint64 vuint64; double vdouble; } u;
2942   guint64 aligned_int64;
2943   memcpy (&aligned_int64, *ipointer, 8);
2944   *ipointer += 8;
2945   u.vuint64 = GUINT64_FROM_BE (aligned_int64);
2946   return u.vdouble;
2947 }
2948
2949 static inline guint32
2950 net_int (const gchar **ipointer)
2951 {
2952   guint32 aligned_int;
2953   memcpy (&aligned_int, *ipointer, 4);
2954   *ipointer += 4;
2955   return g_ntohl (aligned_int);
2956 }
2957
2958 static gboolean
2959 g_test_log_extract (GTestLogBuffer *tbuffer)
2960 {
2961   const gchar *p = tbuffer->data->str;
2962   GTestLogMsg msg;
2963   guint mlength;
2964   if (tbuffer->data->len < 4 * 5)
2965     return FALSE;
2966   mlength = net_int (&p);
2967   if (tbuffer->data->len < mlength)
2968     return FALSE;
2969   msg.log_type = net_int (&p);
2970   msg.n_strings = net_int (&p);
2971   msg.n_nums = net_int (&p);
2972   if (net_int (&p) == 0)
2973     {
2974       guint ui;
2975       msg.strings = g_new0 (gchar*, msg.n_strings + 1);
2976       msg.nums = g_new0 (long double, msg.n_nums);
2977       for (ui = 0; ui < msg.n_strings; ui++)
2978         {
2979           guint sl = net_int (&p);
2980           msg.strings[ui] = g_strndup (p, sl);
2981           p += sl;
2982         }
2983       for (ui = 0; ui < msg.n_nums; ui++)
2984         msg.nums[ui] = net_double (&p);
2985       if (p <= tbuffer->data->str + mlength)
2986         {
2987           g_string_erase (tbuffer->data, 0, mlength);
2988           tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
2989           return TRUE;
2990         }
2991     }
2992   g_free (msg.nums);
2993   g_strfreev (msg.strings);
2994   g_error ("corrupt log stream from test program");
2995   return FALSE;
2996 }
2997
2998 /**
2999  * g_test_log_buffer_new:
3000  *
3001  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3002  */
3003 GTestLogBuffer*
3004 g_test_log_buffer_new (void)
3005 {
3006   GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
3007   tb->data = g_string_sized_new (1024);
3008   return tb;
3009 }
3010
3011 /**
3012  * g_test_log_buffer_free:
3013  *
3014  * Internal function for gtester to free test log messages, no ABI guarantees provided.
3015  */
3016 void
3017 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
3018 {
3019   g_return_if_fail (tbuffer != NULL);
3020   while (tbuffer->msgs)
3021     g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
3022   g_string_free (tbuffer->data, TRUE);
3023   g_free (tbuffer);
3024 }
3025
3026 /**
3027  * g_test_log_buffer_push:
3028  *
3029  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
3030  */
3031 void
3032 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
3033                         guint           n_bytes,
3034                         const guint8   *bytes)
3035 {
3036   g_return_if_fail (tbuffer != NULL);
3037   if (n_bytes)
3038     {
3039       gboolean more_messages;
3040       g_return_if_fail (bytes != NULL);
3041       g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
3042       do
3043         more_messages = g_test_log_extract (tbuffer);
3044       while (more_messages);
3045     }
3046 }
3047
3048 /**
3049  * g_test_log_buffer_pop:
3050  *
3051  * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
3052  */
3053 GTestLogMsg*
3054 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
3055 {
3056   GTestLogMsg *msg = NULL;
3057   g_return_val_if_fail (tbuffer != NULL, NULL);
3058   if (tbuffer->msgs)
3059     {
3060       GSList *slist = g_slist_last (tbuffer->msgs);
3061       msg = slist->data;
3062       tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
3063     }
3064   return msg;
3065 }
3066
3067 /**
3068  * g_test_log_msg_free:
3069  *
3070  * Internal function for gtester to free test log messages, no ABI guarantees provided.
3071  */
3072 void
3073 g_test_log_msg_free (GTestLogMsg *tmsg)
3074 {
3075   g_return_if_fail (tmsg != NULL);
3076   g_strfreev (tmsg->strings);
3077   g_free (tmsg->nums);
3078   g_free (tmsg);
3079 }
3080
3081 static gchar *
3082 g_test_build_filename_va (GTestFileType  file_type,
3083                           const gchar   *first_path,
3084                           va_list        ap)
3085 {
3086   const gchar *pathv[16];
3087   gint num_path_segments;
3088
3089   if (file_type == G_TEST_DIST)
3090     pathv[0] = test_disted_files_dir;
3091   else if (file_type == G_TEST_BUILT)
3092     pathv[0] = test_built_files_dir;
3093   else
3094     g_assert_not_reached ();
3095
3096   pathv[1] = first_path;
3097
3098   for (num_path_segments = 2; num_path_segments < G_N_ELEMENTS (pathv); num_path_segments++)
3099     {
3100       pathv[num_path_segments] = va_arg (ap, const char *);
3101       if (pathv[num_path_segments] == NULL)
3102         break;
3103     }
3104
3105   g_assert_cmpint (num_path_segments, <, G_N_ELEMENTS (pathv));
3106
3107   return g_build_filenamev ((gchar **) pathv);
3108 }
3109
3110 /**
3111  * g_test_build_filename:
3112  * @file_type: the type of file (built vs. distributed)
3113  * @first_path: the first segment of the pathname
3114  * @...: %NULL-terminated additional path segments
3115  *
3116  * Creates the pathname to a data file that is required for a test.
3117  *
3118  * This function is conceptually similar to g_build_filename() except
3119  * that the first argument has been replaced with a #GTestFileType
3120  * argument.
3121  *
3122  * The data file should either have been distributed with the module
3123  * containing the test (%G_TEST_DIST) or built as part of the build
3124  * system of that module (%G_TEST_BUILT).
3125  *
3126  * In order for this function to work in srcdir != builddir situations,
3127  * the G_TEST_SRCDIR and G_TEST_BUILDDIR environment variables need to
3128  * have been defined.  As of 2.38, this is done by the Makefile.decl
3129  * included in GLib.  Please ensure that your copy is up to date before
3130  * using this function.
3131  *
3132  * In case neither variable is set, this function will fall back to
3133  * using the dirname portion of argv[0], possibly removing ".libs".
3134  * This allows for casual running of tests directly from the commandline
3135  * in the srcdir == builddir case and should also support running of
3136  * installed tests, assuming the data files have been installed in the
3137  * same relative path as the test binary.
3138  *
3139  * Returns: the path of the file, to be freed using g_free()
3140  *
3141  * Since: 2.38
3142  **/
3143 /**
3144  * GTestFileType:
3145  * @G_TEST_DIST: a file that was included in the distribution tarball
3146  * @G_TEST_BUILT: a file that was built on the compiling machine
3147  *
3148  * The type of file to return the filename for, when used with
3149  * g_test_build_filename().
3150  *
3151  * These two options correspond rather directly to the 'dist' and
3152  * 'built' terminology that automake uses and are explicitly used to
3153  * distinguish between the 'srcdir' and 'builddir' being separate.  All
3154  * files in your project should either be dist (in the
3155  * <literal>DIST_EXTRA</literal> or <literal>dist_schema_DATA</literal>
3156  * sense, in which case they will always be in the srcdir) or built (in
3157  * the <literal>BUILT_SOURCES</literal> sense, in which case they will
3158  * always be in the builddir).
3159  *
3160  * Note: as a general rule of automake, files that are generated only as
3161  * part of the build-from-git process (but then are distributed with the
3162  * tarball) always go in srcdir (even if doing a srcdir != builddir
3163  * build from git) and are considered as distributed files.
3164  *
3165  * Since: 2.38
3166  **/
3167 gchar *
3168 g_test_build_filename (GTestFileType  file_type,
3169                        const gchar   *first_path,
3170                        ...)
3171 {
3172   gchar *result;
3173   va_list ap;
3174
3175   g_assert (g_test_initialized ());
3176
3177   va_start (ap, first_path);
3178   result = g_test_build_filename_va (file_type, first_path, ap);
3179   va_end (ap);
3180
3181   return result;
3182 }
3183
3184 /**
3185  * g_test_get_dir:
3186  * @file_type: the type of file (built vs. distributed)
3187  *
3188  * Gets the pathname of the directory containing test files of the type
3189  * specified by @file_type.
3190  *
3191  * This is approximately the same as calling g_test_build_filename("."),
3192  * but you don't need to free the return value.
3193  *
3194  * Returns: the path of the directory, owned by GLib
3195  *
3196  * Since: 2.38
3197  **/
3198 const gchar *
3199 g_test_get_dir (GTestFileType file_type)
3200 {
3201   g_assert (g_test_initialized ());
3202
3203   if (file_type == G_TEST_DIST)
3204     return test_disted_files_dir;
3205   else if (file_type == G_TEST_BUILT)
3206     return test_built_files_dir;
3207
3208   g_assert_not_reached ();
3209 }
3210
3211 /**
3212  * g_test_get_filename:
3213  * @file_type: the type of file (built vs. distributed)
3214  * @first_path: the first segment of the pathname
3215  * @...: %NULL-terminated additional path segments
3216  *
3217  * Gets the pathname to a data file that is required for a test.
3218  *
3219  * This is the same as g_test_build_filename() with two differences.
3220  * The first difference is that must only use this function from within
3221  * a testcase function.  The second difference is that you need not free
3222  * the return value -- it will be automatically freed when the testcase
3223  * finishes running.
3224  *
3225  * It is safe to use this function from a thread inside of a testcase
3226  * but you must ensure that all such uses occur before the main testcase
3227  * function returns (ie: it is best to ensure that all threads have been
3228  * joined).
3229  *
3230  * Returns: the path, automatically freed at the end of the testcase
3231  *
3232  * Since: 2.38
3233  **/
3234 const gchar *
3235 g_test_get_filename (GTestFileType  file_type,
3236                      const gchar   *first_path,
3237                      ...)
3238 {
3239   gchar *result;
3240   GSList *node;
3241   va_list ap;
3242
3243   g_assert (g_test_initialized ());
3244   if (test_filename_free_list == NULL)
3245     g_error ("g_test_get_filename() can only be used within testcase functions");
3246
3247   va_start (ap, first_path);
3248   result = g_test_build_filename_va (file_type, first_path, ap);
3249   va_end (ap);
3250
3251   node = g_slist_prepend (NULL, result);
3252   do
3253     node->next = *test_filename_free_list;
3254   while (!g_atomic_pointer_compare_and_exchange (test_filename_free_list, node->next, node));
3255
3256   return result;
3257 }
3258
3259 /* --- macros docs START --- */
3260 /**
3261  * g_test_add:
3262  * @testpath:  The test path for a new test case.
3263  * @Fixture:   The type of a fixture data structure.
3264  * @tdata:     Data argument for the test functions.
3265  * @fsetup:    The function to set up the fixture data.
3266  * @ftest:     The actual test function.
3267  * @fteardown: The function to tear down the fixture data.
3268  *
3269  * Hook up a new test case at @testpath, similar to g_test_add_func().
3270  * A fixture data structure with setup and teardown function may be provided
3271  * though, similar to g_test_create_case().
3272  * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
3273  * fteardown() callbacks can expect a @Fixture pointer as first argument in
3274  * a type safe manner.
3275  *
3276  * Since: 2.16
3277  **/
3278 /* --- macros docs END --- */