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.
21 #include "gtestutils.h"
23 #include <sys/types.h>
39 #ifdef HAVE_SYS_SELECT_H
40 #include <sys/select.h>
41 #endif /* HAVE_SYS_SELECT_H */
43 /* --- structures --- */
48 void (*fixture_setup) (void*, gconstpointer);
49 void (*fixture_test) (void*, gconstpointer);
50 void (*fixture_teardown) (void*, gconstpointer);
59 typedef struct DestroyEntry DestroyEntry;
63 GDestroyNotify destroy_func;
64 gpointer destroy_data;
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,
72 static void gtest_default_log_handler (const gchar *log_domain,
73 GLogLevelFlags log_level,
75 gpointer unused_data);
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 */
107 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars;
109 /* --- functions --- */
111 g_test_log_type_name (GTestLogType log_type)
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";
130 g_test_log_send (guint n_bytes,
131 const guint8 *buffer)
133 if (test_log_fd >= 0)
137 r = write (test_log_fd, buffer, n_bytes);
138 while (r < 0 && errno == EINTR);
142 GTestLogBuffer *lbuffer = g_test_log_buffer_new();
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);
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]);
157 for (ui = 0; ui < msg->n_nums; ui++)
158 g_printerr ("%s%.16Lg", ui ? ";" : "", msg->nums[ui]);
161 g_printerr (":LOG*}\n");
162 g_test_log_msg_free (msg);
167 g_test_log (GTestLogType lbit,
168 const gchar *string1,
169 const gchar *string2,
173 gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
175 gchar *astrings[3] = { NULL, NULL, NULL };
181 case G_TEST_LOG_START_BINARY:
182 if (g_test_verbose())
183 g_print ("GTest: random seed: %s\n", string2);
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)
193 case G_TEST_LOG_MIN_RESULT:
194 if (g_test_verbose())
195 g_print ("(MINPERF:%s)\n", string1);
197 case G_TEST_LOG_MAX_RESULT:
198 if (g_test_verbose())
199 g_print ("(MAXPERF:%s)\n", string1);
201 case G_TEST_LOG_MESSAGE:
202 if (g_test_verbose())
203 g_print ("(MSG: %s)\n", string1);
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;
215 dbuffer = g_test_log_dump (&msg, &dbufferlen);
216 g_test_log_send (dbufferlen, dbuffer);
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);
232 parse_args (gint *argc_p,
235 guint argc = *argc_p;
236 gchar **argv = *argv_p;
238 /* parse known args */
239 for (i = 1; i < argc; i++)
241 if (strcmp (argv[i], "--g-fatal-warnings") == 0)
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);
248 else if (strcmp (argv[i], "--keep-going") == 0 ||
249 strcmp (argv[i], "-k") == 0)
251 test_mode_fatal = FALSE;
254 else if (strcmp (argv[i], "--debug-log") == 0)
256 test_debug_log = TRUE;
259 else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
261 gchar *equal = argv[i] + 12;
263 test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
264 else if (i + 1 < argc)
267 test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
271 else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
273 gchar *equal = argv[i] + 16;
275 test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
276 else if (i + 1 < argc)
279 test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
283 else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
285 gchar *equal = argv[i] + 2;
287 test_paths = g_slist_prepend (test_paths, equal + 1);
288 else if (i + 1 < argc)
291 test_paths = g_slist_prepend (test_paths, argv[i]);
295 else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
297 gchar *equal = argv[i] + 2;
298 const gchar *mode = "";
301 else if (i + 1 < argc)
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)
314 mutable_test_config_vars.test_quick = TRUE;
315 mutable_test_config_vars.test_perf = FALSE;
318 g_error ("unknown test mode: -m %s", mode);
321 else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
323 mutable_test_config_vars.test_quiet = TRUE;
324 mutable_test_config_vars.test_verbose = FALSE;
327 else if (strcmp ("--verbose", argv[i]) == 0)
329 mutable_test_config_vars.test_quiet = FALSE;
330 mutable_test_config_vars.test_verbose = TRUE;
333 else if (strcmp ("-l", argv[i]) == 0)
335 test_run_list = TRUE;
338 else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
340 gchar *equal = argv[i] + 6;
342 test_run_seedstr = equal + 1;
343 else if (i + 1 < argc)
346 test_run_seedstr = argv[i];
353 for (i = 1; i < argc; i++)
365 * @argc: Address of the @argc parameter of the main() function.
366 * Changed if any arguments were handled.
367 * @argv: Address of the @argv parameter of main().
368 * Any parameters understood by g_test_init() stripped before return.
369 * @Varargs: Reserved for future extension. Currently, you must pass %NULL.
371 * Initialize the GLib testing framework, e.g. by seeding the
372 * test random number generator, the name for g_get_prgname()
373 * and parsing test related command line args.
374 * So far, the following arguments are understood:
376 * -l list test cases available in a test executable.
377 * --seed RANDOMSEED provide a random seed to reproduce test runs using random numbers.
378 * --verbose run tests verbosely.
379 * -q, --quiet run tests quietly.
380 * -p TESTPATH execute all tests matching TESTPATH.
381 * -m {perf|slow|thorough|quick}
382 * execute tests according to these test modes:
383 * perf - performance tests, may take long and report results.
384 * slow - slow and thorough tests, may take quite long and maximize coverage.
385 * thorough - currently an alias for "slow".
386 * quick - quick tests, should run really quickly and give good coverage.
387 * --debug-log debug test logging output.
388 * -k, --keep-going gtester specific argument.
389 * --GTestLogFD N gtester specific argument.
390 * --GTestSkipCount N gtester specific argument.
396 g_test_init (int *argc,
400 static char seedstr[4 + 4 * 8 + 1];
403 /* make warnings and criticals fatal for all test programs */
404 GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
405 fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
406 g_log_set_always_fatal (fatal_mask);
407 /* check caller args */
408 g_return_if_fail (argc != NULL);
409 g_return_if_fail (argv != NULL);
410 g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
411 mutable_test_config_vars.test_initialized = TRUE;
413 va_start (args, argv);
414 vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
416 g_return_if_fail (vararg1 == NULL);
418 /* setup random seed string */
419 g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
420 test_run_seedstr = seedstr;
422 /* parse args, sets up mode, changes seed, etc. */
423 parse_args (argc, argv);
424 if (!g_get_prgname())
425 g_set_prgname ((*argv)[0]);
427 /* verify GRand reliability, needed for reliable seeds */
430 GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
431 guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
432 /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
433 if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
434 g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
438 /* check rand seed */
439 test_run_seed (test_run_seedstr);
441 /* report program start */
442 g_log_set_default_handler (gtest_default_log_handler, NULL);
443 g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
447 test_run_seed (const gchar *rseed)
449 guint seed_failed = 0;
451 g_rand_free (test_run_rand);
452 test_run_rand = NULL;
453 while (strchr (" \t\v\r\n\f", *rseed))
455 if (strncmp (rseed, "R02S", 4) == 0) /* seed for random generator 02 (GRand-2.2) */
457 const char *s = rseed + 4;
458 if (strlen (s) >= 32) /* require 4 * 8 chars */
460 guint32 seedarray[4];
461 gchar *p, hexbuf[9] = { 0, };
462 memcpy (hexbuf, s + 0, 8);
463 seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
464 seed_failed += p != NULL && *p != 0;
465 memcpy (hexbuf, s + 8, 8);
466 seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
467 seed_failed += p != NULL && *p != 0;
468 memcpy (hexbuf, s + 16, 8);
469 seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
470 seed_failed += p != NULL && *p != 0;
471 memcpy (hexbuf, s + 24, 8);
472 seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
473 seed_failed += p != NULL && *p != 0;
476 test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
481 g_error ("Unknown or invalid random seed: %s", rseed);
487 * Get a reproducible random integer number.
488 * The random numbers generated by the g_test_rand_*() family of functions
489 * change with every new test program start, unless the --seed option is
490 * given when starting test programs.
491 * For individual test cases however, the random number generator is
492 * reseeded, to avoid dependencies between tests and to make --seed
493 * effective for all test cases.
495 * Returns: a random number from the seeded random number generator.
500 g_test_rand_int (void)
502 return g_rand_int (test_run_rand);
506 * g_test_rand_int_range:
507 * @begin: the minimum value returned by this function
508 * @end: the smallest value not to be returned by this function
510 * Get a reproducible random integer number out of a specified range,
511 * see g_test_rand_int() for details on test case random numbers.
513 * Returns: a number with @begin <= number < @end.
518 g_test_rand_int_range (gint32 begin,
521 return g_rand_int_range (test_run_rand, begin, end);
525 * g_test_rand_double:
527 * Get a reproducible random floating point number,
528 * see g_test_rand_int() for details on test case random numbers.
530 * Returns: a random number from the seeded random number generator.
535 g_test_rand_double (void)
537 return g_rand_double (test_run_rand);
541 * g_test_rand_double_range:
542 * @range_start: the minimum value returned by this function
543 * @range_end: the minimum value not returned by this function
545 * Get a reproducible random floating pointer number out of a specified range,
546 * see g_test_rand_int() for details on test case random numbers.
548 * Returns: a number with @range_start <= number < @range_end.
553 g_test_rand_double_range (double range_start,
556 return g_rand_double_range (test_run_rand, range_start, range_end);
560 * g_test_timer_start:
562 * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
563 * to be done. Call this function again to restart the timer.
568 g_test_timer_start (void)
570 if (!test_user_timer)
571 test_user_timer = g_timer_new();
573 g_timer_start (test_user_timer);
577 * g_test_timer_elapsed:
579 * Get the time since the last start of the timer with g_test_timer_start().
581 * Returns: the time since the last start of the timer, as a double
586 g_test_timer_elapsed (void)
588 test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
589 return test_user_stamp;
595 * Report the last result of g_test_timer_elapsed().
597 * Returns: the last result of g_test_timer_elapsed(), as a double
602 g_test_timer_last (void)
604 return test_user_stamp;
608 * g_test_minimized_result:
609 * @minimized_quantity: the reported value
610 * @format: the format string of the report message
611 * @Varargs: arguments to pass to the printf() function
613 * Report the result of a performance or measurement test.
614 * The test should generally strive to minimize the reported
615 * quantities (smaller values are better than larger ones),
616 * this and @minimized_quantity can determine sorting
617 * order for test result reports.
622 g_test_minimized_result (double minimized_quantity,
626 long double largs = minimized_quantity;
629 va_start (args, format);
630 buffer = g_strdup_vprintf (format, args);
632 g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
637 * g_test_maximized_result:
638 * @maximized_quantity: the reported value
639 * @format: the format string of the report message
640 * @Varargs: arguments to pass to the printf() function
642 * Report the result of a performance or measurement test.
643 * The test should generally strive to maximize the reported
644 * quantities (larger values are better than smaller ones),
645 * this and @maximized_quantity can determine sorting
646 * order for test result reports.
651 g_test_maximized_result (double maximized_quantity,
655 long double largs = maximized_quantity;
658 va_start (args, format);
659 buffer = g_strdup_vprintf (format, args);
661 g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
667 * @format: the format string
668 * @...: printf-like arguments to @format
670 * Add a message to the test report.
675 g_test_message (const char *format,
680 va_start (args, format);
681 buffer = g_strdup_vprintf (format, args);
683 g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
689 * @uri_pattern: the base pattern for bug URIs
691 * Specify the base URI for bug reports.
692 * The base URI is used to construct bug report messages for
693 * g_test_message() when g_test_bug() is called.
694 * Calling this function outside of a test case sets the
695 * default base URI for all test cases. Calling it from within
696 * a test case changes the base URI for the scope of the test
698 * Bug URIs are constructed by appending a bug specific URI
699 * portion to @uri_pattern, or by replacing the special string
700 * '%s' within @uri_pattern if that is present.
705 g_test_bug_base (const char *uri_pattern)
707 g_free (test_uri_base);
708 test_uri_base = g_strdup (uri_pattern);
713 * @bug_uri_snippet: Bug specific bug tracker URI portion.
715 * This function adds a message to test reports that
716 * associates a bug URI with a test case.
717 * Bug URIs are constructed from a base URI set with g_test_bug_base()
718 * and @bug_uri_snippet.
723 g_test_bug (const char *bug_uri_snippet)
726 g_return_if_fail (test_uri_base != NULL);
727 g_return_if_fail (bug_uri_snippet != NULL);
728 c = strstr (test_uri_base, "%s");
731 char *b = g_strndup (test_uri_base, c - test_uri_base);
732 char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
734 g_test_message ("Bug Reference: %s", s);
738 g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
744 * Get the toplevel test suite for the test path API.
746 * Returns: the toplevel #GTestSuite
751 g_test_get_root (void)
753 if (!test_suite_root)
755 test_suite_root = g_test_create_suite ("root");
756 g_free (test_suite_root->name);
757 test_suite_root->name = g_strdup ("");
759 return test_suite_root;
765 * Runs all tests under the toplevel suite which can be retrieved
766 * with g_test_get_root(). Similar to g_test_run_suite(), the test
767 * cases to be run are filtered according to
768 * test path arguments (-p <replaceable>testpath</replaceable>) as
769 * parsed by g_test_init().
770 * g_test_run_suite() or g_test_run() may only be called once
773 * Returns: 0 on success
780 return g_test_run_suite (g_test_get_root());
784 * g_test_create_case:
785 * @test_name: the name for the test case
786 * @data_size: the size of the fixture data structure
787 * @test_data: test data argument for the test functions
788 * @data_setup: the function to set up the fixture data
789 * @data_test: the actual test function
790 * @data_teardown: the function to teardown the fixture data
792 * Create a new #GTestCase, named @test_name, this API is fairly
793 * low level, calling g_test_add() or g_test_add_func() is preferable.
794 * When this test is executed, a fixture structure of size @data_size
795 * will be allocated and filled with 0s. Then data_setup() is called
796 * to initialize the fixture. After fixture setup, the actual test
797 * function data_test() is called. Once the test run completed, the
798 * fixture structure is torn down by calling data_teardown() and
799 * after that the memory is released.
801 * Splitting up a test run into fixture setup, test function and
802 * fixture teardown is most usful if the same fixture is used for
803 * multiple tests. In this cases, g_test_create_case() will be
804 * called with the same fixture, but varying @test_name and
805 * @data_test arguments.
807 * Returns: a newly allocated #GTestCase.
812 g_test_create_case (const char *test_name,
814 gconstpointer test_data,
815 void (*data_setup) (void),
816 void (*data_test) (void),
817 void (*data_teardown) (void))
820 g_return_val_if_fail (test_name != NULL, NULL);
821 g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
822 g_return_val_if_fail (test_name[0] != 0, NULL);
823 g_return_val_if_fail (data_test != NULL, NULL);
824 tc = g_slice_new0 (GTestCase);
825 tc->name = g_strdup (test_name);
826 tc->test_data = (gpointer) test_data;
827 tc->fixture_size = data_size;
828 tc->fixture_setup = (void*) data_setup;
829 tc->fixture_test = (void*) data_test;
830 tc->fixture_teardown = (void*) data_teardown;
835 g_test_add_vtable (const char *testpath,
837 gconstpointer test_data,
838 void (*data_setup) (void),
839 void (*fixture_test_func) (void),
840 void (*data_teardown) (void))
846 g_return_if_fail (testpath != NULL);
847 g_return_if_fail (testpath[0] == '/');
848 g_return_if_fail (fixture_test_func != NULL);
850 suite = g_test_get_root();
851 segments = g_strsplit (testpath, "/", -1);
852 for (ui = 0; segments[ui] != NULL; ui++)
854 const char *seg = segments[ui];
855 gboolean islast = segments[ui + 1] == NULL;
856 if (islast && !seg[0])
857 g_error ("invalid test case path: %s", testpath);
859 continue; /* initial or duplicate slash */
862 GTestSuite *csuite = g_test_create_suite (seg);
863 g_test_suite_add_suite (suite, csuite);
868 GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
869 g_test_suite_add (suite, tc);
872 g_strfreev (segments);
877 * @testpath: Slash-separated test case path name for the test.
878 * @test_func: The test function to invoke for this test.
880 * Create a new test case, similar to g_test_create_case(). However
881 * the test is assumed to use no fixture, and test suites are automatically
882 * created on the fly and added to the root fixture, based on the
883 * slash-separated portions of @testpath.
888 g_test_add_func (const char *testpath,
889 void (*test_func) (void))
891 g_return_if_fail (testpath != NULL);
892 g_return_if_fail (testpath[0] == '/');
893 g_return_if_fail (test_func != NULL);
894 g_test_add_vtable (testpath, 0, NULL, NULL, test_func, NULL);
898 * g_test_add_data_func:
899 * @testpath: Slash-separated test case path name for the test.
900 * @test_data: Test data argument for the test function.
901 * @test_func: The test function to invoke for this test.
903 * Create a new test case, similar to g_test_create_case(). However
904 * the test is assumed to use no fixture, and test suites are automatically
905 * created on the fly and added to the root fixture, based on the
906 * slash-separated portions of @testpath. The @test_data argument
907 * will be passed as first argument to @test_func.
912 g_test_add_data_func (const char *testpath,
913 gconstpointer test_data,
914 void (*test_func) (gconstpointer))
916 g_return_if_fail (testpath != NULL);
917 g_return_if_fail (testpath[0] == '/');
918 g_return_if_fail (test_func != NULL);
919 g_test_add_vtable (testpath, 0, test_data, NULL, (void(*)(void)) test_func, NULL);
923 * g_test_create_suite:
924 * @suite_name: a name for the suite
926 * Create a new test suite with the name @suite_name.
928 * Returns: A newly allocated #GTestSuite instance.
933 g_test_create_suite (const char *suite_name)
936 g_return_val_if_fail (suite_name != NULL, NULL);
937 g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
938 g_return_val_if_fail (suite_name[0] != 0, NULL);
939 ts = g_slice_new0 (GTestSuite);
940 ts->name = g_strdup (suite_name);
946 * @suite: a #GTestSuite
947 * @test_case: a #GTestCase
949 * Adds @test_case to @suite.
954 g_test_suite_add (GTestSuite *suite,
955 GTestCase *test_case)
957 g_return_if_fail (suite != NULL);
958 g_return_if_fail (test_case != NULL);
959 suite->cases = g_slist_prepend (suite->cases, test_case);
963 * g_test_suite_add_suite:
964 * @suite: a #GTestSuite
965 * @nestedsuite: another #GTestSuite
967 * Adds @nestedsuite to @suite.
972 g_test_suite_add_suite (GTestSuite *suite,
973 GTestSuite *nestedsuite)
975 g_return_if_fail (suite != NULL);
976 g_return_if_fail (nestedsuite != NULL);
977 suite->suites = g_slist_prepend (suite->suites, nestedsuite);
982 * @gfree_pointer: the pointer to be stored.
984 * Enqueue a pointer to be released with g_free() during the next
985 * teardown phase. This is equivalent to calling g_test_queue_destroy()
986 * with a destroy callback of g_free().
991 g_test_queue_free (gpointer gfree_pointer)
994 g_test_queue_destroy (g_free, gfree_pointer);
998 * g_test_queue_destroy:
999 * @destroy_func: Destroy callback for teardown phase.
1000 * @destroy_data: Destroy callback data.
1002 * This function enqueus a callback @destroy_func() to be executed
1003 * during the next test case teardown phase. This is most useful
1004 * to auto destruct allocted test resources at the end of a test run.
1005 * Resources are released in reverse queue order, that means enqueueing
1006 * callback A before callback B will cause B() to be called before
1007 * A() during teardown.
1012 g_test_queue_destroy (GDestroyNotify destroy_func,
1013 gpointer destroy_data)
1015 DestroyEntry *dentry;
1016 g_return_if_fail (destroy_func != NULL);
1017 dentry = g_slice_new0 (DestroyEntry);
1018 dentry->destroy_func = destroy_func;
1019 dentry->destroy_data = destroy_data;
1020 dentry->next = test_destroy_queue;
1021 test_destroy_queue = dentry;
1025 test_case_run (GTestCase *tc)
1027 gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
1028 test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
1029 if (++test_run_count <= test_skip_count)
1030 g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
1031 else if (test_run_list)
1033 g_print ("%s\n", test_run_name);
1034 g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
1038 GTimer *test_run_timer = g_timer_new();
1039 long double largs[3];
1041 g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
1043 g_timer_start (test_run_timer);
1044 fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
1045 test_run_seed (test_run_seedstr);
1046 if (tc->fixture_setup)
1047 tc->fixture_setup (fixture, tc->test_data);
1048 tc->fixture_test (fixture, tc->test_data);
1050 while (test_destroy_queue)
1052 DestroyEntry *dentry = test_destroy_queue;
1053 test_destroy_queue = dentry->next;
1054 dentry->destroy_func (dentry->destroy_data);
1055 g_slice_free (DestroyEntry, dentry);
1057 if (tc->fixture_teardown)
1058 tc->fixture_teardown (fixture, tc->test_data);
1059 if (tc->fixture_size)
1061 g_timer_stop (test_run_timer);
1062 largs[0] = 0; /* OK */
1063 largs[1] = test_run_forks;
1064 largs[2] = g_timer_elapsed (test_run_timer, NULL);
1065 g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
1066 g_timer_destroy (test_run_timer);
1068 g_free (test_run_name);
1069 test_run_name = old_name;
1070 g_free (test_uri_base);
1071 test_uri_base = old_base;
1076 g_test_run_suite_internal (GTestSuite *suite,
1079 guint n_bad = 0, n_good = 0, bad_suite = 0, l;
1080 gchar *rest, *old_name = test_run_name;
1081 GSList *slist, *reversed;
1082 g_return_val_if_fail (suite != NULL, -1);
1083 while (path[0] == '/')
1086 rest = strchr (path, '/');
1087 l = rest ? MIN (l, rest - path) : l;
1088 test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
1089 reversed = g_slist_reverse (g_slist_copy (suite->cases));
1090 for (slist = reversed; slist; slist = slist->next)
1092 GTestCase *tc = slist->data;
1093 guint n = l ? strlen (tc->name) : 0;
1094 if (l == n && strncmp (path, tc->name, n) == 0)
1097 n_bad += test_case_run (tc) != 0;
1100 g_slist_free (reversed);
1101 reversed = g_slist_reverse (g_slist_copy (suite->suites));
1102 for (slist = reversed; slist; slist = slist->next)
1104 GTestSuite *ts = slist->data;
1105 guint n = l ? strlen (ts->name) : 0;
1106 if (l == n && strncmp (path, ts->name, n) == 0)
1107 bad_suite += g_test_run_suite_internal (ts, rest ? rest : "") != 0;
1109 g_slist_free (reversed);
1110 g_free (test_run_name);
1111 test_run_name = old_name;
1112 return n_bad || bad_suite;
1117 * @suite: a #GTestSuite
1119 * Execute the tests within @suite and all nested #GTestSuites.
1120 * The test suites to be executed are filtered according to
1121 * test path arguments (-p <testpath>) as parsed by g_test_init().
1122 * g_test_run_suite() or g_test_run() may only be called once
1125 * Returns: 0 on success
1130 g_test_run_suite (GTestSuite *suite)
1133 g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
1134 g_return_val_if_fail (g_test_run_once == TRUE, -1);
1135 g_test_run_once = FALSE;
1137 test_paths = g_slist_prepend (test_paths, "");
1140 const char *rest, *path = test_paths->data;
1141 guint l, n = strlen (suite->name);
1142 test_paths = g_slist_delete_link (test_paths, test_paths);
1143 while (path[0] == '/')
1145 if (!n) /* root suite, run unconditionally */
1147 n_bad += 0 != g_test_run_suite_internal (suite, path);
1150 /* regular suite, match path */
1151 rest = strchr (path, '/');
1153 l = rest ? MIN (l, rest - path) : l;
1154 if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
1155 n_bad += 0 != g_test_run_suite_internal (suite, rest ? rest : "");
1161 gtest_default_log_handler (const gchar *log_domain,
1162 GLogLevelFlags log_level,
1163 const gchar *message,
1164 gpointer unused_data)
1166 const gchar *strv[16];
1171 strv[i++] = log_domain;
1174 if (log_level & G_LOG_FLAG_FATAL)
1175 strv[i++] = "FATAL-";
1176 if (log_level & G_LOG_FLAG_RECURSION)
1177 strv[i++] = "RECURSIVE-";
1178 if (log_level & G_LOG_LEVEL_ERROR)
1179 strv[i++] = "ERROR";
1180 if (log_level & G_LOG_LEVEL_CRITICAL)
1181 strv[i++] = "CRITICAL";
1182 if (log_level & G_LOG_LEVEL_WARNING)
1183 strv[i++] = "WARNING";
1184 if (log_level & G_LOG_LEVEL_MESSAGE)
1185 strv[i++] = "MESSAGE";
1186 if (log_level & G_LOG_LEVEL_INFO)
1188 if (log_level & G_LOG_LEVEL_DEBUG)
1189 strv[i++] = "DEBUG";
1191 strv[i++] = message;
1193 msg = g_strjoinv ("", (gchar**) strv);
1194 g_test_log (G_TEST_LOG_ERROR, msg, NULL, 0, NULL);
1195 g_log_default_handler (log_domain, log_level, message, unused_data);
1200 g_assertion_message (const char *domain,
1204 const char *message)
1209 message = "code should not be reached";
1210 g_snprintf (lstr, 32, "%d", line);
1211 s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
1212 "ERROR:(", file, ":", lstr, "):",
1213 func, func[0] ? ":" : "",
1214 " ", message, NULL);
1215 g_printerr ("**\n** %s\n", s);
1216 g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
1222 g_assertion_message_expr (const char *domain,
1228 char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
1229 g_assertion_message (domain, file, line, func, s);
1234 g_assertion_message_cmpnum (const char *domain,
1247 case 'i': s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
1248 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;
1249 case 'f': s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
1250 /* ideally use: floats=%.7g double=%.17g */
1252 g_assertion_message (domain, file, line, func, s);
1257 g_assertion_message_cmpstr (const char *domain,
1266 char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
1267 a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
1268 a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
1271 s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
1274 g_assertion_message (domain, file, line, func, s);
1280 * @str1: a C string or %NULL
1281 * @str2: another C string or %NULL
1283 * Compares @str1 and @str2 like strcmp(). Handles %NULL strings gracefully.
1285 * Returns: -1, 0 or 1, if @str1 is <, == or > than @str2.
1290 g_strcmp0 (const char *str1,
1294 return -(str1 != str2);
1296 return str1 != str2;
1297 return strcmp (str1, str2);
1301 static int /* 0 on success */
1302 kill_child (int pid,
1307 if (patience >= 3) /* try graceful reap */
1309 if (waitpid (pid, status, WNOHANG) > 0)
1312 if (patience >= 2) /* try SIGHUP */
1315 if (waitpid (pid, status, WNOHANG) > 0)
1317 g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
1318 if (waitpid (pid, status, WNOHANG) > 0)
1320 g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
1321 if (waitpid (pid, status, WNOHANG) > 0)
1323 g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
1324 if (waitpid (pid, status, WNOHANG) > 0)
1327 if (patience >= 1) /* try SIGTERM */
1329 kill (pid, SIGTERM);
1330 if (waitpid (pid, status, WNOHANG) > 0)
1332 g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
1333 if (waitpid (pid, status, WNOHANG) > 0)
1335 g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
1336 if (waitpid (pid, status, WNOHANG) > 0)
1340 kill (pid, SIGKILL);
1342 wr = waitpid (pid, status, 0);
1343 while (wr < 0 && errno == EINTR);
1349 g_string_must_read (GString *gstring,
1352 #define STRING_BUFFER_SIZE 4096
1353 char buf[STRING_BUFFER_SIZE];
1356 bytes = read (fd, buf, sizeof (buf));
1358 return 0; /* EOF, calling this function assumes data is available */
1361 g_string_append_len (gstring, buf, bytes);
1364 else if (bytes < 0 && errno == EINTR)
1366 else /* bytes < 0 */
1368 g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1369 return 1; /* ignore error after warning */
1374 g_string_write_out (GString *gstring,
1378 if (*stringpos < gstring->len)
1382 r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
1383 while (r < 0 && errno == EINTR);
1384 *stringpos += MAX (r, 0);
1389 test_trap_clear (void)
1391 test_trap_last_status = 0;
1392 test_trap_last_pid = 0;
1393 g_free (test_trap_last_stdout);
1394 test_trap_last_stdout = NULL;
1395 g_free (test_trap_last_stderr);
1396 test_trap_last_stderr = NULL;
1407 ret = dup2 (fd1, fd2);
1408 while (ret < 0 && errno == EINTR);
1413 test_time_stamp (void)
1417 g_get_current_time (&tv);
1419 stamp = stamp * 1000000 + tv.tv_usec;
1427 * @usec_timeout: Timeout for the forked test in micro seconds.
1428 * @test_trap_flags: Flags to modify forking behaviour.
1430 * Fork the current test program to execute a test case that might
1431 * not return or that might abort. The forked test case is aborted
1432 * and considered failing if its run time exceeds @usec_timeout.
1433 * The forking behavior can be configured with the following flags:
1434 * %G_TEST_TRAP_SILENCE_STDOUT - redirect stdout of the test child
1435 * to /dev/null so it cannot be observed on the console during test
1436 * runs. The actual output is still captured though to allow later
1437 * tests with g_test_trap_assert_stdout().
1438 * %G_TEST_TRAP_SILENCE_STDERR - redirect stderr of the test child
1439 * to /dev/null so it cannot be observed on the console during test
1440 * runs. The actual output is still captured though to allow later
1441 * tests with g_test_trap_assert_stderr().
1442 * %G_TEST_TRAP_INHERIT_STDIN - if this flag is given, stdin of the
1443 * forked child process is shared with stdin of its parent process.
1444 * It is redirected to /dev/null otherwise.
1446 * In the following example, the test code forks, the forked child
1447 * process produces some sample output and exits successfully.
1448 * The forking parent process then asserts successfull child program
1449 * termination and validates child program outputs.
1453 * test_fork_patterns (void)
1455 * if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
1457 * g_print ("some stdout text: somagic17\n");
1458 * g_printerr ("some stderr text: semagic43\n");
1459 * exit (0); /* successful test run */
1461 * g_test_trap_assert_passed();
1462 * g_test_trap_assert_stdout ("*somagic17*");
1463 * g_test_trap_assert_stderr ("*semagic43*");
1467 * This function is implemented only on Unix platforms.
1469 * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
1474 g_test_trap_fork (guint64 usec_timeout,
1475 GTestTrapFlags test_trap_flags)
1478 gboolean pass_on_forked_log = FALSE;
1479 int stdout_pipe[2] = { -1, -1 };
1480 int stderr_pipe[2] = { -1, -1 };
1481 int stdtst_pipe[2] = { -1, -1 };
1483 if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
1484 g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
1485 signal (SIGCHLD, SIG_DFL);
1486 test_trap_last_pid = fork ();
1487 if (test_trap_last_pid < 0)
1488 g_error ("failed to fork test program: %s", g_strerror (errno));
1489 if (test_trap_last_pid == 0) /* child */
1492 close (stdout_pipe[0]);
1493 close (stderr_pipe[0]);
1494 close (stdtst_pipe[0]);
1495 if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
1496 fd0 = open ("/dev/null", O_RDONLY);
1497 if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
1498 g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
1501 if (stdout_pipe[1] >= 3)
1502 close (stdout_pipe[1]);
1503 if (stderr_pipe[1] >= 3)
1504 close (stderr_pipe[1]);
1505 test_log_fd = stdtst_pipe[1];
1510 GString *sout = g_string_new (NULL);
1511 GString *serr = g_string_new (NULL);
1513 int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
1515 close (stdout_pipe[1]);
1516 close (stderr_pipe[1]);
1517 close (stdtst_pipe[1]);
1518 sstamp = test_time_stamp();
1519 /* read data until we get EOF on all pipes */
1520 while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
1526 if (stdout_pipe[0] >= 0)
1527 FD_SET (stdout_pipe[0], &fds);
1528 if (stderr_pipe[0] >= 0)
1529 FD_SET (stderr_pipe[0], &fds);
1530 if (stdtst_pipe[0] >= 0)
1531 FD_SET (stdtst_pipe[0], &fds);
1533 tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
1534 ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
1535 if (ret < 0 && errno != EINTR)
1537 g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
1540 if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
1541 g_string_must_read (sout, stdout_pipe[0]) == 0)
1543 close (stdout_pipe[0]);
1544 stdout_pipe[0] = -1;
1546 if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
1547 g_string_must_read (serr, stderr_pipe[0]) == 0)
1549 close (stderr_pipe[0]);
1550 stderr_pipe[0] = -1;
1552 if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
1554 guint8 buffer[4096];
1555 gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
1556 if (r > 0 && test_log_fd > 0)
1558 l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
1559 while (l < 0 && errno == EINTR);
1560 if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
1562 close (stdtst_pipe[0]);
1563 stdtst_pipe[0] = -1;
1566 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
1567 g_string_write_out (sout, 1, &soutpos);
1568 if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
1569 g_string_write_out (serr, 2, &serrpos);
1572 guint64 nstamp = test_time_stamp();
1574 sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
1575 if (usec_timeout < nstamp - sstamp)
1577 /* timeout reached, need to abort the child now */
1578 kill_child (test_trap_last_pid, &status, 3);
1579 test_trap_last_status = 1024; /* timeout */
1580 if (0 && WIFSIGNALED (status))
1581 g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
1587 close (stdout_pipe[0]);
1588 close (stderr_pipe[0]);
1589 close (stdtst_pipe[0]);
1594 wr = waitpid (test_trap_last_pid, &status, 0);
1595 while (wr < 0 && errno == EINTR);
1596 if (WIFEXITED (status)) /* normal exit */
1597 test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
1598 else if (WIFSIGNALED (status))
1599 test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
1600 else /* WCOREDUMP (status) */
1601 test_trap_last_status = 512; /* coredump */
1603 test_trap_last_stdout = g_string_free (sout, FALSE);
1604 test_trap_last_stderr = g_string_free (serr, FALSE);
1608 g_message ("Not implemented: g_test_trap_fork");
1615 * g_test_trap_has_passed:
1617 * Check the result of the last g_test_trap_fork() call.
1619 * Returns: %TRUE if the last forked child terminated successfully.
1624 g_test_trap_has_passed (void)
1626 return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
1630 * g_test_trap_reached_timeout:
1632 * Check the result of the last g_test_trap_fork() call.
1634 * Returns: %TRUE if the last forked child got killed due to a fork timeout.
1639 g_test_trap_reached_timeout (void)
1641 return 0 != (test_trap_last_status & 1024); /* timeout flag */
1645 g_test_trap_assertions (const char *domain,
1649 guint64 assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
1650 const char *pattern)
1653 gboolean must_pass = assertion_flags == 0;
1654 gboolean must_fail = assertion_flags == 1;
1655 gboolean match_result = 0 == (assertion_flags & 1);
1656 const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
1657 const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
1658 const char *match_error = match_result ? "failed to match" : "contains invalid match";
1659 if (test_trap_last_pid == 0)
1660 g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
1661 if (must_pass && !g_test_trap_has_passed())
1663 char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
1664 g_assertion_message (domain, file, line, func, msg);
1667 if (must_fail && g_test_trap_has_passed())
1669 char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
1670 g_assertion_message (domain, file, line, func, msg);
1673 if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
1675 char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
1676 g_assertion_message (domain, file, line, func, msg);
1679 if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
1681 char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
1682 g_assertion_message (domain, file, line, func, msg);
1689 gstring_overwrite_int (GString *gstring,
1693 vuint = g_htonl (vuint);
1694 g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
1698 gstring_append_int (GString *gstring,
1701 vuint = g_htonl (vuint);
1702 g_string_append_len (gstring, (const gchar*) &vuint, 4);
1706 gstring_append_double (GString *gstring,
1709 union { double vdouble; guint64 vuint64; } u;
1710 u.vdouble = vdouble;
1711 u.vuint64 = GUINT64_TO_BE (u.vuint64);
1712 g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
1716 g_test_log_dump (GTestLogMsg *msg,
1719 GString *gstring = g_string_sized_new (1024);
1721 gstring_append_int (gstring, 0); /* message length */
1722 gstring_append_int (gstring, msg->log_type);
1723 gstring_append_int (gstring, msg->n_strings);
1724 gstring_append_int (gstring, msg->n_nums);
1725 gstring_append_int (gstring, 0); /* reserved */
1726 for (ui = 0; ui < msg->n_strings; ui++)
1728 guint l = strlen (msg->strings[ui]);
1729 gstring_append_int (gstring, l);
1730 g_string_append_len (gstring, msg->strings[ui], l);
1732 for (ui = 0; ui < msg->n_nums; ui++)
1733 gstring_append_double (gstring, msg->nums[ui]);
1734 *len = gstring->len;
1735 gstring_overwrite_int (gstring, 0, *len); /* message length */
1736 return (guint8*) g_string_free (gstring, FALSE);
1739 static inline long double
1740 net_double (const gchar **ipointer)
1742 union { guint64 vuint64; double vdouble; } u;
1743 guint64 aligned_int64;
1744 memcpy (&aligned_int64, *ipointer, 8);
1746 u.vuint64 = GUINT64_FROM_BE (aligned_int64);
1750 static inline guint32
1751 net_int (const gchar **ipointer)
1753 guint32 aligned_int;
1754 memcpy (&aligned_int, *ipointer, 4);
1756 return g_ntohl (aligned_int);
1760 g_test_log_extract (GTestLogBuffer *tbuffer)
1762 const gchar *p = tbuffer->data->str;
1765 if (tbuffer->data->len < 4 * 5)
1767 mlength = net_int (&p);
1768 if (tbuffer->data->len < mlength)
1770 msg.log_type = net_int (&p);
1771 msg.n_strings = net_int (&p);
1772 msg.n_nums = net_int (&p);
1773 if (net_int (&p) == 0)
1776 msg.strings = g_new0 (gchar*, msg.n_strings + 1);
1777 msg.nums = g_new0 (long double, msg.n_nums);
1778 for (ui = 0; ui < msg.n_strings; ui++)
1780 guint sl = net_int (&p);
1781 msg.strings[ui] = g_strndup (p, sl);
1784 for (ui = 0; ui < msg.n_nums; ui++)
1785 msg.nums[ui] = net_double (&p);
1786 if (p <= tbuffer->data->str + mlength)
1788 g_string_erase (tbuffer->data, 0, mlength);
1789 tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
1794 g_strfreev (msg.strings);
1795 g_error ("corrupt log stream from test program");
1800 * g_test_log_buffer_new:
1802 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1805 g_test_log_buffer_new (void)
1807 GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
1808 tb->data = g_string_sized_new (1024);
1813 * g_test_log_buffer_free
1815 * Internal function for gtester to free test log messages, no ABI guarantees provided.
1818 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
1820 g_return_if_fail (tbuffer != NULL);
1821 while (tbuffer->msgs)
1822 g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
1823 g_string_free (tbuffer->data, TRUE);
1828 * g_test_log_buffer_push
1830 * Internal function for gtester to decode test log messages, no ABI guarantees provided.
1833 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
1835 const guint8 *bytes)
1837 g_return_if_fail (tbuffer != NULL);
1840 gboolean more_messages;
1841 g_return_if_fail (bytes != NULL);
1842 g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
1844 more_messages = g_test_log_extract (tbuffer);
1845 while (more_messages);
1850 * g_test_log_buffer_pop:
1852 * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
1855 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
1857 GTestLogMsg *msg = NULL;
1858 g_return_val_if_fail (tbuffer != NULL, NULL);
1861 GSList *slist = g_slist_last (tbuffer->msgs);
1863 tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
1869 * g_test_log_msg_free:
1871 * Internal function for gtester to free test log messages, no ABI guarantees provided.
1874 g_test_log_msg_free (GTestLogMsg *tmsg)
1876 g_return_if_fail (tmsg != NULL);
1877 g_strfreev (tmsg->strings);
1878 g_free (tmsg->nums);
1882 /* --- macros docs START --- */
1885 * @testpath: The test path for a new test case.
1886 * @Fixture: The type of a fixture data structure.
1887 * @tdata: Data argument for the test functions.
1888 * @fsetup: The function to set up the fixture data.
1889 * @ftest: The actual test function.
1890 * @fteardown: The function to tear down the fixture data.
1892 * Hook up a new test case at @testpath, similar to g_test_add_func().
1893 * A fixture data structure with setup and teardown function may be provided
1894 * though, similar to g_test_create_case().
1895 * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
1896 * fteardown() callbacks can expect a @Fixture pointer as first argument in
1897 * a type safe manner.
1901 /* --- macros docs END --- */
1903 #define __G_TEST_UTILS_C__
1904 #include "galiasdef.c"