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