1 /* GLib testing utilities
2 * Copyright (C) 2007 Imendio AB
3 * Authors: Tim Janik, Sven Herzberg
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.
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.
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.
23 #include "gtestutils.h"
25 #include <sys/types.h>
42 #ifdef HAVE_SYS_SELECT_H
43 #include <sys/select.h>
44 #endif /* HAVE_SYS_SELECT_H */
49 #include "gstrfuncs.h"
54 /* Global variable for storing assertion messages; this is the counterpart to
55 * glibc's (private) __abort_msg variable, and allows developers and crash
56 * analysis systems like Apport and ABRT to fish out assertion messages from
57 * core dumps, instead of having to catch them on screen output. */
58 char *__glib_assert_msg
= NULL
;
60 /* --- structures --- */
65 void (*fixture_setup
) (void*, gconstpointer
);
66 void (*fixture_test
) (void*, gconstpointer
);
67 void (*fixture_teardown
) (void*, gconstpointer
);
76 typedef struct DestroyEntry DestroyEntry
;
80 GDestroyNotify destroy_func
;
81 gpointer destroy_data
;
84 /* --- prototypes --- */
85 static void test_run_seed (const gchar
*rseed
);
86 static void test_trap_clear (void);
87 static guint8
* g_test_log_dump (GTestLogMsg
*msg
,
89 static void gtest_default_log_handler (const gchar
*log_domain
,
90 GLogLevelFlags log_level
,
92 gpointer unused_data
);
95 /* --- variables --- */
96 static int test_log_fd
= -1;
97 static gboolean test_mode_fatal
= TRUE
;
98 static gboolean g_test_run_once
= TRUE
;
99 static gboolean test_run_list
= FALSE
;
100 static gchar
*test_run_seedstr
= NULL
;
101 static GRand
*test_run_rand
= NULL
;
102 static gchar
*test_run_name
= "";
103 static guint test_run_forks
= 0;
104 static guint test_run_count
= 0;
105 static guint test_skip_count
= 0;
106 static GTimer
*test_user_timer
= NULL
;
107 static double test_user_stamp
= 0;
108 static GSList
*test_paths
= NULL
;
109 static GTestSuite
*test_suite_root
= NULL
;
110 static int test_trap_last_status
= 0;
111 static int test_trap_last_pid
= 0;
112 static char *test_trap_last_stdout
= NULL
;
113 static char *test_trap_last_stderr
= NULL
;
114 static char *test_uri_base
= NULL
;
115 static gboolean test_debug_log
= FALSE
;
116 static DestroyEntry
*test_destroy_queue
= NULL
;
117 static GTestConfig mutable_test_config_vars
= {
118 FALSE
, /* test_initialized */
119 TRUE
, /* test_quick */
120 FALSE
, /* test_perf */
121 FALSE
, /* test_verbose */
122 FALSE
, /* test_quiet */
124 const GTestConfig
* const g_test_config_vars
= &mutable_test_config_vars
;
126 /* --- functions --- */
128 g_test_log_type_name (GTestLogType log_type
)
132 case G_TEST_LOG_NONE
: return "none";
133 case G_TEST_LOG_ERROR
: return "error";
134 case G_TEST_LOG_START_BINARY
: return "binary";
135 case G_TEST_LOG_LIST_CASE
: return "list";
136 case G_TEST_LOG_SKIP_CASE
: return "skip";
137 case G_TEST_LOG_START_CASE
: return "start";
138 case G_TEST_LOG_STOP_CASE
: return "stop";
139 case G_TEST_LOG_MIN_RESULT
: return "minperf";
140 case G_TEST_LOG_MAX_RESULT
: return "maxperf";
141 case G_TEST_LOG_MESSAGE
: return "message";
147 g_test_log_send (guint n_bytes
,
148 const guint8
*buffer
)
150 if (test_log_fd
>= 0)
154 r
= write (test_log_fd
, buffer
, n_bytes
);
155 while (r
< 0 && errno
== EINTR
);
159 GTestLogBuffer
*lbuffer
= g_test_log_buffer_new ();
162 g_test_log_buffer_push (lbuffer
, n_bytes
, buffer
);
163 msg
= g_test_log_buffer_pop (lbuffer
);
164 g_warn_if_fail (msg
!= NULL
);
165 g_warn_if_fail (lbuffer
->data
->len
== 0);
166 g_test_log_buffer_free (lbuffer
);
168 g_printerr ("{*LOG(%s)", g_test_log_type_name (msg
->log_type
));
169 for (ui
= 0; ui
< msg
->n_strings
; ui
++)
170 g_printerr (":{%s}", msg
->strings
[ui
]);
174 for (ui
= 0; ui
< msg
->n_nums
; ui
++)
175 g_printerr ("%s%.16Lg", ui
? ";" : "", msg
->nums
[ui
]);
178 g_printerr (":LOG*}\n");
179 g_test_log_msg_free (msg
);
184 g_test_log (GTestLogType lbit
,
185 const gchar
*string1
,
186 const gchar
*string2
,
190 gboolean fail
= lbit
== G_TEST_LOG_STOP_CASE
&& largs
[0] != 0;
192 gchar
*astrings
[3] = { NULL
, NULL
, NULL
};
198 case G_TEST_LOG_START_BINARY
:
199 if (g_test_verbose())
200 g_print ("GTest: random seed: %s\n", string2
);
202 case G_TEST_LOG_STOP_CASE
:
203 if (g_test_verbose())
204 g_print ("GTest: result: %s\n", fail
? "FAIL" : "OK");
205 else if (!g_test_quiet())
206 g_print ("%s\n", fail
? "FAIL" : "OK");
207 if (fail
&& test_mode_fatal
)
210 case G_TEST_LOG_MIN_RESULT
:
211 if (g_test_verbose())
212 g_print ("(MINPERF:%s)\n", string1
);
214 case G_TEST_LOG_MAX_RESULT
:
215 if (g_test_verbose())
216 g_print ("(MAXPERF:%s)\n", string1
);
218 case G_TEST_LOG_MESSAGE
:
219 if (g_test_verbose())
220 g_print ("(MSG: %s)\n", string1
);
226 msg
.n_strings
= (string1
!= NULL
) + (string1
&& string2
);
227 msg
.strings
= astrings
;
228 astrings
[0] = (gchar
*) string1
;
229 astrings
[1] = astrings
[0] ? (gchar
*) string2
: NULL
;
232 dbuffer
= g_test_log_dump (&msg
, &dbufferlen
);
233 g_test_log_send (dbufferlen
, dbuffer
);
238 case G_TEST_LOG_START_CASE
:
239 if (g_test_verbose())
240 g_print ("GTest: run: %s\n", string1
);
241 else if (!g_test_quiet())
242 g_print ("%s: ", string1
);
248 /* We intentionally parse the command line without GOptionContext
249 * because otherwise you would never be able to test it.
252 parse_args (gint
*argc_p
,
255 guint argc
= *argc_p
;
256 gchar
**argv
= *argv_p
;
258 /* parse known args */
259 for (i
= 1; i
< argc
; i
++)
261 if (strcmp (argv
[i
], "--g-fatal-warnings") == 0)
263 GLogLevelFlags fatal_mask
= (GLogLevelFlags
) g_log_set_always_fatal ((GLogLevelFlags
) G_LOG_FATAL_MASK
);
264 fatal_mask
= (GLogLevelFlags
) (fatal_mask
| G_LOG_LEVEL_WARNING
| G_LOG_LEVEL_CRITICAL
);
265 g_log_set_always_fatal (fatal_mask
);
268 else if (strcmp (argv
[i
], "--keep-going") == 0 ||
269 strcmp (argv
[i
], "-k") == 0)
271 test_mode_fatal
= FALSE
;
274 else if (strcmp (argv
[i
], "--debug-log") == 0)
276 test_debug_log
= TRUE
;
279 else if (strcmp ("--GTestLogFD", argv
[i
]) == 0 || strncmp ("--GTestLogFD=", argv
[i
], 13) == 0)
281 gchar
*equal
= argv
[i
] + 12;
283 test_log_fd
= g_ascii_strtoull (equal
+ 1, NULL
, 0);
284 else if (i
+ 1 < argc
)
287 test_log_fd
= g_ascii_strtoull (argv
[i
], NULL
, 0);
291 else if (strcmp ("--GTestSkipCount", argv
[i
]) == 0 || strncmp ("--GTestSkipCount=", argv
[i
], 17) == 0)
293 gchar
*equal
= argv
[i
] + 16;
295 test_skip_count
= g_ascii_strtoull (equal
+ 1, NULL
, 0);
296 else if (i
+ 1 < argc
)
299 test_skip_count
= g_ascii_strtoull (argv
[i
], NULL
, 0);
303 else if (strcmp ("-p", argv
[i
]) == 0 || strncmp ("-p=", argv
[i
], 3) == 0)
305 gchar
*equal
= argv
[i
] + 2;
307 test_paths
= g_slist_prepend (test_paths
, equal
+ 1);
308 else if (i
+ 1 < argc
)
311 test_paths
= g_slist_prepend (test_paths
, argv
[i
]);
315 else if (strcmp ("-m", argv
[i
]) == 0 || strncmp ("-m=", argv
[i
], 3) == 0)
317 gchar
*equal
= argv
[i
] + 2;
318 const gchar
*mode
= "";
321 else if (i
+ 1 < argc
)
326 if (strcmp (mode
, "perf") == 0)
327 mutable_test_config_vars
.test_perf
= TRUE
;
328 else if (strcmp (mode
, "slow") == 0)
329 mutable_test_config_vars
.test_quick
= FALSE
;
330 else if (strcmp (mode
, "thorough") == 0)
331 mutable_test_config_vars
.test_quick
= FALSE
;
332 else if (strcmp (mode
, "quick") == 0)
334 mutable_test_config_vars
.test_quick
= TRUE
;
335 mutable_test_config_vars
.test_perf
= FALSE
;
338 g_error ("unknown test mode: -m %s", mode
);
341 else if (strcmp ("-q", argv
[i
]) == 0 || strcmp ("--quiet", argv
[i
]) == 0)
343 mutable_test_config_vars
.test_quiet
= TRUE
;
344 mutable_test_config_vars
.test_verbose
= FALSE
;
347 else if (strcmp ("--verbose", argv
[i
]) == 0)
349 mutable_test_config_vars
.test_quiet
= FALSE
;
350 mutable_test_config_vars
.test_verbose
= TRUE
;
353 else if (strcmp ("-l", argv
[i
]) == 0)
355 test_run_list
= TRUE
;
358 else if (strcmp ("--seed", argv
[i
]) == 0 || strncmp ("--seed=", argv
[i
], 7) == 0)
360 gchar
*equal
= argv
[i
] + 6;
362 test_run_seedstr
= equal
+ 1;
363 else if (i
+ 1 < argc
)
366 test_run_seedstr
= argv
[i
];
370 else if (strcmp ("-?", argv
[i
]) == 0 || strcmp ("--help", argv
[i
]) == 0)
373 " %s [OPTION...]\n\n"
375 " -?, --help Show help options\n"
377 " -l List test cases available in a test executable\n"
378 " -seed=RANDOMSEED Provide a random seed to reproduce test\n"
379 " runs using random numbers\n"
380 " --verbose Run tests verbosely\n"
381 " -q, --quiet Run tests quietly\n"
382 " -p TESTPATH execute all tests matching TESTPATH\n"
383 " -m {perf|slow|thorough|quick} Execute tests according modes\n"
384 " --debug-log debug test logging output\n"
385 " -k, --keep-going gtester-specific argument\n"
386 " --GTestLogFD=N gtester-specific argument\n"
387 " --GTestSkipCount=N gtester-specific argument\n",
394 for (i
= 1; i
< argc
; i
++)
406 * @argc: Address of the @argc parameter of the main() function.
407 * Changed if any arguments were handled.
408 * @argv: Address of the @argv parameter of main().
409 * Any parameters understood by g_test_init() stripped before return.
410 * @Varargs: Reserved for future extension. Currently, you must pass %NULL.
412 * Initialize the GLib testing framework, e.g. by seeding the
413 * test random number generator, the name for g_get_prgname()
414 * and parsing test related command line args.
415 * So far, the following arguments are understood:
418 * <term><option>-l</option></term>
420 * list test cases available in a test executable.
424 * <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
426 * provide a random seed to reproduce test runs using random numbers.
430 * <term><option>--verbose</option></term>
431 * <listitem><para>run tests verbosely.</para></listitem>
434 * <term><option>-q</option>, <option>--quiet</option></term>
435 * <listitem><para>run tests quietly.</para></listitem>
438 * <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
440 * execute all tests matching <replaceable>TESTPATH</replaceable>.
444 * <term><option>-m {perf|slow|thorough|quick}</option></term>
446 * execute tests according to these test modes:
451 * performance tests, may take long and report results.
455 * <term>slow, thorough</term>
457 * slow and thorough tests, may take quite long and
464 * quick tests, should run really quickly and give good coverage.
471 * <term><option>--debug-log</option></term>
472 * <listitem><para>debug test logging output.</para></listitem>
475 * <term><option>-k</option>, <option>--keep-going</option></term>
476 * <listitem><para>gtester-specific argument.</para></listitem>
479 * <term><option>--GTestLogFD <replaceable>N</replaceable></option></term>
480 * <listitem><para>gtester-specific argument.</para></listitem>
483 * <term><option>--GTestSkipCount <replaceable>N</replaceable></option></term>
484 * <listitem><para>gtester-specific argument.</para></listitem>
491 g_test_init (int *argc
,
495 static char seedstr
[4 + 4 * 8 + 1];
498 /* make warnings and criticals fatal for all test programs */
499 GLogLevelFlags fatal_mask
= (GLogLevelFlags
) g_log_set_always_fatal ((GLogLevelFlags
) G_LOG_FATAL_MASK
);
500 fatal_mask
= (GLogLevelFlags
) (fatal_mask
| G_LOG_LEVEL_WARNING
| G_LOG_LEVEL_CRITICAL
);
501 g_log_set_always_fatal (fatal_mask
);
502 /* check caller args */
503 g_return_if_fail (argc
!= NULL
);
504 g_return_if_fail (argv
!= NULL
);
505 g_return_if_fail (g_test_config_vars
->test_initialized
== FALSE
);
506 mutable_test_config_vars
.test_initialized
= TRUE
;
508 va_start (args
, argv
);
509 vararg1
= va_arg (args
, gpointer
); /* reserved for future extensions */
511 g_return_if_fail (vararg1
== NULL
);
513 /* setup random seed string */
514 g_snprintf (seedstr
, sizeof (seedstr
), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
515 test_run_seedstr
= seedstr
;
517 /* parse args, sets up mode, changes seed, etc. */
518 parse_args (argc
, argv
);
519 if (!g_get_prgname())
520 g_set_prgname ((*argv
)[0]);
522 /* verify GRand reliability, needed for reliable seeds */
525 GRand
*rg
= g_rand_new_with_seed (0xc8c49fb6);
526 guint32 t1
= g_rand_int (rg
), t2
= g_rand_int (rg
), t3
= g_rand_int (rg
), t4
= g_rand_int (rg
);
527 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
528 if (t1
!= 0xfab39f9b || t2
!= 0xb948fb0e || t3
!= 0x3d31be26 || t4
!= 0x43a19d66)
529 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
533 /* check rand seed */
534 test_run_seed (test_run_seedstr
);
536 /* report program start */
537 g_log_set_default_handler (gtest_default_log_handler
, NULL
);
538 g_test_log (G_TEST_LOG_START_BINARY
, g_get_prgname(), test_run_seedstr
, 0, NULL
);
542 test_run_seed (const gchar
*rseed
)
544 guint seed_failed
= 0;
546 g_rand_free (test_run_rand
);
547 test_run_rand
= NULL
;
548 while (strchr (" \t\v\r\n\f", *rseed
))
550 if (strncmp (rseed
, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
552 const char *s
= rseed
+ 4;
553 if (strlen (s
) >= 32) /* require 4 * 8 chars */
555 guint32 seedarray
[4];
556 gchar
*p
, hexbuf
[9] = { 0, };
557 memcpy (hexbuf
, s
+ 0, 8);
558 seedarray
[0] = g_ascii_strtoull (hexbuf
, &p
, 16);
559 seed_failed
+= p
!= NULL
&& *p
!= 0;
560 memcpy (hexbuf
, s
+ 8, 8);
561 seedarray
[1] = g_ascii_strtoull (hexbuf
, &p
, 16);
562 seed_failed
+= p
!= NULL
&& *p
!= 0;
563 memcpy (hexbuf
, s
+ 16, 8);
564 seedarray
[2] = g_ascii_strtoull (hexbuf
, &p
, 16);
565 seed_failed
+= p
!= NULL
&& *p
!= 0;
566 memcpy (hexbuf
, s
+ 24, 8);
567 seedarray
[3] = g_ascii_strtoull (hexbuf
, &p
, 16);
568 seed_failed
+= p
!= NULL
&& *p
!= 0;
571 test_run_rand
= g_rand_new_with_seed_array (seedarray
, 4);
576 g_error ("Unknown or invalid random seed: %s", rseed
);
582 * Get a reproducible random integer number.
584 * The random numbers generated by the g_test_rand_*() family of functions
585 * change with every new test program start, unless the --seed option is
586 * given when starting test programs.
588 * For individual test cases however, the random number generator is
589 * reseeded, to avoid dependencies between tests and to make --seed
590 * effective for all test cases.
592 * Returns: a random number from the seeded random number generator.
597 g_test_rand_int (void)
599 return g_rand_int (test_run_rand
);
603 * g_test_rand_int_range:
604 * @begin: the minimum value returned by this function
605 * @end: the smallest value not to be returned by this function
607 * Get a reproducible random integer number out of a specified range,
608 * see g_test_rand_int() for details on test case random numbers.
610 * Returns: a number with @begin <= number < @end.
615 g_test_rand_int_range (gint32 begin
,
618 return g_rand_int_range (test_run_rand
, begin
, end
);
622 * g_test_rand_double:
624 * Get a reproducible random floating point number,
625 * see g_test_rand_int() for details on test case random numbers.
627 * Returns: a random number from the seeded random number generator.
632 g_test_rand_double (void)
634 return g_rand_double (test_run_rand
);
638 * g_test_rand_double_range:
639 * @range_start: the minimum value returned by this function
640 * @range_end: the minimum value not returned by this function
642 * Get a reproducible random floating pointer number out of a specified range,
643 * see g_test_rand_int() for details on test case random numbers.
645 * Returns: a number with @range_start <= number < @range_end.
650 g_test_rand_double_range (double range_start
,
653 return g_rand_double_range (test_run_rand
, range_start
, range_end
);
657 * g_test_timer_start:
659 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
660 * to be done. Call this function again to restart the timer.
665 g_test_timer_start (void)
667 if (!test_user_timer
)
668 test_user_timer
= g_timer_new();
670 g_timer_start (test_user_timer
);
674 * g_test_timer_elapsed:
676 * Get the time since the last start of the timer with g_test_timer_start().
678 * Returns: the time since the last start of the timer, as a double
683 g_test_timer_elapsed (void)
685 test_user_stamp
= test_user_timer
? g_timer_elapsed (test_user_timer
, NULL
) : 0;
686 return test_user_stamp
;
692 * Report the last result of g_test_timer_elapsed().
694 * Returns: the last result of g_test_timer_elapsed(), as a double
699 g_test_timer_last (void)
701 return test_user_stamp
;
705 * g_test_minimized_result:
706 * @minimized_quantity: the reported value
707 * @format: the format string of the report message
708 * @Varargs: arguments to pass to the printf() function
710 * Report the result of a performance or measurement test.
711 * The test should generally strive to minimize the reported
712 * quantities (smaller values are better than larger ones),
713 * this and @minimized_quantity can determine sorting
714 * order for test result reports.
719 g_test_minimized_result (double minimized_quantity
,
723 long double largs
= minimized_quantity
;
726 va_start (args
, format
);
727 buffer
= g_strdup_vprintf (format
, args
);
729 g_test_log (G_TEST_LOG_MIN_RESULT
, buffer
, NULL
, 1, &largs
);
734 * g_test_maximized_result:
735 * @maximized_quantity: the reported value
736 * @format: the format string of the report message
737 * @Varargs: arguments to pass to the printf() function
739 * Report the result of a performance or measurement test.
740 * The test should generally strive to maximize the reported
741 * quantities (larger values are better than smaller ones),
742 * this and @maximized_quantity can determine sorting
743 * order for test result reports.
748 g_test_maximized_result (double maximized_quantity
,
752 long double largs
= maximized_quantity
;
755 va_start (args
, format
);
756 buffer
= g_strdup_vprintf (format
, args
);
758 g_test_log (G_TEST_LOG_MAX_RESULT
, buffer
, NULL
, 1, &largs
);
764 * @format: the format string
765 * @...: printf-like arguments to @format
767 * Add a message to the test report.
772 g_test_message (const char *format
,
777 va_start (args
, format
);
778 buffer
= g_strdup_vprintf (format
, args
);
780 g_test_log (G_TEST_LOG_MESSAGE
, buffer
, NULL
, 0, NULL
);
786 * @uri_pattern: the base pattern for bug URIs
788 * Specify the base URI for bug reports.
790 * The base URI is used to construct bug report messages for
791 * g_test_message() when g_test_bug() is called.
792 * Calling this function outside of a test case sets the
793 * default base URI for all test cases. Calling it from within
794 * a test case changes the base URI for the scope of the test
796 * Bug URIs are constructed by appending a bug specific URI
797 * portion to @uri_pattern, or by replacing the special string
798 * '%s' within @uri_pattern if that is present.
803 g_test_bug_base (const char *uri_pattern
)
805 g_free (test_uri_base
);
806 test_uri_base
= g_strdup (uri_pattern
);
811 * @bug_uri_snippet: Bug specific bug tracker URI portion.
813 * This function adds a message to test reports that
814 * associates a bug URI with a test case.
815 * Bug URIs are constructed from a base URI set with g_test_bug_base()
816 * and @bug_uri_snippet.
821 g_test_bug (const char *bug_uri_snippet
)
824 g_return_if_fail (test_uri_base
!= NULL
);
825 g_return_if_fail (bug_uri_snippet
!= NULL
);
826 c
= strstr (test_uri_base
, "%s");
829 char *b
= g_strndup (test_uri_base
, c
- test_uri_base
);
830 char *s
= g_strconcat (b
, bug_uri_snippet
, c
+ 2, NULL
);
832 g_test_message ("Bug Reference: %s", s
);
836 g_test_message ("Bug Reference: %s%s", test_uri_base
, bug_uri_snippet
);
842 * Get the toplevel test suite for the test path API.
844 * Returns: the toplevel #GTestSuite
849 g_test_get_root (void)
851 if (!test_suite_root
)
853 test_suite_root
= g_test_create_suite ("root");
854 g_free (test_suite_root
->name
);
855 test_suite_root
->name
= g_strdup ("");
857 return test_suite_root
;
863 * Runs all tests under the toplevel suite which can be retrieved
864 * with g_test_get_root(). Similar to g_test_run_suite(), the test
865 * cases to be run are filtered according to
866 * test path arguments (-p <replaceable>testpath</replaceable>) as
867 * parsed by g_test_init().
868 * g_test_run_suite() or g_test_run() may only be called once
871 * Returns: 0 on success
878 return g_test_run_suite (g_test_get_root());
882 * g_test_create_case:
883 * @test_name: the name for the test case
884 * @data_size: the size of the fixture data structure
885 * @test_data: test data argument for the test functions
886 * @data_setup: the function to set up the fixture data
887 * @data_test: the actual test function
888 * @data_teardown: the function to teardown the fixture data
890 * Create a new #GTestCase, named @test_name, this API is fairly
891 * low level, calling g_test_add() or g_test_add_func() is preferable.
892 * When this test is executed, a fixture structure of size @data_size
893 * will be allocated and filled with 0s. Then data_setup() is called
894 * to initialize the fixture. After fixture setup, the actual test
895 * function data_test() is called. Once the test run completed, the
896 * fixture structure is torn down by calling data_teardown() and
897 * after that the memory is released.
899 * Splitting up a test run into fixture setup, test function and
900 * fixture teardown is most usful if the same fixture is used for
901 * multiple tests. In this cases, g_test_create_case() will be
902 * called with the same fixture, but varying @test_name and
903 * @data_test arguments.
905 * Returns: a newly allocated #GTestCase.
910 g_test_create_case (const char *test_name
,
912 gconstpointer test_data
,
913 void (*data_setup
) (void),
914 void (*data_test
) (void),
915 void (*data_teardown
) (void))
918 g_return_val_if_fail (test_name
!= NULL
, NULL
);
919 g_return_val_if_fail (strchr (test_name
, '/') == NULL
, NULL
);
920 g_return_val_if_fail (test_name
[0] != 0, NULL
);
921 g_return_val_if_fail (data_test
!= NULL
, NULL
);
922 tc
= g_slice_new0 (GTestCase
);
923 tc
->name
= g_strdup (test_name
);
924 tc
->test_data
= (gpointer
) test_data
;
925 tc
->fixture_size
= data_size
;
926 tc
->fixture_setup
= (void*) data_setup
;
927 tc
->fixture_test
= (void*) data_test
;
928 tc
->fixture_teardown
= (void*) data_teardown
;
933 g_test_add_vtable (const char *testpath
,
935 gconstpointer test_data
,
936 void (*data_setup
) (void),
937 void (*fixture_test_func
) (void),
938 void (*data_teardown
) (void))
944 g_return_if_fail (testpath
!= NULL
);
945 g_return_if_fail (testpath
[0] == '/');
946 g_return_if_fail (fixture_test_func
!= NULL
);
948 suite
= g_test_get_root();
949 segments
= g_strsplit (testpath
, "/", -1);
950 for (ui
= 0; segments
[ui
] != NULL
; ui
++)
952 const char *seg
= segments
[ui
];
953 gboolean islast
= segments
[ui
+ 1] == NULL
;
954 if (islast
&& !seg
[0])
955 g_error ("invalid test case path: %s", testpath
);
957 continue; /* initial or duplicate slash */
960 GTestSuite
*csuite
= g_test_create_suite (seg
);
961 g_test_suite_add_suite (suite
, csuite
);
966 GTestCase
*tc
= g_test_create_case (seg
, data_size
, test_data
, data_setup
, fixture_test_func
, data_teardown
);
967 g_test_suite_add (suite
, tc
);
970 g_strfreev (segments
);
975 * @testpath: Slash-separated test case path name for the test.
976 * @test_func: The test function to invoke for this test.
978 * Create a new test case, similar to g_test_create_case(). However
979 * the test is assumed to use no fixture, and test suites are automatically
980 * created on the fly and added to the root fixture, based on the
981 * slash-separated portions of @testpath.
986 g_test_add_func (const char *testpath
,
987 void (*test_func
) (void))
989 g_return_if_fail (testpath
!= NULL
);
990 g_return_if_fail (testpath
[0] == '/');
991 g_return_if_fail (test_func
!= NULL
);
992 g_test_add_vtable (testpath
, 0, NULL
, NULL
, test_func
, NULL
);
996 * g_test_add_data_func:
997 * @testpath: Slash-separated test case path name for the test.
998 * @test_data: Test data argument for the test function.
999 * @test_func: The test function to invoke for this test.
1001 * Create a new test case, similar to g_test_create_case(). However
1002 * the test is assumed to use no fixture, and test suites are automatically
1003 * created on the fly and added to the root fixture, based on the
1004 * slash-separated portions of @testpath. The @test_data argument
1005 * will be passed as first argument to @test_func.
1010 g_test_add_data_func (const char *testpath
,
1011 gconstpointer test_data
,
1012 void (*test_func
) (gconstpointer
))
1014 g_return_if_fail (testpath
!= NULL
);
1015 g_return_if_fail (testpath
[0] == '/');
1016 g_return_if_fail (test_func
!= NULL
);
1017 g_test_add_vtable (testpath
, 0, test_data
, NULL
, (void(*)(void)) test_func
, NULL
);
1021 * g_test_create_suite:
1022 * @suite_name: a name for the suite
1024 * Create a new test suite with the name @suite_name.
1026 * Returns: A newly allocated #GTestSuite instance.
1031 g_test_create_suite (const char *suite_name
)
1034 g_return_val_if_fail (suite_name
!= NULL
, NULL
);
1035 g_return_val_if_fail (strchr (suite_name
, '/') == NULL
, NULL
);
1036 g_return_val_if_fail (suite_name
[0] != 0, NULL
);
1037 ts
= g_slice_new0 (GTestSuite
);
1038 ts
->name
= g_strdup (suite_name
);
1044 * @suite: a #GTestSuite
1045 * @test_case: a #GTestCase
1047 * Adds @test_case to @suite.
1052 g_test_suite_add (GTestSuite
*suite
,
1053 GTestCase
*test_case
)
1055 g_return_if_fail (suite
!= NULL
);
1056 g_return_if_fail (test_case
!= NULL
);
1057 suite
->cases
= g_slist_prepend (suite
->cases
, test_case
);
1061 * g_test_suite_add_suite:
1062 * @suite: a #GTestSuite
1063 * @nestedsuite: another #GTestSuite
1065 * Adds @nestedsuite to @suite.
1070 g_test_suite_add_suite (GTestSuite
*suite
,
1071 GTestSuite
*nestedsuite
)
1073 g_return_if_fail (suite
!= NULL
);
1074 g_return_if_fail (nestedsuite
!= NULL
);
1075 suite
->suites
= g_slist_prepend (suite
->suites
, nestedsuite
);
1079 * g_test_queue_free:
1080 * @gfree_pointer: the pointer to be stored.
1082 * Enqueue a pointer to be released with g_free() during the next
1083 * teardown phase. This is equivalent to calling g_test_queue_destroy()
1084 * with a destroy callback of g_free().
1089 g_test_queue_free (gpointer gfree_pointer
)
1092 g_test_queue_destroy (g_free
, gfree_pointer
);
1096 * g_test_queue_destroy:
1097 * @destroy_func: Destroy callback for teardown phase.
1098 * @destroy_data: Destroy callback data.
1100 * This function enqueus a callback @destroy_func() to be executed
1101 * during the next test case teardown phase. This is most useful
1102 * to auto destruct allocted test resources at the end of a test run.
1103 * Resources are released in reverse queue order, that means enqueueing
1104 * callback A before callback B will cause B() to be called before
1105 * A() during teardown.
1110 g_test_queue_destroy (GDestroyNotify destroy_func
,
1111 gpointer destroy_data
)
1113 DestroyEntry
*dentry
;
1114 g_return_if_fail (destroy_func
!= NULL
);
1115 dentry
= g_slice_new0 (DestroyEntry
);
1116 dentry
->destroy_func
= destroy_func
;
1117 dentry
->destroy_data
= destroy_data
;
1118 dentry
->next
= test_destroy_queue
;
1119 test_destroy_queue
= dentry
;
1123 test_case_run (GTestCase
*tc
)
1125 gchar
*old_name
= test_run_name
, *old_base
= g_strdup (test_uri_base
);
1126 test_run_name
= g_strconcat (old_name
, "/", tc
->name
, NULL
);
1127 if (++test_run_count
<= test_skip_count
)
1128 g_test_log (G_TEST_LOG_SKIP_CASE
, test_run_name
, NULL
, 0, NULL
);
1129 else if (test_run_list
)
1131 g_print ("%s\n", test_run_name
);
1132 g_test_log (G_TEST_LOG_LIST_CASE
, test_run_name
, NULL
, 0, NULL
);
1136 GTimer
*test_run_timer
= g_timer_new();
1137 long double largs
[3];
1139 g_test_log (G_TEST_LOG_START_CASE
, test_run_name
, NULL
, 0, NULL
);
1141 g_test_log_set_fatal_handler (NULL
, NULL
);
1142 g_timer_start (test_run_timer
);
1143 fixture
= tc
->fixture_size
? g_malloc0 (tc
->fixture_size
) : tc
->test_data
;
1144 test_run_seed (test_run_seedstr
);
1145 if (tc
->fixture_setup
)
1146 tc
->fixture_setup (fixture
, tc
->test_data
);
1147 tc
->fixture_test (fixture
, tc
->test_data
);
1149 while (test_destroy_queue
)
1151 DestroyEntry
*dentry
= test_destroy_queue
;
1152 test_destroy_queue
= dentry
->next
;
1153 dentry
->destroy_func (dentry
->destroy_data
);
1154 g_slice_free (DestroyEntry
, dentry
);
1156 if (tc
->fixture_teardown
)
1157 tc
->fixture_teardown (fixture
, tc
->test_data
);
1158 if (tc
->fixture_size
)
1160 g_timer_stop (test_run_timer
);
1161 largs
[0] = 0; /* OK */
1162 largs
[1] = test_run_forks
;
1163 largs
[2] = g_timer_elapsed (test_run_timer
, NULL
);
1164 g_test_log (G_TEST_LOG_STOP_CASE
, NULL
, NULL
, G_N_ELEMENTS (largs
), largs
);
1165 g_timer_destroy (test_run_timer
);
1167 g_free (test_run_name
);
1168 test_run_name
= old_name
;
1169 g_free (test_uri_base
);
1170 test_uri_base
= old_base
;
1175 g_test_run_suite_internal (GTestSuite
*suite
,
1178 guint n_bad
= 0, n_good
= 0, bad_suite
= 0, l
;
1179 gchar
*rest
, *old_name
= test_run_name
;
1180 GSList
*slist
, *reversed
;
1181 g_return_val_if_fail (suite
!= NULL
, -1);
1182 while (path
[0] == '/')
1185 rest
= strchr (path
, '/');
1186 l
= rest
? MIN (l
, rest
- path
) : l
;
1187 test_run_name
= suite
->name
[0] == 0 ? g_strdup (test_run_name
) : g_strconcat (old_name
, "/", suite
->name
, NULL
);
1188 reversed
= g_slist_reverse (g_slist_copy (suite
->cases
));
1189 for (slist
= reversed
; slist
; slist
= slist
->next
)
1191 GTestCase
*tc
= slist
->data
;
1192 guint n
= l
? strlen (tc
->name
) : 0;
1193 if (l
== n
&& strncmp (path
, tc
->name
, n
) == 0)
1196 n_bad
+= test_case_run (tc
) != 0;
1199 g_slist_free (reversed
);
1200 reversed
= g_slist_reverse (g_slist_copy (suite
->suites
));
1201 for (slist
= reversed
; slist
; slist
= slist
->next
)
1203 GTestSuite
*ts
= slist
->data
;
1204 guint n
= l
? strlen (ts
->name
) : 0;
1205 if (l
== n
&& strncmp (path
, ts
->name
, n
) == 0)
1206 bad_suite
+= g_test_run_suite_internal (ts
, rest
? rest
: "") != 0;
1208 g_slist_free (reversed
);
1209 g_free (test_run_name
);
1210 test_run_name
= old_name
;
1211 return n_bad
|| bad_suite
;
1216 * @suite: a #GTestSuite
1218 * Execute the tests within @suite and all nested #GTestSuites.
1219 * The test suites to be executed are filtered according to
1220 * test path arguments (-p <replaceable>testpath</replaceable>)
1221 * as parsed by g_test_init().
1222 * g_test_run_suite() or g_test_run() may only be called once
1225 * Returns: 0 on success
1230 g_test_run_suite (GTestSuite
*suite
)
1233 g_return_val_if_fail (g_test_config_vars
->test_initialized
, -1);
1234 g_return_val_if_fail (g_test_run_once
== TRUE
, -1);
1235 g_test_run_once
= FALSE
;
1237 test_paths
= g_slist_prepend (test_paths
, "");
1240 const char *rest
, *path
= test_paths
->data
;
1241 guint l
, n
= strlen (suite
->name
);
1242 test_paths
= g_slist_delete_link (test_paths
, test_paths
);
1243 while (path
[0] == '/')
1245 if (!n
) /* root suite, run unconditionally */
1247 n_bad
+= 0 != g_test_run_suite_internal (suite
, path
);
1250 /* regular suite, match path */
1251 rest
= strchr (path
, '/');
1253 l
= rest
? MIN (l
, rest
- path
) : l
;
1254 if ((!l
|| l
== n
) && strncmp (path
, suite
->name
, n
) == 0)
1255 n_bad
+= 0 != g_test_run_suite_internal (suite
, rest
? rest
: "");
1261 gtest_default_log_handler (const gchar
*log_domain
,
1262 GLogLevelFlags log_level
,
1263 const gchar
*message
,
1264 gpointer unused_data
)
1266 const gchar
*strv
[16];
1271 strv
[i
++] = log_domain
;
1274 if (log_level
& G_LOG_FLAG_FATAL
)
1275 strv
[i
++] = "FATAL-";
1276 if (log_level
& G_LOG_FLAG_RECURSION
)
1277 strv
[i
++] = "RECURSIVE-";
1278 if (log_level
& G_LOG_LEVEL_ERROR
)
1279 strv
[i
++] = "ERROR";
1280 if (log_level
& G_LOG_LEVEL_CRITICAL
)
1281 strv
[i
++] = "CRITICAL";
1282 if (log_level
& G_LOG_LEVEL_WARNING
)
1283 strv
[i
++] = "WARNING";
1284 if (log_level
& G_LOG_LEVEL_MESSAGE
)
1285 strv
[i
++] = "MESSAGE";
1286 if (log_level
& G_LOG_LEVEL_INFO
)
1288 if (log_level
& G_LOG_LEVEL_DEBUG
)
1289 strv
[i
++] = "DEBUG";
1291 strv
[i
++] = message
;
1293 msg
= g_strjoinv ("", (gchar
**) strv
);
1294 g_test_log (G_TEST_LOG_ERROR
, msg
, NULL
, 0, NULL
);
1295 g_log_default_handler (log_domain
, log_level
, message
, unused_data
);
1300 g_assertion_message (const char *domain
,
1304 const char *message
)
1309 message
= "code should not be reached";
1310 g_snprintf (lstr
, 32, "%d", line
);
1311 s
= g_strconcat (domain
? domain
: "", domain
&& domain
[0] ? ":" : "",
1312 "ERROR:", file
, ":", lstr
, ":",
1313 func
, func
[0] ? ":" : "",
1314 " ", message
, NULL
);
1315 g_printerr ("**\n%s\n", s
);
1317 /* store assertion message in global variable, so that it can be found in a
1319 if (__glib_assert_msg
!= NULL
)
1320 /* free the old one */
1321 free (__glib_assert_msg
);
1322 __glib_assert_msg
= (char*) malloc (strlen (s
) + 1);
1323 strcpy (__glib_assert_msg
, s
);
1325 g_test_log (G_TEST_LOG_ERROR
, s
, NULL
, 0, NULL
);
1331 g_assertion_message_expr (const char *domain
,
1337 char *s
= g_strconcat ("assertion failed: (", expr
, ")", NULL
);
1338 g_assertion_message (domain
, file
, line
, func
, s
);
1343 g_assertion_message_cmpnum (const char *domain
,
1356 case 'i': s
= g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr
, arg1
, cmp
, arg2
); break;
1357 case 'x': s
= g_strdup_printf ("assertion failed (%s): (0x%08" G_GINT64_MODIFIER
"x %s 0x%08" G_GINT64_MODIFIER
"x)", expr
, (guint64
) arg1
, cmp
, (guint64
) arg2
); break;
1358 case 'f': s
= g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr
, arg1
, cmp
, arg2
); break;
1359 /* ideally use: floats=%.7g double=%.17g */
1361 g_assertion_message (domain
, file
, line
, func
, s
);
1366 g_assertion_message_cmpstr (const char *domain
,
1375 char *a1
, *a2
, *s
, *t1
= NULL
, *t2
= NULL
;
1376 a1
= arg1
? g_strconcat ("\"", t1
= g_strescape (arg1
, NULL
), "\"", NULL
) : g_strdup ("NULL");
1377 a2
= arg2
? g_strconcat ("\"", t2
= g_strescape (arg2
, NULL
), "\"", NULL
) : g_strdup ("NULL");
1380 s
= g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr
, a1
, cmp
, a2
);
1383 g_assertion_message (domain
, file
, line
, func
, s
);
1388 g_assertion_message_error (const char *domain
,
1393 const GError
*error
,
1394 GQuark error_domain
,
1399 /* This is used by both g_assert_error() and g_assert_no_error(), so there
1400 * are three cases: expected an error but got the wrong error, expected
1401 * an error but got no error, and expected no error but got an error.
1404 gstring
= g_string_new ("assertion failed ");
1406 g_string_append_printf (gstring
, "(%s == (%s, %d)): ", expr
,
1407 g_quark_to_string (error_domain
), error_code
);
1409 g_string_append_printf (gstring
, "(%s == NULL): ", expr
);
1412 g_string_append_printf (gstring
, "%s (%s, %d)", error
->message
,
1413 g_quark_to_string (error
->domain
), error
->code
);
1415 g_string_append_printf (gstring
, "%s is NULL", expr
);
1417 g_assertion_message (domain
, file
, line
, func
, gstring
->str
);
1418 g_string_free (gstring
, TRUE
);
1423 * @str1: a C string or %NULL
1424 * @str2: another C string or %NULL
1426 * Compares @str1 and @str2 like strcmp(). Handles %NULL
1427 * gracefully by sorting it before non-%NULL strings.
1429 * Returns: -1, 0 or 1, if @str1 is <, == or > than @str2.
1434 g_strcmp0 (const char *str1
,
1438 return -(str1
!= str2
);
1440 return str1
!= str2
;
1441 return strcmp (str1
, str2
);
1445 static int /* 0 on success */
1446 kill_child (int pid
,
1451 if (patience
>= 3) /* try graceful reap */
1453 if (waitpid (pid
, status
, WNOHANG
) > 0)
1456 if (patience
>= 2) /* try SIGHUP */
1459 if (waitpid (pid
, status
, WNOHANG
) > 0)
1461 g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1462 if (waitpid (pid
, status
, WNOHANG
) > 0)
1464 g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
1465 if (waitpid (pid
, status
, WNOHANG
) > 0)
1467 g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
1468 if (waitpid (pid
, status
, WNOHANG
) > 0)
1471 if (patience
>= 1) /* try SIGTERM */
1473 kill (pid
, SIGTERM
);
1474 if (waitpid (pid
, status
, WNOHANG
) > 0)
1476 g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
1477 if (waitpid (pid
, status
, WNOHANG
) > 0)
1479 g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
1480 if (waitpid (pid
, status
, WNOHANG
) > 0)
1484 kill (pid
, SIGKILL
);
1486 wr
= waitpid (pid
, status
, 0);
1487 while (wr
< 0 && errno
== EINTR
);
1493 g_string_must_read (GString
*gstring
,
1496 #define STRING_BUFFER_SIZE 4096
1497 char buf
[STRING_BUFFER_SIZE
];
1500 bytes
= read (fd
, buf
, sizeof (buf
));
1502 return 0; /* EOF, calling this function assumes data is available */
1505 g_string_append_len (gstring
, buf
, bytes
);
1508 else if (bytes
< 0 && errno
== EINTR
)
1510 else /* bytes < 0 */
1512 g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid
, g_strerror (errno
));
1513 return 1; /* ignore error after warning */
1518 g_string_write_out (GString
*gstring
,
1522 if (*stringpos
< gstring
->len
)
1526 r
= write (outfd
, gstring
->str
+ *stringpos
, gstring
->len
- *stringpos
);
1527 while (r
< 0 && errno
== EINTR
);
1528 *stringpos
+= MAX (r
, 0);
1533 test_trap_clear (void)
1535 test_trap_last_status
= 0;
1536 test_trap_last_pid
= 0;
1537 g_free (test_trap_last_stdout
);
1538 test_trap_last_stdout
= NULL
;
1539 g_free (test_trap_last_stderr
);
1540 test_trap_last_stderr
= NULL
;
1551 ret
= dup2 (fd1
, fd2
);
1552 while (ret
< 0 && errno
== EINTR
);
1557 test_time_stamp (void)
1561 g_get_current_time (&tv
);
1563 stamp
= stamp
* 1000000 + tv
.tv_usec
;
1571 * @usec_timeout: Timeout for the forked test in micro seconds.
1572 * @test_trap_flags: Flags to modify forking behaviour.
1574 * Fork the current test program to execute a test case that might
1575 * not return or that might abort. The forked test case is aborted
1576 * and considered failing if its run time exceeds @usec_timeout.
1578 * The forking behavior can be configured with the #GTestTrapFlags flags.
1580 * In the following example, the test code forks, the forked child
1581 * process produces some sample output and exits successfully.
1582 * The forking parent process then asserts successful child program
1583 * termination and validates child program outputs.
1587 * test_fork_patterns (void)
1589 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
1591 * g_print ("some stdout text: somagic17\n");
1592 * g_printerr ("some stderr text: semagic43\n");
1593 * exit (0); /* successful test run */
1595 * g_test_trap_assert_passed();
1596 * g_test_trap_assert_stdout ("*somagic17*");
1597 * g_test_trap_assert_stderr ("*semagic43*");
1601 * This function is implemented only on Unix platforms.
1603 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
1608 g_test_trap_fork (guint64 usec_timeout
,
1609 GTestTrapFlags test_trap_flags
)
1612 gboolean pass_on_forked_log
= FALSE
;
1613 int stdout_pipe
[2] = { -1, -1 };
1614 int stderr_pipe
[2] = { -1, -1 };
1615 int stdtst_pipe
[2] = { -1, -1 };
1617 if (pipe (stdout_pipe
) < 0 || pipe (stderr_pipe
) < 0 || pipe (stdtst_pipe
) < 0)
1618 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno
));
1619 signal (SIGCHLD
, SIG_DFL
);
1620 test_trap_last_pid
= fork ();
1621 if (test_trap_last_pid
< 0)
1622 g_error ("failed to fork test program: %s", g_strerror (errno
));
1623 if (test_trap_last_pid
== 0) /* child */
1626 close (stdout_pipe
[0]);
1627 close (stderr_pipe
[0]);
1628 close (stdtst_pipe
[0]);
1629 if (!(test_trap_flags
& G_TEST_TRAP_INHERIT_STDIN
))
1630 fd0
= open ("/dev/null", O_RDONLY
);
1631 if (sane_dup2 (stdout_pipe
[1], 1) < 0 || sane_dup2 (stderr_pipe
[1], 2) < 0 || (fd0
>= 0 && sane_dup2 (fd0
, 0) < 0))
1632 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno
));
1635 if (stdout_pipe
[1] >= 3)
1636 close (stdout_pipe
[1]);
1637 if (stderr_pipe
[1] >= 3)
1638 close (stderr_pipe
[1]);
1639 test_log_fd
= stdtst_pipe
[1];
1644 GString
*sout
= g_string_new (NULL
);
1645 GString
*serr
= g_string_new (NULL
);
1647 int soutpos
= 0, serrpos
= 0, wr
, need_wait
= TRUE
;
1649 close (stdout_pipe
[1]);
1650 close (stderr_pipe
[1]);
1651 close (stdtst_pipe
[1]);
1652 sstamp
= test_time_stamp();
1653 /* read data until we get EOF on all pipes */
1654 while (stdout_pipe
[0] >= 0 || stderr_pipe
[0] >= 0 || stdtst_pipe
[0] > 0)
1660 if (stdout_pipe
[0] >= 0)
1661 FD_SET (stdout_pipe
[0], &fds
);
1662 if (stderr_pipe
[0] >= 0)
1663 FD_SET (stderr_pipe
[0], &fds
);
1664 if (stdtst_pipe
[0] >= 0)
1665 FD_SET (stdtst_pipe
[0], &fds
);
1667 tv
.tv_usec
= MIN (usec_timeout
? usec_timeout
: 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
1668 ret
= select (MAX (MAX (stdout_pipe
[0], stderr_pipe
[0]), stdtst_pipe
[0]) + 1, &fds
, NULL
, NULL
, &tv
);
1669 if (ret
< 0 && errno
!= EINTR
)
1671 g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid
, g_strerror (errno
));
1674 if (stdout_pipe
[0] >= 0 && FD_ISSET (stdout_pipe
[0], &fds
) &&
1675 g_string_must_read (sout
, stdout_pipe
[0]) == 0)
1677 close (stdout_pipe
[0]);
1678 stdout_pipe
[0] = -1;
1680 if (stderr_pipe
[0] >= 0 && FD_ISSET (stderr_pipe
[0], &fds
) &&
1681 g_string_must_read (serr
, stderr_pipe
[0]) == 0)
1683 close (stderr_pipe
[0]);
1684 stderr_pipe
[0] = -1;
1686 if (stdtst_pipe
[0] >= 0 && FD_ISSET (stdtst_pipe
[0], &fds
))
1688 guint8 buffer
[4096];
1689 gint l
, r
= read (stdtst_pipe
[0], buffer
, sizeof (buffer
));
1690 if (r
> 0 && test_log_fd
> 0)
1692 l
= write (pass_on_forked_log
? test_log_fd
: -1, buffer
, r
);
1693 while (l
< 0 && errno
== EINTR
);
1694 if (r
== 0 || (r
< 0 && errno
!= EINTR
&& errno
!= EAGAIN
))
1696 close (stdtst_pipe
[0]);
1697 stdtst_pipe
[0] = -1;
1700 if (!(test_trap_flags
& G_TEST_TRAP_SILENCE_STDOUT
))
1701 g_string_write_out (sout
, 1, &soutpos
);
1702 if (!(test_trap_flags
& G_TEST_TRAP_SILENCE_STDERR
))
1703 g_string_write_out (serr
, 2, &serrpos
);
1706 guint64 nstamp
= test_time_stamp();
1708 sstamp
= MIN (sstamp
, nstamp
); /* guard against backwards clock skews */
1709 if (usec_timeout
< nstamp
- sstamp
)
1711 /* timeout reached, need to abort the child now */
1712 kill_child (test_trap_last_pid
, &status
, 3);
1713 test_trap_last_status
= 1024; /* timeout */
1714 if (0 && WIFSIGNALED (status
))
1715 g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC
, g_strsignal (WTERMSIG (status
)));
1721 close (stdout_pipe
[0]);
1722 close (stderr_pipe
[0]);
1723 close (stdtst_pipe
[0]);
1728 wr
= waitpid (test_trap_last_pid
, &status
, 0);
1729 while (wr
< 0 && errno
== EINTR
);
1730 if (WIFEXITED (status
)) /* normal exit */
1731 test_trap_last_status
= WEXITSTATUS (status
); /* 0..255 */
1732 else if (WIFSIGNALED (status
))
1733 test_trap_last_status
= (WTERMSIG (status
) << 12); /* signalled */
1734 else /* WCOREDUMP (status) */
1735 test_trap_last_status
= 512; /* coredump */
1737 test_trap_last_stdout
= g_string_free (sout
, FALSE
);
1738 test_trap_last_stderr
= g_string_free (serr
, FALSE
);
1742 g_message ("Not implemented: g_test_trap_fork");
1749 * g_test_trap_has_passed:
1751 * Check the result of the last g_test_trap_fork() call.
1753 * Returns: %TRUE if the last forked child terminated successfully.
1758 g_test_trap_has_passed (void)
1760 return test_trap_last_status
== 0; /* exit_status == 0 && !signal && !coredump */
1764 * g_test_trap_reached_timeout:
1766 * Check the result of the last g_test_trap_fork() call.
1768 * Returns: %TRUE if the last forked child got killed due to a fork timeout.
1773 g_test_trap_reached_timeout (void)
1775 return 0 != (test_trap_last_status
& 1024); /* timeout flag */
1779 g_test_trap_assertions (const char *domain
,
1783 guint64 assertion_flags
, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
1784 const char *pattern
)
1787 gboolean must_pass
= assertion_flags
== 0;
1788 gboolean must_fail
= assertion_flags
== 1;
1789 gboolean match_result
= 0 == (assertion_flags
& 1);
1790 const char *stdout_pattern
= (assertion_flags
& 2) ? pattern
: NULL
;
1791 const char *stderr_pattern
= (assertion_flags
& 4) ? pattern
: NULL
;
1792 const char *match_error
= match_result
? "failed to match" : "contains invalid match";
1793 if (test_trap_last_pid
== 0)
1794 g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
1795 if (must_pass
&& !g_test_trap_has_passed())
1797 char *msg
= g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid
);
1798 g_assertion_message (domain
, file
, line
, func
, msg
);
1801 if (must_fail
&& g_test_trap_has_passed())
1803 char *msg
= g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid
);
1804 g_assertion_message (domain
, file
, line
, func
, msg
);
1807 if (stdout_pattern
&& match_result
== !g_pattern_match_simple (stdout_pattern
, test_trap_last_stdout
))
1809 char *msg
= g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid
, match_error
, stdout_pattern
);
1810 g_assertion_message (domain
, file
, line
, func
, msg
);
1813 if (stderr_pattern
&& match_result
== !g_pattern_match_simple (stderr_pattern
, test_trap_last_stderr
))
1815 char *msg
= g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid
, match_error
, stderr_pattern
);
1816 g_assertion_message (domain
, file
, line
, func
, msg
);
1823 gstring_overwrite_int (GString
*gstring
,
1827 vuint
= g_htonl (vuint
);
1828 g_string_overwrite_len (gstring
, pos
, (const gchar
*) &vuint
, 4);
1832 gstring_append_int (GString
*gstring
,
1835 vuint
= g_htonl (vuint
);
1836 g_string_append_len (gstring
, (const gchar
*) &vuint
, 4);
1840 gstring_append_double (GString
*gstring
,
1843 union { double vdouble
; guint64 vuint64
; } u
;
1844 u
.vdouble
= vdouble
;
1845 u
.vuint64
= GUINT64_TO_BE (u
.vuint64
);
1846 g_string_append_len (gstring
, (const gchar
*) &u
.vuint64
, 8);
1850 g_test_log_dump (GTestLogMsg
*msg
,
1853 GString
*gstring
= g_string_sized_new (1024);
1855 gstring_append_int (gstring
, 0); /* message length */
1856 gstring_append_int (gstring
, msg
->log_type
);
1857 gstring_append_int (gstring
, msg
->n_strings
);
1858 gstring_append_int (gstring
, msg
->n_nums
);
1859 gstring_append_int (gstring
, 0); /* reserved */
1860 for (ui
= 0; ui
< msg
->n_strings
; ui
++)
1862 guint l
= strlen (msg
->strings
[ui
]);
1863 gstring_append_int (gstring
, l
);
1864 g_string_append_len (gstring
, msg
->strings
[ui
], l
);
1866 for (ui
= 0; ui
< msg
->n_nums
; ui
++)
1867 gstring_append_double (gstring
, msg
->nums
[ui
]);
1868 *len
= gstring
->len
;
1869 gstring_overwrite_int (gstring
, 0, *len
); /* message length */
1870 return (guint8
*) g_string_free (gstring
, FALSE
);
1873 static inline long double
1874 net_double (const gchar
**ipointer
)
1876 union { guint64 vuint64
; double vdouble
; } u
;
1877 guint64 aligned_int64
;
1878 memcpy (&aligned_int64
, *ipointer
, 8);
1880 u
.vuint64
= GUINT64_FROM_BE (aligned_int64
);
1884 static inline guint32
1885 net_int (const gchar
**ipointer
)
1887 guint32 aligned_int
;
1888 memcpy (&aligned_int
, *ipointer
, 4);
1890 return g_ntohl (aligned_int
);
1894 g_test_log_extract (GTestLogBuffer
*tbuffer
)
1896 const gchar
*p
= tbuffer
->data
->str
;
1899 if (tbuffer
->data
->len
< 4 * 5)
1901 mlength
= net_int (&p
);
1902 if (tbuffer
->data
->len
< mlength
)
1904 msg
.log_type
= net_int (&p
);
1905 msg
.n_strings
= net_int (&p
);
1906 msg
.n_nums
= net_int (&p
);
1907 if (net_int (&p
) == 0)
1910 msg
.strings
= g_new0 (gchar
*, msg
.n_strings
+ 1);
1911 msg
.nums
= g_new0 (long double, msg
.n_nums
);
1912 for (ui
= 0; ui
< msg
.n_strings
; ui
++)
1914 guint sl
= net_int (&p
);
1915 msg
.strings
[ui
] = g_strndup (p
, sl
);
1918 for (ui
= 0; ui
< msg
.n_nums
; ui
++)
1919 msg
.nums
[ui
] = net_double (&p
);
1920 if (p
<= tbuffer
->data
->str
+ mlength
)
1922 g_string_erase (tbuffer
->data
, 0, mlength
);
1923 tbuffer
->msgs
= g_slist_prepend (tbuffer
->msgs
, g_memdup (&msg
, sizeof (msg
)));
1928 g_strfreev (msg
.strings
);
1929 g_error ("corrupt log stream from test program");
1934 * g_test_log_buffer_new:
1936 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1939 g_test_log_buffer_new (void)
1941 GTestLogBuffer
*tb
= g_new0 (GTestLogBuffer
, 1);
1942 tb
->data
= g_string_sized_new (1024);
1947 * g_test_log_buffer_free
1949 * Internal function for gtester to free test log messages, no ABI guarantees provided.
1952 g_test_log_buffer_free (GTestLogBuffer
*tbuffer
)
1954 g_return_if_fail (tbuffer
!= NULL
);
1955 while (tbuffer
->msgs
)
1956 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer
));
1957 g_string_free (tbuffer
->data
, TRUE
);
1962 * g_test_log_buffer_push
1964 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1967 g_test_log_buffer_push (GTestLogBuffer
*tbuffer
,
1969 const guint8
*bytes
)
1971 g_return_if_fail (tbuffer
!= NULL
);
1974 gboolean more_messages
;
1975 g_return_if_fail (bytes
!= NULL
);
1976 g_string_append_len (tbuffer
->data
, (const gchar
*) bytes
, n_bytes
);
1978 more_messages
= g_test_log_extract (tbuffer
);
1979 while (more_messages
);
1984 * g_test_log_buffer_pop:
1986 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
1989 g_test_log_buffer_pop (GTestLogBuffer
*tbuffer
)
1991 GTestLogMsg
*msg
= NULL
;
1992 g_return_val_if_fail (tbuffer
!= NULL
, NULL
);
1995 GSList
*slist
= g_slist_last (tbuffer
->msgs
);
1997 tbuffer
->msgs
= g_slist_delete_link (tbuffer
->msgs
, slist
);
2003 * g_test_log_msg_free:
2005 * Internal function for gtester to free test log messages, no ABI guarantees provided.
2008 g_test_log_msg_free (GTestLogMsg
*tmsg
)
2010 g_return_if_fail (tmsg
!= NULL
);
2011 g_strfreev (tmsg
->strings
);
2012 g_free (tmsg
->nums
);
2016 /* --- macros docs START --- */
2019 * @testpath: The test path for a new test case.
2020 * @Fixture: The type of a fixture data structure.
2021 * @tdata: Data argument for the test functions.
2022 * @fsetup: The function to set up the fixture data.
2023 * @ftest: The actual test function.
2024 * @fteardown: The function to tear down the fixture data.
2026 * Hook up a new test case at @testpath, similar to g_test_add_func().
2027 * A fixture data structure with setup and teardown function may be provided
2028 * though, similar to g_test_create_case().
2029 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
2030 * fteardown() callbacks can expect a @Fixture pointer as first argument in
2031 * a type safe manner.
2035 /* --- macros docs END --- */
2037 #define __G_TEST_UTILS_C__
2038 #include "galiasdef.c"