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