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