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