added g_test_trap_assert_stdout_unmatched() and
[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 #include "config.h"
21 #include "gtestutils.h"
22 #include "galias.h"
23 #include <sys/types.h>
24 #ifdef G_OS_UNIX
25 #include <sys/wait.h>
26 #include <fcntl.h>
27 #endif
28 #include <string.h>
29 #include <stdlib.h>
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
33 #ifdef G_OS_WIN32
34 #include <io.h>
35 #endif
36 #include <errno.h>
37 #include <signal.h>
38 #ifdef HAVE_SYS_SELECT_H
39 #include <sys/select.h>
40 #endif /* HAVE_SYS_SELECT_H */
41
42 /* --- structures --- */
43 struct GTestCase
44 {
45   gchar  *name;
46   guint   fixture_size;
47   void   (*fixture_setup)    (void*, gconstpointer);
48   void   (*fixture_test)     (void*, gconstpointer);
49   void   (*fixture_teardown) (void*, gconstpointer);
50   gpointer test_data;
51 };
52 struct GTestSuite
53 {
54   gchar  *name;
55   GSList *suites;
56   GSList *cases;
57 };
58 typedef struct DestroyEntry DestroyEntry;
59 struct DestroyEntry
60 {
61   DestroyEntry *next;
62   GDestroyNotify destroy_func;
63   gpointer       destroy_data;
64 };
65
66 /* --- prototypes --- */
67 static void                     test_run_seed           (const gchar *rseed);
68 static void                     test_trap_clear         (void);
69 static guint8*                  g_test_log_dump         (GTestLogMsg *msg,
70                                                          guint       *len);
71
72 /* --- variables --- */
73 static int         test_log_fd = -1;
74 static gboolean    test_mode_fatal = TRUE;
75 static gboolean    g_test_run_once = TRUE;
76 static gboolean    test_run_list = FALSE;
77 static gchar      *test_run_seedstr = NULL;
78 static GRand      *test_run_rand = NULL;
79 static gchar      *test_run_name = "";
80 static guint       test_run_forks = 0;
81 static guint       test_run_count = 0;
82 static guint       test_skip_count = 0;
83 static GTimer     *test_user_timer = NULL;
84 static double      test_user_stamp = 0;
85 static GSList     *test_paths = NULL;
86 static GTestSuite *test_suite_root = NULL;
87 static int         test_trap_last_status = 0;
88 static int         test_trap_last_pid = 0;
89 static char       *test_trap_last_stdout = NULL;
90 static char       *test_trap_last_stderr = NULL;
91 static char       *test_uri_base = NULL;
92 static gboolean    test_debug_log = FALSE;
93 static DestroyEntry *test_destroy_queue = NULL;
94 static GTestConfig mutable_test_config_vars = {
95   FALSE,        /* test_initialized */
96   TRUE,         /* test_quick */
97   FALSE,        /* test_perf */
98   FALSE,        /* test_verbose */
99   FALSE,        /* test_quiet */
100 };
101 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
102
103 /* --- functions --- */
104 const char*
105 g_test_log_type_name (GTestLogType log_type)
106 {
107   switch (log_type)
108     {
109     case G_TEST_LOG_NONE:               return "none";
110     case G_TEST_LOG_ERROR:              return "error";
111     case G_TEST_LOG_START_BINARY:       return "binary";
112     case G_TEST_LOG_LIST_CASE:          return "list";
113     case G_TEST_LOG_SKIP_CASE:          return "skip";
114     case G_TEST_LOG_START_CASE:         return "start";
115     case G_TEST_LOG_STOP_CASE:          return "stop";
116     case G_TEST_LOG_MIN_RESULT:         return "minperf";
117     case G_TEST_LOG_MAX_RESULT:         return "maxperf";
118     case G_TEST_LOG_MESSAGE:            return "message";
119     }
120   return "???";
121 }
122
123 static void
124 g_test_log_send (guint         n_bytes,
125                  const guint8 *buffer)
126 {
127   if (test_log_fd >= 0)
128     {
129       int r;
130       do
131         r = write (test_log_fd, buffer, n_bytes);
132       while (r < 0 && errno == EINTR);
133     }
134   if (test_debug_log)
135     {
136       GTestLogBuffer *lbuffer = g_test_log_buffer_new();
137       GTestLogMsg *msg;
138       guint ui;
139       g_test_log_buffer_push (lbuffer, n_bytes, buffer);
140       msg = g_test_log_buffer_pop (lbuffer);
141       g_assert (msg != NULL); /* FIXME: should be g_awrn_if_fail */
142       g_assert (lbuffer->data->len == 0); /* FIXME: should be g_awrn_if_fail */
143       g_test_log_buffer_free (lbuffer);
144       /* print message */
145       g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
146       for (ui = 0; ui < msg->n_strings; ui++)
147         g_printerr (":{%s}", msg->strings[ui]);
148       if (msg->n_nums)
149         {
150           g_printerr (":(");
151           for (ui = 0; ui < msg->n_nums; ui++)
152             g_printerr ("%s%.16Lg", ui ? ";" : "", msg->nums[ui]);
153           g_printerr (")");
154         }
155       g_printerr (":LOG*}\n");
156       g_test_log_msg_free (msg);
157     }
158 }
159
160 static void
161 g_test_log (GTestLogType lbit,
162             const gchar *string1,
163             const gchar *string2,
164             guint        n_args,
165             long double *largs)
166 {
167   gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
168   GTestLogMsg msg;
169   gchar *astrings[3] = { NULL, NULL, NULL };
170   guint8 *dbuffer;
171   guint32 dbufferlen;
172
173   switch (lbit)
174     {
175     case G_TEST_LOG_START_BINARY:
176       if (g_test_verbose())
177         g_print ("GTest: random seed: %s\n", string2);
178       break;
179     case G_TEST_LOG_STOP_CASE:
180       if (g_test_verbose())
181         g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
182       else if (!g_test_quiet())
183         g_print ("%s\n", fail ? "FAIL" : "OK");
184       if (fail && test_mode_fatal)
185         abort();
186       break;
187     case G_TEST_LOG_MIN_RESULT:
188       if (g_test_verbose())
189         g_print ("(MINPERF:%s)\n", string1);
190       break;
191     case G_TEST_LOG_MAX_RESULT:
192       if (g_test_verbose())
193         g_print ("(MAXPERF:%s)\n", string1);
194       break;
195     case G_TEST_LOG_MESSAGE:
196       if (g_test_verbose())
197         g_print ("(MSG: %s)\n", string1);
198       break;
199     default: ;
200     }
201
202   msg.log_type = lbit;
203   msg.n_strings = (string1 != NULL) + (string1 && string2);
204   msg.strings = astrings;
205   astrings[0] = (gchar*) string1;
206   astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
207   msg.n_nums = n_args;
208   msg.nums = largs;
209   dbuffer = g_test_log_dump (&msg, &dbufferlen);
210   g_test_log_send (dbufferlen, dbuffer);
211   g_free (dbuffer);
212
213   switch (lbit)
214     {
215     case G_TEST_LOG_START_CASE:
216       if (g_test_verbose())
217         g_print ("GTest: run: %s\n", string1);
218       else if (!g_test_quiet())
219         g_print ("%s: ", string1);
220       break;
221     default: ;
222     }
223 }
224
225 static void
226 parse_args (gint    *argc_p,
227             gchar ***argv_p)
228 {
229   guint argc = *argc_p;
230   gchar **argv = *argv_p;
231   guint i, e;
232   /* parse known args */
233   for (i = 1; i < argc; i++)
234     {
235       if (strcmp (argv[i], "--g-fatal-warnings") == 0)
236         {
237           GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
238           fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
239           g_log_set_always_fatal (fatal_mask);
240           argv[i] = NULL;
241         }
242       else if (strcmp (argv[i], "--keep-going") == 0 ||
243                strcmp (argv[i], "-k") == 0)
244         {
245           test_mode_fatal = FALSE;
246           argv[i] = NULL;
247         }
248       else if (strcmp (argv[i], "--debug-log") == 0)
249         {
250           test_debug_log = TRUE;
251           argv[i] = NULL;
252         }
253       else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
254         {
255           gchar *equal = argv[i] + 12;
256           if (*equal == '=')
257             test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
258           else if (i + 1 < argc)
259             {
260               argv[i++] = NULL;
261               test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
262             }
263           argv[i] = NULL;
264         }
265       else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
266         {
267           gchar *equal = argv[i] + 16;
268           if (*equal == '=')
269             test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
270           else if (i + 1 < argc)
271             {
272               argv[i++] = NULL;
273               test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
274             }
275           argv[i] = NULL;
276         }
277       else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
278         {
279           gchar *equal = argv[i] + 2;
280           if (*equal == '=')
281             test_paths = g_slist_prepend (test_paths, equal + 1);
282           else if (i + 1 < argc)
283             {
284               argv[i++] = NULL;
285               test_paths = g_slist_prepend (test_paths, argv[i]);
286             }
287           argv[i] = NULL;
288         }
289       else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
290         {
291           gchar *equal = argv[i] + 2;
292           const gchar *mode = "";
293           if (*equal == '=')
294             mode = equal + 1;
295           else if (i + 1 < argc)
296             {
297               argv[i++] = NULL;
298               mode = argv[i];
299             }
300           if (strcmp (mode, "perf") == 0)
301             mutable_test_config_vars.test_perf = TRUE;
302           else if (strcmp (mode, "slow") == 0)
303             mutable_test_config_vars.test_quick = FALSE;
304           else if (strcmp (mode, "thorough") == 0)
305             mutable_test_config_vars.test_quick = FALSE;
306           else if (strcmp (mode, "quick") == 0)
307             {
308               mutable_test_config_vars.test_quick = TRUE;
309               mutable_test_config_vars.test_perf = FALSE;
310             }
311           else
312             g_error ("unknown test mode: -m %s", mode);
313           argv[i] = NULL;
314         }
315       else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
316         {
317           mutable_test_config_vars.test_quiet = TRUE;
318           mutable_test_config_vars.test_verbose = FALSE;
319           argv[i] = NULL;
320         }
321       else if (strcmp ("--verbose", argv[i]) == 0)
322         {
323           mutable_test_config_vars.test_quiet = FALSE;
324           mutable_test_config_vars.test_verbose = TRUE;
325           argv[i] = NULL;
326         }
327       else if (strcmp ("-l", argv[i]) == 0)
328         {
329           test_run_list = TRUE;
330           argv[i] = NULL;
331         }
332       else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
333         {
334           gchar *equal = argv[i] + 6;
335           if (*equal == '=')
336             test_run_seedstr = equal + 1;
337           else if (i + 1 < argc)
338             {
339               argv[i++] = NULL;
340               test_run_seedstr = argv[i];
341             }
342           argv[i] = NULL;
343         }
344     }
345   /* collapse argv */
346   e = 1;
347   for (i = 1; i < argc; i++)
348     if (argv[i])
349       {
350         argv[e++] = argv[i];
351         if (i >= e)
352           argv[i] = NULL;
353       }
354   *argc_p = e;
355 }
356
357 /**
358  * g_test_init:
359  * @argc: Address of the @argc parameter of the main() function.
360  *        Changed if any arguments were handled.
361  * @argv: Address of the @argv parameter of main().
362  *        Any parameters understood by g_test_init() stripped before return.
363  *
364  * Initialize the GLib testing framework, e.g. by seeding the
365  * test random number generator, the name for g_get_prgname()
366  * and parsing test related command line args.
367  * So far, the following arguments are understood:
368  * <informalexample>
369  * -l                   list test cases available in a test executable.
370  * --seed RANDOMSEED    provide a random seed to reproduce test runs using random numbers.
371  * --verbose            run tests verbosely.
372  * -q, --quiet          run tests quietly.
373  * -p TESTPATH          execute all tests matching TESTPATH.
374  * -m {perf|slow|thorough|quick}
375  *                      execute tests according to these test modes:
376  *                      perf - performance tests, may take long and report results.
377  *                      slow - slow and thorough tests, may take quite long and maximize coverage.
378  *                      thorough - currently an alias for "slow".
379  *                      quick - quick tests, should run really quickly and give good coverage.
380  * --debug-log          debug test logging output.
381  * -k, --keep-going     gtester specific argument.
382  * --GTestLogFD N       gtester specific argument.
383  * --GTestSkipCount N   gtester specific argument.
384  * </informalexample>
385  */
386 void
387 g_test_init (int    *argc,
388              char ***argv,
389              ...)
390 {
391   static char seedstr[4 + 4 * 8 + 1];
392   va_list args;
393   gpointer vararg1;
394   /* make warnings and criticals fatal for all test programs */
395   GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
396   fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
397   g_log_set_always_fatal (fatal_mask);
398   /* check caller args */
399   g_return_if_fail (argc != NULL);
400   g_return_if_fail (argv != NULL);
401   g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
402   mutable_test_config_vars.test_initialized = TRUE;
403
404   va_start (args, argv);
405   vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
406   va_end (args);
407   g_return_if_fail (vararg1 == NULL);
408
409   /* setup random seed string */
410   g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
411   test_run_seedstr = seedstr;
412
413   /* parse args, sets up mode, changes seed, etc. */
414   parse_args (argc, argv);
415   if (!g_get_prgname())
416     g_set_prgname ((*argv)[0]);
417
418   /* verify GRand reliability, needed for reliable seeds */
419   if (1)
420     {
421       GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
422       guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
423       /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
424       if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
425         g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
426       g_rand_free (rg);
427     }
428
429   /* check rand seed */
430   test_run_seed (test_run_seedstr);
431
432   /* report program start */
433   g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
434 }
435
436 static void
437 test_run_seed (const gchar *rseed)
438 {
439   guint seed_failed = 0;
440   if (test_run_rand)
441     g_rand_free (test_run_rand);
442   test_run_rand = NULL;
443   while (strchr (" \t\v\r\n\f", *rseed))
444     rseed++;
445   if (strncmp (rseed, "R02S", 4) == 0)  /* seed for random generator 02 (GRand-2.2) */
446     {
447       const char *s = rseed + 4;
448       if (strlen (s) >= 32)             /* require 4 * 8 chars */
449         {
450           guint32 seedarray[4];
451           gchar *p, hexbuf[9] = { 0, };
452           memcpy (hexbuf, s + 0, 8);
453           seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
454           seed_failed += p != NULL && *p != 0;
455           memcpy (hexbuf, s + 8, 8);
456           seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
457           seed_failed += p != NULL && *p != 0;
458           memcpy (hexbuf, s + 16, 8);
459           seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
460           seed_failed += p != NULL && *p != 0;
461           memcpy (hexbuf, s + 24, 8);
462           seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
463           seed_failed += p != NULL && *p != 0;
464           if (!seed_failed)
465             {
466               test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
467               return;
468             }
469         }
470     }
471   g_error ("Unknown or invalid random seed: %s", rseed);
472 }
473
474 /**
475  * g_test_rand_int:
476  *
477  * Get a reproducable random integer number.
478  * The random numbers generate by the g_test_rand_*() family of functions
479  * change with every new test program start, unless the --seed option is
480  * given when starting test programs.
481  * For individual test cases however, the random number generator is
482  * reseeded, to avoid dependencies between tests and to make --seed
483  * effective for all test cases.
484  *
485  * Returns: a random number from the seeded random number generator.
486  */
487 gint32
488 g_test_rand_int (void)
489 {
490   return g_rand_int (test_run_rand);
491 }
492
493 /**
494  * g_test_rand_int_range:
495  * @begin: the minimum value returned by this function
496  * @end:   the smallest value not to be returned by this function
497  *
498  * Get a reproducable random integer number out of a specified range,
499  * see g_test_rand_int() for details on test case random numbers.
500  *
501  * Returns: a number with @begin <= number < @end.
502  */
503 gint32
504 g_test_rand_int_range (gint32          begin,
505                        gint32          end)
506 {
507   return g_rand_int_range (test_run_rand, begin, end);
508 }
509
510 /**
511  * g_test_rand_double:
512  *
513  * Get a reproducable random floating point number,
514  * see g_test_rand_int() for details on test case random numbers.
515  *
516  * Return a random number from the seeded random number generator.
517  */
518 double
519 g_test_rand_double (void)
520 {
521   return g_rand_double (test_run_rand);
522 }
523
524 /**
525  * g_test_rand_double_range:
526  * @range_start: the minimum value returned by this function
527  * @range_end: the minimum value not returned by this function
528  *
529  * Get a reproducable random floating pointer number out of a specified range,
530  * see g_test_rand_int() for details on test case random numbers.
531  *
532  * Returns: a number with @range_start <= number < @range_end.
533  */
534 double
535 g_test_rand_double_range (double          range_start,
536                           double          range_end)
537 {
538   return g_rand_double_range (test_run_rand, range_start, range_end);
539 }
540
541 /**
542  * g_test_timer_start:
543  *
544  * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
545  * to be done. Call this function again to restart the timer.
546  */
547 void
548 g_test_timer_start (void)
549 {
550   if (!test_user_timer)
551     test_user_timer = g_timer_new();
552   test_user_stamp = 0;
553   g_timer_start (test_user_timer);
554 }
555
556 /**
557  * g_test_timer_elapsed:
558  *
559  * Get the time since the last start of the timer with g_test_timer_start().
560  *
561  * Returns: the time since the last start of the timer, as a double
562  */
563 double
564 g_test_timer_elapsed (void)
565 {
566   test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
567   return test_user_stamp;
568 }
569
570 /**
571  * g_test_timer_last:
572  *
573  * Report the last result of g_test_timer_elapsed().
574  *
575  * Returns: the last result of g_test_timer_elapsed(), as a double
576  */
577 double
578 g_test_timer_last (void)
579 {
580   return test_user_stamp;
581 }
582
583 /**
584  * g_test_minimized_result:
585  * @minimized_quantity: the reported value
586  * @format: the format string of the report message
587  *
588  * Report the result of a performance or measurement test.
589  * The test should generally strive to minimize the reported
590  * quantities (smaller values are better than larger ones),
591  * this and @minimized_quantity can determine sorting
592  * order for test result reports.
593  */
594 void
595 g_test_minimized_result (double          minimized_quantity,
596                          const char     *format,
597                          ...)
598 {
599   long double largs = minimized_quantity;
600   gchar *buffer;
601   va_list args;
602   va_start (args, format);
603   buffer = g_strdup_vprintf (format, args);
604   va_end (args);
605   g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
606   g_free (buffer);
607 }
608
609 /**
610  * g_test_minimized_result:
611  * @maximized_quantity: the reported value
612  * @format: the format string of the report message
613  *
614  * Report the result of a performance or measurement test.
615  * The test should generally strive to maximize the reported
616  * quantities (larger values are better than smaller ones),
617  * this and @maximized_quantity can determine sorting
618  * order for test result reports.
619  */
620 void
621 g_test_maximized_result (double          maximized_quantity,
622                          const char     *format,
623                          ...)
624 {
625   long double largs = maximized_quantity;
626   gchar *buffer;
627   va_list args;
628   va_start (args, format);
629   buffer = g_strdup_vprintf (format, args);
630   va_end (args);
631   g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
632   g_free (buffer);
633 }
634
635 /**
636  * g_test_message:
637  * @format: the format string
638  * @...:    printf-like arguments to @format
639  *
640  * Add a message to the test report.
641  */
642 void
643 g_test_message (const char *format,
644                 ...)
645 {
646   gchar *buffer;
647   va_list args;
648   va_start (args, format);
649   buffer = g_strdup_vprintf (format, args);
650   va_end (args);
651   g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
652   g_free (buffer);
653 }
654
655 /**
656  * g_test_bug_base:
657  * @uri_pattern: the base pattern for bug URIs
658  *
659  * Specify the base URI for bug reports.
660  * The base URI is used to construct bug report messages for
661  * g_test_message() when g_test_bug() is called.
662  * Calling this function outside of a test case sets the
663  * default base URI for all test cases. Calling it from within
664  * a test case changes the base URI for the scope of the test
665  * case only.
666  * Bug URIs are constructed by appending a bug specific URI
667  * portion to @uri_pattern, or by replacing the special string
668  * '%s' within @uri_pattern if that is present.
669  */
670 void
671 g_test_bug_base (const char *uri_pattern)
672 {
673   g_free (test_uri_base);
674   test_uri_base = g_strdup (uri_pattern);
675 }
676
677 /**
678  * g_test_bug:
679  * @bug_uri_snippet: Bug specific bug tracker URI portion.
680  *
681  * This function adds a message to test reports that
682  * associates a bug URI with a test case.
683  * Bug URIs are constructed from a base URI set with g_test_bug_base()
684  * and @bug_uri_snippet.
685  */
686 void
687 g_test_bug (const char *bug_uri_snippet)
688 {
689   char *c;
690   g_return_if_fail (test_uri_base != NULL);
691   g_return_if_fail (bug_uri_snippet != NULL);
692   c = strstr (test_uri_base, "%s");
693   if (c)
694     {
695       char *b = g_strndup (test_uri_base, c - test_uri_base);
696       char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
697       g_free (b);
698       g_test_message ("Bug Reference: %s", s);
699       g_free (s);
700     }
701   else
702     g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
703 }
704
705 /**
706  * g_test_get_root:
707  *
708  * Get the toplevel test suite for the test path API.
709  *
710  * Returns: the toplevel #GTestSuite
711  */
712 GTestSuite*
713 g_test_get_root (void)
714 {
715   if (!test_suite_root)
716     {
717       test_suite_root = g_test_create_suite ("root");
718       g_free (test_suite_root->name);
719       test_suite_root->name = g_strdup ("");
720     }
721   return test_suite_root;
722 }
723
724 /**
725  * g_test_run:
726  *
727  * Runs all tests under the toplevel suite which can be retrieved
728  * with g_test_get_root(). Similar to g_test_run_suite(), the test
729  * cases to be run are filtered according to
730  * test path arguments (-p <testpath>) as parsed by g_test_init().
731  * g_test_run_suite() or g_test_run() may only be called once
732  * in a program.
733  *
734  * Returns: 0 on success
735  */
736 int
737 g_test_run (void)
738 {
739   return g_test_run_suite (g_test_get_root());
740 }
741
742 /**
743  * g_test_create_case:
744  * @test_name:     the name for the test case
745  * @data_size:     the size of the fixture data structure
746  * @test_data:     test data argument for the test functions
747  * @data_setup:    the function to set up the fixture data
748  * @data_test:     the actual test function
749  * @data_teardown: the function to teardown the fixture data
750  *
751  * Create a new #GTestCase, named @test_name, this API is fairly
752  * low level, calling g_test_add() or g_test_add_func() is preferable.
753  * When this test is executed, a fixture structure of size @data_size
754  * will be allocated and filled with 0s. Then data_setup() is called
755  * to initialize the fixture. After fixture setup, the actual test
756  * function data_test() is called. Once the test run completed, the
757  * fixture structure is torn down  by calling data_teardown() and
758  * after that the memory is released.
759  * Splitting up a test run into fixture setup, test function and
760  * fixture teardown is most usful if the same fixture is used for
761  * multiple tests. In this cases, g_test_create_case() will be
762  * called with the same fixture, but varying @test_name and
763  * @data_test arguments.
764  *
765  * Returns: a newly allocated #GTestCase.
766  */
767 GTestCase*
768 g_test_create_case (const char     *test_name,
769                     gsize           data_size,
770                     gconstpointer   test_data,
771                     void          (*data_setup) (void),
772                     void          (*data_test) (void),
773                     void          (*data_teardown) (void))
774 {
775   GTestCase *tc;
776   g_return_val_if_fail (test_name != NULL, NULL);
777   g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
778   g_return_val_if_fail (test_name[0] != 0, NULL);
779   g_return_val_if_fail (data_test != NULL, NULL);
780   tc = g_slice_new0 (GTestCase);
781   tc->name = g_strdup (test_name);
782   tc->test_data = (gpointer) test_data;
783   tc->fixture_size = data_size;
784   tc->fixture_setup = (void*) data_setup;
785   tc->fixture_test = (void*) data_test;
786   tc->fixture_teardown = (void*) data_teardown;
787   return tc;
788 }
789
790 void
791 g_test_add_vtable (const char     *testpath,
792                    gsize           data_size,
793                    gconstpointer   test_data,
794                    void          (*data_setup)    (void),
795                    void          (*fixture_test_func) (void),
796                    void          (*data_teardown) (void))
797 {
798   gchar **segments;
799   guint ui;
800   GTestSuite *suite;
801
802   g_return_if_fail (testpath != NULL);
803   g_return_if_fail (testpath[0] == '/');
804   g_return_if_fail (fixture_test_func != NULL);
805
806   suite = g_test_get_root();
807   segments = g_strsplit (testpath, "/", -1);
808   for (ui = 0; segments[ui] != NULL; ui++)
809     {
810       const char *seg = segments[ui];
811       gboolean islast = segments[ui + 1] == NULL;
812       if (islast && !seg[0])
813         g_error ("invalid test case path: %s", testpath);
814       else if (!seg[0])
815         continue;       /* initial or duplicate slash */
816       else if (!islast)
817         {
818           GTestSuite *csuite = g_test_create_suite (seg);
819           g_test_suite_add_suite (suite, csuite);
820           suite = csuite;
821         }
822       else /* islast */
823         {
824           GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
825           g_test_suite_add (suite, tc);
826         }
827     }
828   g_strfreev (segments);
829 }
830
831 /**
832  * g_test_add_func:
833  * @testpath:   Slash seperated test case path name for the test.
834  * @test_func:  The test function to invoke for this test.
835  *
836  * Create a new test case, similar to g_test_create_case(). However
837  * the test is assumed to use no fixture, and test suites are automatically
838  * created on the fly and added to the root fixture, based on the
839  * slash seperated portions of @testpath.
840  */
841 void
842 g_test_add_func (const char     *testpath,
843                  void          (*test_func) (void))
844 {
845   g_return_if_fail (testpath != NULL);
846   g_return_if_fail (testpath[0] == '/');
847   g_return_if_fail (test_func != NULL);
848   g_test_add_vtable (testpath, 0, NULL, NULL, test_func, NULL);
849 }
850
851 /**
852  * g_test_add_data_func:
853  * @testpath:   Slash seperated test case path name for the test.
854  * @test_data:  Test data argument for the test function.
855  * @test_func:  The test function to invoke for this test.
856  *
857  * Create a new test case, similar to g_test_create_case(). However
858  * the test is assumed to use no fixture, and test suites are automatically
859  * created on the fly and added to the root fixture, based on the
860  * slash seperated portions of @testpath. The @test_data argument
861  * will be passed as first argument to @test_func.
862  */
863 void
864 g_test_add_data_func (const char     *testpath,
865                       gconstpointer   test_data,
866                       void          (*test_func) (gconstpointer))
867 {
868   g_return_if_fail (testpath != NULL);
869   g_return_if_fail (testpath[0] == '/');
870   g_return_if_fail (test_func != NULL);
871   g_test_add_vtable (testpath, 0, test_data, NULL, (void(*)(void)) test_func, NULL);
872 }
873
874 /**
875  * g_test_create_suite:
876  * @suite_name: a name for the suite
877  *
878  * Create a new test suite with the name @suite_name.
879  *
880  * Returns: A newly allocated #GTestSuite instance.
881  */
882 GTestSuite*
883 g_test_create_suite (const char *suite_name)
884 {
885   GTestSuite *ts;
886   g_return_val_if_fail (suite_name != NULL, NULL);
887   g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
888   g_return_val_if_fail (suite_name[0] != 0, NULL);
889   ts = g_slice_new0 (GTestSuite);
890   ts->name = g_strdup (suite_name);
891   return ts;
892 }
893
894 /**
895  * g_test_suite_add:
896  * @suite: a #GTestSuite
897  * @test_case: a #GTestCase
898  *
899  * Adds @test_case to @suite.
900  */
901 void
902 g_test_suite_add (GTestSuite     *suite,
903                   GTestCase      *test_case)
904 {
905   g_return_if_fail (suite != NULL);
906   g_return_if_fail (test_case != NULL);
907   suite->cases = g_slist_prepend (suite->cases, test_case);
908 }
909
910 /**
911  * g_test_suite_add_suite:
912  * @suite:       a #GTestSuite
913  * @nestedsuite: another #GTestSuite
914  *
915  * Adds @nestedsuite to @suite.
916  */
917 void
918 g_test_suite_add_suite (GTestSuite     *suite,
919                         GTestSuite     *nestedsuite)
920 {
921   g_return_if_fail (suite != NULL);
922   g_return_if_fail (nestedsuite != NULL);
923   suite->suites = g_slist_prepend (suite->suites, nestedsuite);
924 }
925
926 /**
927  * g_test_queue_free:
928  * @gfree_pointer: the pointer to be stored.
929  *
930  * Enqueue a pointer to be released with g_free() during the next
931  * teardown phase. This is equivalent to calling g_test_queue_destroy()
932  * with a destroy callback of g_free().
933  */
934 void
935 g_test_queue_free (gpointer gfree_pointer)
936 {
937   if (gfree_pointer)
938     g_test_queue_destroy (g_free, gfree_pointer);
939 }
940
941 /**
942  * g_test_queue_destroy:
943  * @destroy_func:       Destroy callback for teardown phase.
944  * @destroy_data:       Destroy callback data.
945  *
946  * This function enqueus a callback @destroy_func() to be executed
947  * during the next test case teardown phase. This is most useful
948  * to auto destruct allocted test resources at the end of a test run.
949  * Resources are released in reverse queue order, that means enqueueing
950  * callback A before callback B will cause B() to be called before
951  * A() during teardown.
952  */
953 void
954 g_test_queue_destroy (GDestroyNotify destroy_func,
955                       gpointer       destroy_data)
956 {
957   DestroyEntry *dentry;
958   g_return_if_fail (destroy_func != NULL);
959   dentry = g_slice_new0 (DestroyEntry);
960   dentry->destroy_func = destroy_func;
961   dentry->destroy_data = destroy_data;
962   dentry->next = test_destroy_queue;
963   test_destroy_queue = dentry;
964 }
965
966 static int
967 test_case_run (GTestCase *tc)
968 {
969   gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
970   test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
971   if (++test_run_count <= test_skip_count)
972     g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
973   else if (test_run_list)
974     {
975       g_print ("%s\n", test_run_name);
976       g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
977     }
978   else
979     {
980       GTimer *test_run_timer = g_timer_new();
981       long double largs[3];
982       void *fixture;
983       g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
984       test_run_forks = 0;
985       g_timer_start (test_run_timer);
986       fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
987       test_run_seed (test_run_seedstr);
988       if (tc->fixture_setup)
989         tc->fixture_setup (fixture, tc->test_data);
990       tc->fixture_test (fixture, tc->test_data);
991       test_trap_clear();
992       while (test_destroy_queue)
993         {
994           DestroyEntry *dentry = test_destroy_queue;
995           test_destroy_queue = dentry->next;
996           dentry->destroy_func (dentry->destroy_data);
997           g_slice_free (DestroyEntry, dentry);
998         }
999       if (tc->fixture_teardown)
1000         tc->fixture_teardown (fixture, tc->test_data);
1001       if (tc->fixture_size)
1002         g_free (fixture);
1003       g_timer_stop (test_run_timer);
1004       largs[0] = 0; /* OK */
1005       largs[1] = test_run_forks;
1006       largs[2] = g_timer_elapsed (test_run_timer, NULL);
1007       g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1008       g_timer_destroy (test_run_timer);
1009     }
1010   g_free (test_run_name);
1011   test_run_name = old_name;
1012   g_free (test_uri_base);
1013   test_uri_base = old_base;
1014   return 0;
1015 }
1016
1017 static int
1018 g_test_run_suite_internal (GTestSuite *suite,
1019                            const char *path)
1020 {
1021   guint n_bad = 0, n_good = 0, bad_suite = 0, l;
1022   gchar *rest, *old_name = test_run_name;
1023   GSList *slist, *reversed;
1024   g_return_val_if_fail (suite != NULL, -1);
1025   while (path[0] == '/')
1026     path++;
1027   l = strlen (path);
1028   rest = strchr (path, '/');
1029   l = rest ? MIN (l, rest - path) : l;
1030   test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1031   reversed = g_slist_reverse (g_slist_copy (suite->cases));
1032   for (slist = reversed; slist; slist = slist->next)
1033     {
1034       GTestCase *tc = slist->data;
1035       guint n = l ? strlen (tc->name) : 0;
1036       if (l == n && strncmp (path, tc->name, n) == 0)
1037         {
1038           n_good++;
1039           n_bad += test_case_run (tc) != 0;
1040         }
1041     }
1042   g_slist_free (reversed);
1043   reversed = g_slist_reverse (g_slist_copy (suite->suites));
1044   for (slist = reversed; slist; slist = slist->next)
1045     {
1046       GTestSuite *ts = slist->data;
1047       guint n = l ? strlen (ts->name) : 0;
1048       if (l == n && strncmp (path, ts->name, n) == 0)
1049         bad_suite += g_test_run_suite_internal (ts, rest ? rest : "") != 0;
1050     }
1051   g_slist_free (reversed);
1052   g_free (test_run_name);
1053   test_run_name = old_name;
1054   return n_bad || bad_suite;
1055 }
1056
1057 /**
1058  * g_test_run_suite:
1059  * @suite: a #GTestSuite
1060  *
1061  * Execute the tests within @suite and all nested #GTestSuites.
1062  * The test suites to be executed are filtered according to
1063  * test path arguments (-p <testpath>) as parsed by g_test_init().
1064  * g_test_run_suite() or g_test_run() may only be called once
1065  * in a program.
1066  *
1067  * Returns: 0 on success
1068  */
1069 int
1070 g_test_run_suite (GTestSuite *suite)
1071 {
1072   guint n_bad = 0;
1073   g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1074   g_return_val_if_fail (g_test_run_once == TRUE, -1);
1075   g_test_run_once = FALSE;
1076   if (!test_paths)
1077     test_paths = g_slist_prepend (test_paths, "");
1078   while (test_paths)
1079     {
1080       const char *rest, *path = test_paths->data;
1081       guint l, n = strlen (suite->name);
1082       test_paths = g_slist_delete_link (test_paths, test_paths);
1083       while (path[0] == '/')
1084         path++;
1085       if (!n) /* root suite, run unconditionally */
1086         {
1087           n_bad += 0 != g_test_run_suite_internal (suite, path);
1088           continue;
1089         }
1090       /* regular suite, match path */
1091       rest = strchr (path, '/');
1092       l = strlen (path);
1093       l = rest ? MIN (l, rest - path) : l;
1094       if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1095         n_bad += 0 != g_test_run_suite_internal (suite, rest ? rest : "");
1096     }
1097   return n_bad;
1098 }
1099
1100 void
1101 g_assertion_message (const char     *domain,
1102                      const char     *file,
1103                      int             line,
1104                      const char     *func,
1105                      const char     *message)
1106 {
1107   char lstr[32];
1108   char *s;
1109   if (!message)
1110     message = "code should not be reached";
1111   g_snprintf (lstr, 32, "%d", line);
1112   s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1113                    "ERROR:(", file, ":", lstr, "):",
1114                    func, func[0] ? ":" : "",
1115                    " ", message, NULL);
1116   g_printerr ("**\n** %s\n", s);
1117   g_free (s);
1118   abort();
1119 }
1120
1121 void
1122 g_assertion_message_expr (const char     *domain,
1123                           const char     *file,
1124                           int             line,
1125                           const char     *func,
1126                           const char     *expr)
1127 {
1128   char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1129   g_assertion_message (domain, file, line, func, s);
1130   g_free (s);
1131 }
1132
1133 void
1134 g_assertion_message_cmpnum (const char     *domain,
1135                             const char     *file,
1136                             int             line,
1137                             const char     *func,
1138                             const char     *expr,
1139                             long double     arg1,
1140                             const char     *cmp,
1141                             long double     arg2,
1142                             char            numtype)
1143 {
1144   char *s = NULL;
1145   switch (numtype)
1146     {
1147     case 'i':   s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
1148     case 'x':   s = g_strdup_printf ("assertion failed (%s): (0x%08" G_GUINT64_FORMAT " %s 0x%08" G_GUINT64_FORMAT ")", expr, (guint64) arg1, cmp, (guint64) arg2); break;
1149     case 'f':   s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
1150       /* ideally use: floats=%.7g double=%.17g */
1151     }
1152   g_assertion_message (domain, file, line, func, s);
1153   g_free (s);
1154 }
1155
1156 void
1157 g_assertion_message_cmpstr (const char     *domain,
1158                             const char     *file,
1159                             int             line,
1160                             const char     *func,
1161                             const char     *expr,
1162                             const char     *arg1,
1163                             const char     *cmp,
1164                             const char     *arg2)
1165 {
1166   char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1167   a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1168   a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1169   g_free (t1);
1170   g_free (t2);
1171   s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1172   g_free (a1);
1173   g_free (a2);
1174   g_assertion_message (domain, file, line, func, s);
1175   g_free (s);
1176 }
1177
1178 /**
1179  * g_strcmp0:
1180  * @str1: a C string or %NULL
1181  * @str2: another C string or %NULL
1182  *
1183  * Compares @str1 and @str2 like strcmp(). Handles %NULL strings gracefully.
1184  */
1185 int
1186 g_strcmp0 (const char     *str1,
1187            const char     *str2)
1188 {
1189   if (!str1)
1190     return -(str1 != str2);
1191   if (!str2)
1192     return str1 != str2;
1193   return strcmp (str1, str2);
1194 }
1195
1196 #ifdef G_OS_UNIX
1197 static int /* 0 on success */
1198 kill_child (int  pid,
1199             int *status,
1200             int  patience)
1201 {
1202   int wr;
1203   if (patience >= 3)    /* try graceful reap */
1204     {
1205       if (waitpid (pid, status, WNOHANG) > 0)
1206         return 0;
1207     }
1208   if (patience >= 2)    /* try SIGHUP */
1209     {
1210       kill (pid, SIGHUP);
1211       if (waitpid (pid, status, WNOHANG) > 0)
1212         return 0;
1213       g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1214       if (waitpid (pid, status, WNOHANG) > 0)
1215         return 0;
1216       g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
1217       if (waitpid (pid, status, WNOHANG) > 0)
1218         return 0;
1219       g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
1220       if (waitpid (pid, status, WNOHANG) > 0)
1221         return 0;
1222     }
1223   if (patience >= 1)    /* try SIGTERM */
1224     {
1225       kill (pid, SIGTERM);
1226       if (waitpid (pid, status, WNOHANG) > 0)
1227         return 0;
1228       g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
1229       if (waitpid (pid, status, WNOHANG) > 0)
1230         return 0;
1231       g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
1232       if (waitpid (pid, status, WNOHANG) > 0)
1233         return 0;
1234     }
1235   /* finish it off */
1236   kill (pid, SIGKILL);
1237   do
1238     wr = waitpid (pid, status, 0);
1239   while (wr < 0 && errno == EINTR);
1240   return wr;
1241 }
1242 #endif
1243
1244 static inline int
1245 g_string_must_read (GString *gstring,
1246                     int      fd)
1247 {
1248 #define STRING_BUFFER_SIZE     4096
1249   char buf[STRING_BUFFER_SIZE];
1250   gssize bytes;
1251  again:
1252   bytes = read (fd, buf, sizeof (buf));
1253   if (bytes == 0)
1254     return 0; /* EOF, calling this function assumes data is available */
1255   else if (bytes > 0)
1256     {
1257       g_string_append_len (gstring, buf, bytes);
1258       return 1;
1259     }
1260   else if (bytes < 0 && errno == EINTR)
1261     goto again;
1262   else /* bytes < 0 */
1263     {
1264       g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1265       return 1; /* ignore error after warning */
1266     }
1267 }
1268
1269 static inline void
1270 g_string_write_out (GString *gstring,
1271                     int      outfd,
1272                     int     *stringpos)
1273 {
1274   if (*stringpos < gstring->len)
1275     {
1276       int r;
1277       do
1278         r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
1279       while (r < 0 && errno == EINTR);
1280       *stringpos += MAX (r, 0);
1281     }
1282 }
1283
1284 static int
1285 sane_dup2 (int fd1,
1286            int fd2)
1287 {
1288   int ret;
1289   do
1290     ret = dup2 (fd1, fd2);
1291   while (ret < 0 && errno == EINTR);
1292   return ret;
1293 }
1294
1295 static void
1296 test_trap_clear (void)
1297 {
1298   test_trap_last_status = 0;
1299   test_trap_last_pid = 0;
1300   g_free (test_trap_last_stdout);
1301   test_trap_last_stdout = NULL;
1302   g_free (test_trap_last_stderr);
1303   test_trap_last_stderr = NULL;
1304 }
1305
1306 static guint64
1307 test_time_stamp (void)
1308 {
1309   GTimeVal tv;
1310   guint64 stamp;
1311   g_get_current_time (&tv);
1312   stamp = tv.tv_sec;
1313   stamp = stamp * 1000000 + tv.tv_usec;
1314   return stamp;
1315 }
1316
1317 /**
1318  * g_test_trap_fork:
1319  * @usec_timeout:    Timeout for the forked test in micro seconds.
1320  * @test_trap_flags: Flags to modify forking behaviour.
1321  *
1322  * Fork the current test program to execute a test case that might
1323  * not return or that might abort. The forked test case is aborted
1324  * and considered failing if its run time exceeds @usec_timeout.
1325  * The forking behavior can be configured with the following flags:
1326  * %G_TEST_TRAP_SILENCE_STDOUT - redirect stdout of the test child
1327  * to /dev/null so it cannot be observed on the console during test
1328  * runs. The actual output is still captured though to allow later
1329  * tests with g_test_trap_assert_stdout().
1330  * %G_TEST_TRAP_SILENCE_STDERR - redirect stderr of the test child
1331  * to /dev/null so it cannot be observed on the console during test
1332  * runs. The actual output is still captured though to allow later
1333  * tests with g_test_trap_assert_stderr().
1334  * %G_TEST_TRAP_INHERIT_STDIN - if this flag is given, stdin of the
1335  * forked child process is shared with stdin of its parent process.
1336  * It is redirected to /dev/null otherwise.
1337  *
1338  * In the following example, the test code forks, the forked child
1339  * process produces some sample output and exits successfully.
1340  * The forking parent process then asserts successfull child program
1341  * termination and validates cihld program outputs.
1342  *
1343  * |[
1344  *   static void
1345  *   test_fork_patterns (void)
1346  *   {
1347  *     if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
1348  *       {
1349  *         g_print ("some stdout text: somagic17\n");
1350  *         g_printerr ("some stderr text: semagic43\n");
1351  *         exit (0); /&ast; successful test run &ast;/
1352  *       }
1353  *     g_test_trap_assert_passed();
1354  *     g_test_trap_assert_stdout ("*somagic17*");
1355  *     g_test_trap_assert_stderr ("*semagic43*");
1356  *   }
1357  * ]|
1358  *
1359  * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
1360  */
1361 gboolean
1362 g_test_trap_fork (guint64        usec_timeout,
1363                   GTestTrapFlags test_trap_flags)
1364 {
1365 #ifdef G_OS_UNIX
1366   int stdout_pipe[2] = { -1, -1 };
1367   int stderr_pipe[2] = { -1, -1 };
1368   int stdtst_pipe[2] = { -1, -1 };
1369   test_trap_clear();
1370   if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
1371     g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
1372   signal (SIGCHLD, SIG_DFL);
1373   test_trap_last_pid = fork ();
1374   if (test_trap_last_pid < 0)
1375     g_error ("failed to fork test program: %s", g_strerror (errno));
1376   if (test_trap_last_pid == 0)  /* child */
1377     {
1378       int fd0 = -1;
1379       close (stdout_pipe[0]);
1380       close (stderr_pipe[0]);
1381       close (stdtst_pipe[0]);
1382       if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
1383         fd0 = open ("/dev/null", O_RDONLY);
1384       if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
1385         g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
1386       if (fd0 >= 3)
1387         close (fd0);
1388       if (stdout_pipe[1] >= 3)
1389         close (stdout_pipe[1]);
1390       if (stderr_pipe[1] >= 3)
1391         close (stderr_pipe[1]);
1392       test_log_fd = stdtst_pipe[1];
1393       return TRUE;
1394     }
1395   else                          /* parent */
1396     {
1397       GString *sout = g_string_new (NULL);
1398       GString *serr = g_string_new (NULL);
1399       guint64 sstamp;
1400       int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
1401       test_run_forks++;
1402       close (stdout_pipe[1]);
1403       close (stderr_pipe[1]);
1404       close (stdtst_pipe[1]);
1405       sstamp = test_time_stamp();
1406       /* read data until we get EOF on all pipes */
1407       while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
1408         {
1409           fd_set fds;
1410           struct timeval tv;
1411           FD_ZERO (&fds);
1412           if (stdout_pipe[0] >= 0)
1413             FD_SET (stdout_pipe[0], &fds);
1414           if (stderr_pipe[0] >= 0)
1415             FD_SET (stderr_pipe[0], &fds);
1416           if (stdtst_pipe[0] >= 0)
1417             FD_SET (stdtst_pipe[0], &fds);
1418           tv.tv_sec = 0;
1419           tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
1420           int ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
1421           if (ret < 0 && errno != EINTR)
1422             {
1423               g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1424               break;
1425             }
1426           if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
1427               g_string_must_read (sout, stdout_pipe[0]) == 0)
1428             {
1429               close (stdout_pipe[0]);
1430               stdout_pipe[0] = -1;
1431             }
1432           if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
1433               g_string_must_read (serr, stderr_pipe[0]) == 0)
1434             {
1435               close (stderr_pipe[0]);
1436               stderr_pipe[0] = -1;
1437             }
1438           if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
1439             {
1440               guint8 buffer[4096];
1441               gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
1442               if (r > 0 && test_log_fd > 0)
1443                 do
1444                   l = write (test_log_fd, buffer, r);
1445                 while (l < 0 && errno == EINTR);
1446               if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
1447                 {
1448                   close (stdtst_pipe[0]);
1449                   stdtst_pipe[0] = -1;
1450                 }
1451             }
1452           if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
1453             g_string_write_out (sout, 1, &soutpos);
1454           if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
1455             g_string_write_out (serr, 2, &serrpos);
1456           if (usec_timeout)
1457             {
1458               guint64 nstamp = test_time_stamp();
1459               int status = 0;
1460               sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
1461               if (usec_timeout < nstamp - sstamp)
1462                 {
1463                   /* timeout reached, need to abort the child now */
1464                   kill_child (test_trap_last_pid, &status, 3);
1465                   test_trap_last_status = 1024; /* timeout */
1466                   if (0 && WIFSIGNALED (status))
1467                     g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
1468                   need_wait = FALSE;
1469                   break;
1470                 }
1471             }
1472         }
1473       close (stdout_pipe[0]);
1474       close (stderr_pipe[0]);
1475       close (stdtst_pipe[0]);
1476       if (need_wait)
1477         {
1478           int status = 0;
1479           do
1480             wr = waitpid (test_trap_last_pid, &status, 0);
1481           while (wr < 0 && errno == EINTR);
1482           if (WIFEXITED (status)) /* normal exit */
1483             test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
1484           else if (WIFSIGNALED (status))
1485             test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
1486           else /* WCOREDUMP (status) */
1487             test_trap_last_status = 512; /* coredump */
1488         }
1489       test_trap_last_stdout = g_string_free (sout, FALSE);
1490       test_trap_last_stderr = g_string_free (serr, FALSE);
1491       return FALSE;
1492     }
1493 #else
1494   g_error ("Not implemented: g_test_trap_fork");
1495 #endif
1496 }
1497
1498 /**
1499  * g_test_trap_has_passed:
1500  *
1501  * Check the reuslt of the last g_test_trap_fork() call.
1502  *
1503  * Returns: %TRUE if the last forked child terminated successfully.
1504  */
1505 gboolean
1506 g_test_trap_has_passed (void)
1507 {
1508   return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
1509 }
1510
1511 /**
1512  * g_test_trap_reached_timeout:
1513  *
1514  * Check the reuslt of the last g_test_trap_fork() call.
1515  *
1516  * Returns: %TRUE if the last forked child got killed due to a fork timeout.
1517  */
1518 gboolean
1519 g_test_trap_reached_timeout (void)
1520 {
1521   return 0 != (test_trap_last_status & 1024); /* timeout flag */
1522 }
1523
1524 void
1525 g_test_trap_assertions (const char     *domain,
1526                         const char     *file,
1527                         int             line,
1528                         const char     *func,
1529                         guint64         assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
1530                         const char     *pattern)
1531 {
1532   gboolean must_pass = assertion_flags == 0;
1533   gboolean must_fail = assertion_flags == 1;
1534   gboolean match_result = 0 == (assertion_flags & 1);
1535   const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
1536   const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
1537   const char *match_error = match_result ? "failed to match" : "contains invalid match";
1538   if (test_trap_last_pid == 0)
1539     g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
1540   if (must_pass && !g_test_trap_has_passed())
1541     {
1542       char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
1543       g_assertion_message (domain, file, line, func, msg);
1544       g_free (msg);
1545     }
1546   if (must_fail && g_test_trap_has_passed())
1547     {
1548       char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
1549       g_assertion_message (domain, file, line, func, msg);
1550       g_free (msg);
1551     }
1552   if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
1553     {
1554       char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
1555       g_assertion_message (domain, file, line, func, msg);
1556       g_free (msg);
1557     }
1558   if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
1559     {
1560       char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
1561       g_assertion_message (domain, file, line, func, msg);
1562       g_free (msg);
1563     }
1564 }
1565
1566 static void
1567 gstring_overwrite_int (GString *gstring,
1568                        guint    pos,
1569                        guint32  vuint)
1570 {
1571   vuint = g_htonl (vuint);
1572   g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
1573 }
1574
1575 static void
1576 gstring_append_int (GString *gstring,
1577                     guint32  vuint)
1578 {
1579   vuint = g_htonl (vuint);
1580   g_string_append_len (gstring, (const gchar*) &vuint, 4);
1581 }
1582
1583 static void
1584 gstring_append_double (GString *gstring,
1585                        double   vdouble)
1586 {
1587   union { double vdouble; guint64 vuint64; } u;
1588   u.vdouble = vdouble;
1589   u.vuint64 = GUINT64_TO_BE (u.vuint64);
1590   g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
1591 }
1592
1593 static guint8*
1594 g_test_log_dump (GTestLogMsg *msg,
1595                  guint       *len)
1596 {
1597   GString *gstring = g_string_sized_new (1024);
1598   guint ui;
1599   gstring_append_int (gstring, 0);              /* message length */
1600   gstring_append_int (gstring, msg->log_type);
1601   gstring_append_int (gstring, msg->n_strings);
1602   gstring_append_int (gstring, msg->n_nums);
1603   gstring_append_int (gstring, 0);      /* reserved */
1604   for (ui = 0; ui < msg->n_strings; ui++)
1605     {
1606       guint l = strlen (msg->strings[ui]);
1607       gstring_append_int (gstring, l);
1608       g_string_append_len (gstring, msg->strings[ui], l);
1609     }
1610   for (ui = 0; ui < msg->n_nums; ui++)
1611     gstring_append_double (gstring, msg->nums[ui]);
1612   *len = gstring->len;
1613   gstring_overwrite_int (gstring, 0, *len);     /* message length */
1614   return (guint8*) g_string_free (gstring, FALSE);
1615 }
1616
1617 static inline long double
1618 net_double (const gchar **ipointer)
1619 {
1620   union { guint64 vuint64; double vdouble; } u;
1621   guint64 aligned_int64;
1622   memcpy (&aligned_int64, *ipointer, 8);
1623   *ipointer += 8;
1624   u.vuint64 = GUINT64_FROM_BE (aligned_int64);
1625   return u.vdouble;
1626 }
1627
1628 static inline guint32
1629 net_int (const gchar **ipointer)
1630 {
1631   guint32 aligned_int;
1632   memcpy (&aligned_int, *ipointer, 4);
1633   *ipointer += 4;
1634   return g_ntohl (aligned_int);
1635 }
1636
1637 static gboolean
1638 g_test_log_extract (GTestLogBuffer *tbuffer)
1639 {
1640   const gchar *p = tbuffer->data->str;
1641   GTestLogMsg msg;
1642   guint mlength;
1643   if (tbuffer->data->len < 4 * 5)
1644     return FALSE;
1645   mlength = net_int (&p);
1646   if (tbuffer->data->len < mlength)
1647     return FALSE;
1648   msg.log_type = net_int (&p);
1649   msg.n_strings = net_int (&p);
1650   msg.n_nums = net_int (&p);
1651   if (net_int (&p) == 0)
1652     {
1653       guint ui;
1654       msg.strings = g_new0 (gchar*, msg.n_strings + 1);
1655       msg.nums = g_new0 (long double, msg.n_nums);
1656       for (ui = 0; ui < msg.n_strings; ui++)
1657         {
1658           guint sl = net_int (&p);
1659           msg.strings[ui] = g_strndup (p, sl);
1660           p += sl;
1661         }
1662       for (ui = 0; ui < msg.n_nums; ui++)
1663         msg.nums[ui] = net_double (&p);
1664       if (p <= tbuffer->data->str + mlength)
1665         {
1666           g_string_erase (tbuffer->data, 0, mlength);
1667           tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
1668           return TRUE;
1669         }
1670     }
1671   g_free (msg.nums);
1672   g_strfreev (msg.strings);
1673   g_error ("corrupt log stream from test program");
1674   return FALSE;
1675 }
1676
1677 /**
1678  * g_test_log_buffer_new:
1679  *
1680  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1681  */
1682 GTestLogBuffer*
1683 g_test_log_buffer_new (void)
1684 {
1685   GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
1686   tb->data = g_string_sized_new (1024);
1687   return tb;
1688 }
1689
1690 /**
1691  * g_test_log_buffer_free
1692  *
1693  * Internal function for gtester to free test log messages, no ABI guarantees provided.
1694  */
1695 void
1696 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
1697 {
1698   g_return_if_fail (tbuffer != NULL);
1699   while (tbuffer->msgs)
1700     g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
1701   g_string_free (tbuffer->data, TRUE);
1702   g_free (tbuffer);
1703 }
1704
1705 /**
1706  * g_test_log_buffer_push
1707  *
1708  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1709  */
1710 void
1711 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
1712                         guint           n_bytes,
1713                         const guint8   *bytes)
1714 {
1715   g_return_if_fail (tbuffer != NULL);
1716   if (n_bytes)
1717     {
1718       gboolean more_messages;
1719       g_return_if_fail (bytes != NULL);
1720       g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
1721       do
1722         more_messages = g_test_log_extract (tbuffer);
1723       while (more_messages);
1724     }
1725 }
1726
1727 /**
1728  * g_test_log_buffer_pop:
1729  *
1730  * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
1731  */
1732 GTestLogMsg*
1733 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
1734 {
1735   GTestLogMsg *msg = NULL;
1736   g_return_val_if_fail (tbuffer != NULL, NULL);
1737   if (tbuffer->msgs)
1738     {
1739       GSList *slist = g_slist_last (tbuffer->msgs);
1740       msg = slist->data;
1741       tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
1742     }
1743   return msg;
1744 }
1745
1746 /**
1747  * g_test_log_msg_free:
1748  *
1749  * Internal function for gtester to free test log messages, no ABI guarantees provided.
1750  */
1751 void
1752 g_test_log_msg_free (GTestLogMsg *tmsg)
1753 {
1754   g_return_if_fail (tmsg != NULL);
1755   g_strfreev (tmsg->strings);
1756   g_free (tmsg->nums);
1757   g_free (tmsg);
1758 }
1759
1760 /* --- macros docs START --- */
1761 /**
1762  * g_test_add:
1763  * @testpath:  The test path for a new test case.
1764  * @Fixture:   The type of a fixture data structure.
1765  * @fsetup:    The function to set up the fixture data.
1766  * @ftest:     The actual test function.
1767  * @fteardown: The function to tear down the fixture data.
1768  *
1769  * Hook up a new test case at @testpath, similar to g_test_add_func().
1770  * A fixture data structure with setup and teardown function may be provided
1771  * though, simmilar to g_test_create_case().
1772  * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
1773  * fteardown() callbacks can expect a @Fixture pointer as first argument in
1774  * a type safe manner.
1775  **/
1776 /* --- macros docs END --- */
1777
1778 #define __G_TEST_UTILS_C__
1779 #include "galiasdef.c"