Testing

Testing — a test framework

Functions

void g_test_minimized_result ()
void g_test_maximized_result ()
void g_test_init ()
#define g_test_initialized
#define g_test_quick
#define g_test_slow
#define g_test_thorough
#define g_test_perf
#define g_test_verbose
#define g_test_undefined
#define g_test_quiet
gboolean g_test_subprocess ()
int g_test_run ()
void (*GTestFunc) ()
void g_test_add_func ()
void (*GTestDataFunc) ()
void g_test_add_data_func ()
void g_test_add_data_func_full ()
#define g_test_add()
gchar * g_test_build_filename ()
const gchar * g_test_get_filename ()
const gchar * g_test_get_dir ()
void g_test_fail ()
void g_test_skip ()
void g_test_incomplete ()
gboolean g_test_failed ()
void g_test_message ()
void g_test_bug_base ()
void g_test_bug ()
gboolean (*GTestLogFatalFunc) ()
void g_test_log_set_fatal_handler ()
void g_test_timer_start ()
double g_test_timer_elapsed ()
double g_test_timer_last ()
void g_test_queue_free ()
void g_test_queue_destroy ()
#define g_test_queue_unref()
void g_test_expect_message ()
#define g_test_assert_expected_messages
void g_test_trap_subprocess ()
gboolean g_test_trap_has_passed ()
gboolean g_test_trap_reached_timeout ()
#define g_test_trap_assert_passed
#define g_test_trap_assert_failed
#define g_test_trap_assert_stdout()
#define g_test_trap_assert_stdout_unmatched()
#define g_test_trap_assert_stderr()
#define g_test_trap_assert_stderr_unmatched()
gboolean g_test_trap_fork ()
#define g_test_rand_bit
gint32 g_test_rand_int ()
gint32 g_test_rand_int_range ()
double g_test_rand_double ()
double g_test_rand_double_range ()
#define g_assert()
#define g_assert_not_reached
#define g_assert_cmpstr()
#define g_assert_cmpint()
#define g_assert_cmpuint()
#define g_assert_cmphex()
#define g_assert_cmpfloat()
#define g_assert_cmpmem()
#define g_assert_no_error()
#define g_assert_error()
#define g_assert_true()
#define g_assert_false()
#define g_assert_null()
#define g_assert_nonnull()
void g_test_set_nonfatal_assertions ()
void (*GTestFixtureFunc) ()
GTestCase * g_test_create_case ()
GTestSuite * g_test_create_suite ()
GTestSuite * g_test_get_root ()
void g_test_suite_add ()
void g_test_suite_add_suite ()
int g_test_run_suite ()

Types and Values

Includes

#include <glib.h>
#include <glib/gi18n.h>

Description

GLib provides a framework for writing and maintaining unit tests in parallel to the code they are testing. The API is designed according to established concepts found in the other test frameworks (JUnit, NUnit, RUnit), which in turn is based on smalltalk unit testing concepts.

  • Test case: Tests (test methods) are grouped together with their fixture into test cases.

  • Fixture: A test fixture consists of fixture data and setup and teardown methods to establish the environment for the test functions. We use fresh fixtures, i.e. fixtures are newly set up and torn down around each test invocation to avoid dependencies between tests.

  • Test suite: Test cases can be grouped into test suites, to allow subsets of the available tests to be run. Test suites can be grouped into other test suites as well.

The API is designed to handle creation and registration of test suites and test cases implicitly. A simple call like

1
g_test_add_func ("/misc/assertions", test_assertions);

creates a test suite called "misc" with a single test case named "assertions", which consists of running the test_assertions function.

In addition to the traditional g_assert(), the test framework provides an extended set of assertions for comparisons: g_assert_cmpfloat(), g_assert_cmpint(), g_assert_cmpuint(), g_assert_cmphex(), g_assert_cmpstr(), and g_assert_cmpmem(). The advantage of these variants over plain g_assert() is that the assertion messages can be more elaborate, and include the values of the compared entities.

A full example of creating a test suite with two tests using fixtures:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <glib.h>
#include <locale.h>

typedef struct {
  MyObject *obj;
  OtherObject *helper;
} MyObjectFixture;

static void
my_object_fixture_set_up (MyObjectFixture *fixture,
                          gconstpointer user_data)
{
  fixture->obj = my_object_new ();
  my_object_set_prop1 (fixture->obj, "some-value");
  my_object_do_some_complex_setup (fixture->obj, user_data);

  fixture->helper = other_object_new ();
}

static void
my_object_fixture_tear_down (MyObjectFixture *fixture,
                             gconstpointer user_data)
{
  g_clear_object (&fixture->helper);
  g_clear_object (&fixture->obj);
}

static void
test_my_object_test1 (MyObjectFixture *fixture,
                      gconstpointer user_data)
{
  g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "initial-value");
}

static void
test_my_object_test2 (MyObjectFixture *fixture,
                      gconstpointer user_data)
{
  my_object_do_some_work_using_helper (fixture->obj, fixture->helper);
  g_assert_cmpstr (my_object_get_property (fixture->obj), ==, "updated-value");
}

int
main (int argc, char *argv[])
{
  setlocale (LC_ALL, "");

  g_test_init (&argc, &argv, NULL);
  g_test_bug_base ("http://bugzilla.gnome.org/show_bug.cgi?id=");

  // Define the tests.
  g_test_add ("/my-object/test1", MyObjectFixture, "some-user-data",
              my_object_fixture_set_up, test_my_object_test1,
              my_object_fixture_tear_down);
  g_test_add ("/my-object/test2", MyObjectFixture, "some-user-data",
              my_object_fixture_set_up, test_my_object_test2,
              my_object_fixture_tear_down);

  return g_test_run ();
}

### Integrating GTest in your project

If you are using the Meson build system, you will typically use the provided test() primitive to call the test binaries, e.g.:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
test(
  'foo',
  executable('foo', 'foo.c', dependencies: deps),
  env: [
    'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
    'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
  ],
)

test(
  'bar',
  executable('bar', 'bar.c', dependencies: deps),
  env: [
    'G_TEST_SRCDIR=@0@'.format(meson.current_source_dir()),
    'G_TEST_BUILDDIR=@0@'.format(meson.current_build_dir()),
  ],
)

If you are using Autotools, you're strongly encouraged to use the Automake TAP harness; GLib provides template files for easily integrating with it:

You can copy these files in your own project's root directory, and then set up your Makefile.am file to reference them, for instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
include $(top_srcdir)/glib-tap.mk

# test binaries
test_programs = \
  foo \
  bar

# data distributed in the tarball
dist_test_data = \
  foo.data.txt \
  bar.data.txt

# data not distributed in the tarball
test_data = \
  blah.data.txt

Make sure to distribute the TAP files, using something like the following in your top-level Makefile.am:

1
2
3
EXTRA_DIST += \
  tap-driver.sh \
  tap-test

glib-tap.mk will be distributed implicitly due to being included in a Makefile.am. All three files should be added to version control.

If you don't have access to the Autotools TAP harness, you can use the gtester and gtester-report tools, and use the glib.mk Automake template provided by GLib.

Functions

g_test_minimized_result ()

void
g_test_minimized_result (double minimized_quantity,
                         const char *format,
                         ...);

Report the result of a performance or measurement test. The test should generally strive to minimize the reported quantities (smaller values are better than larger ones), this and minimized_quantity can determine sorting order for test result reports.

Parameters

minimized_quantity

the reported value

 

format

the format string of the report message

 

...

arguments to pass to the printf() function

 

Since: 2.16


g_test_maximized_result ()

void
g_test_maximized_result (double maximized_quantity,
                         const char *format,
                         ...);

Report the result of a performance or measurement test. The test should generally strive to maximize the reported quantities (larger values are better than smaller ones), this and maximized_quantity can determine sorting order for test result reports.

Parameters

maximized_quantity

the reported value

 

format

the format string of the report message

 

...

arguments to pass to the printf() function

 

Since: 2.16


g_test_init ()

void
g_test_init (int *argc,
             char ***argv,
             ...);

Initialize the GLib testing framework, e.g. by seeding the test random number generator, the name for g_get_prgname() and parsing test related command line args.

So far, the following arguments are understood:

  • -l: List test cases available in a test executable.

  • --seed=SEED: Provide a random seed to reproduce test runs using random numbers.

  • --verbose: Run tests verbosely.

  • -q, --quiet: Run tests quietly.

  • -p PATH: Execute all tests matching the given path.

  • -s PATH: Skip all tests matching the given path. This can also be used to force a test to run that would otherwise be skipped (ie, a test whose name contains "/subprocess").

  • -m {perf|slow|thorough|quick|undefined|no-undefined}: Execute tests according to these test modes:

    perf: Performance tests, may take long and report results (off by default).

    slow, thorough: Slow and thorough tests, may take quite long and maximize coverage (off by default).

    quick: Quick tests, should run really quickly and give good coverage (the default).

    undefined: Tests for undefined behaviour, may provoke programming errors under g_test_trap_subprocess() or g_test_expect_message() to check that appropriate assertions or warnings are given (the default).

    no-undefined: Avoid tests for undefined behaviour

  • --debug-log: Debug test logging output.

Parameters

argc

Address of the argc parameter of the main() function. Changed if any arguments were handled.

 

argv

Address of the argv parameter of main(). Any parameters understood by g_test_init() stripped before return.

 

...

NULL-terminated list of special options. Currently the only defined option is "no_g_set_prgname", which will cause g_test_init() to not call g_set_prgname().

 

Since: 2.16


g_test_initialized

#define             g_test_initialized()

Returns TRUE if g_test_init() has been called.

Returns

TRUE if g_test_init() has been called.

Since: 2.36


g_test_quick

#define             g_test_quick()

Returns TRUE if tests are run in quick mode. Exactly one of g_test_quick() and g_test_slow() is active in any run; there is no "medium speed".

By default, tests are run in quick mode. In tests that use g_test_init(), the options -m quick, -m slow and -m thorough can be used to change this.

Returns

TRUE if in quick mode


g_test_slow

#define             g_test_slow()

Returns TRUE if tests are run in slow mode. Exactly one of g_test_quick() and g_test_slow() is active in any run; there is no "medium speed".

By default, tests are run in quick mode. In tests that use g_test_init(), the options -m quick, -m slow and -m thorough can be used to change this.

Returns

the opposite of g_test_quick()


g_test_thorough

#define             g_test_thorough()

Returns TRUE if tests are run in thorough mode, equivalent to g_test_slow().

By default, tests are run in quick mode. In tests that use g_test_init(), the options -m quick, -m slow and -m thorough can be used to change this.

Returns

the same thing as g_test_slow()


g_test_perf

#define             g_test_perf()

Returns TRUE if tests are run in performance mode.

By default, tests are run in quick mode. In tests that use g_test_init(), the option -m perf enables performance tests, while -m quick disables them.

Returns

TRUE if in performance mode


g_test_verbose

#define             g_test_verbose()

Returns TRUE if tests are run in verbose mode. In tests that use g_test_init(), the option --verbose enables this, while -q or --quiet disables it. The default is neither g_test_verbose() nor g_test_quiet().

Returns

TRUE if in verbose mode


g_test_undefined

#define             g_test_undefined()

Returns TRUE if tests may provoke assertions and other formally-undefined behaviour, to verify that appropriate warnings are given. It might, in some cases, be useful to turn this off with if running tests under valgrind; in tests that use g_test_init(), the option -m no-undefined disables those tests, while -m undefined explicitly enables them (the default behaviour).

Returns

TRUE if tests may provoke programming errors


g_test_quiet

#define             g_test_quiet()

Returns TRUE if tests are run in quiet mode. In tests that use g_test_init(), the option -q or --quiet enables this, while --verbose disables it. The default is neither g_test_verbose() nor g_test_quiet().

Returns

TRUE if in quiet mode


g_test_subprocess ()

gboolean
g_test_subprocess (void);

Returns TRUE (after g_test_init() has been called) if the test program is running under g_test_trap_subprocess().

Returns

TRUE if the test program is running under g_test_trap_subprocess().

Since: 2.38


g_test_run ()

int
g_test_run (void);

Runs all tests under the toplevel suite which can be retrieved with g_test_get_root(). Similar to g_test_run_suite(), the test cases to be run are filtered according to test path arguments (-p testpath and -s testpath) as parsed by g_test_init(). g_test_run_suite() or g_test_run() may only be called once in a program.

In general, the tests and sub-suites within each suite are run in the order in which they are defined. However, note that prior to GLib 2.36, there was a bug in the g_test_add_* functions which caused them to create multiple suites with the same name, meaning that if you created tests "/foo/simple", "/bar/simple", and "/foo/using-bar" in that order, they would get run in that order (since g_test_run() would run the first "/foo" suite, then the "/bar" suite, then the second "/foo" suite). As of 2.36, this bug is fixed, and adding the tests in that order would result in a running order of "/foo/simple", "/foo/using-bar", "/bar/simple". If this new ordering is sub-optimal (because it puts more-complicated tests before simpler ones, making it harder to figure out exactly what has failed), you can fix it by changing the test paths to group tests by suite in a way that will result in the desired running order. Eg, "/simple/foo", "/simple/bar", "/complex/foo-using-bar".

However, you should never make the actual result of a test depend on the order that tests are run in. If you need to ensure that some particular code runs before or after a given test case, use g_test_add(), which lets you specify setup and teardown functions.

If all tests are skipped, this function will return 0 if producing TAP output, or 77 (treated as "skip test" by Automake) otherwise.

Returns

0 on success, 1 on failure (assuming it returns at all), 0 or 77 if all tests were skipped with g_test_skip()

Since: 2.16


GTestFunc ()

void
(*GTestFunc) (void);

The type used for test case functions.

Since: 2.28


g_test_add_func ()

void
g_test_add_func (const char *testpath,
                 GTestFunc test_func);

Create a new test case, similar to g_test_create_case(). However the test is assumed to use no fixture, and test suites are automatically created on the fly and added to the root fixture, based on the slash-separated portions of testpath .

If testpath includes the component "subprocess" anywhere in it, the test will be skipped by default, and only run if explicitly required via the -p command-line option or g_test_trap_subprocess().

Parameters

testpath

/-separated test case path name for the test.

 

test_func

The test function to invoke for this test.

[scope async]

Since: 2.16


GTestDataFunc ()

void
(*GTestDataFunc) (gconstpointer user_data);

The type used for test case functions that take an extra pointer argument.

Parameters

user_data

the data provided when registering the test

 

Since: 2.28


g_test_add_data_func ()

void
g_test_add_data_func (const char *testpath,
                      gconstpointer test_data,
                      GTestDataFunc test_func);

Create a new test case, similar to g_test_create_case(). However the test is assumed to use no fixture, and test suites are automatically created on the fly and added to the root fixture, based on the slash-separated portions of testpath . The test_data argument will be passed as first argument to test_func .

If testpath includes the component "subprocess" anywhere in it, the test will be skipped by default, and only run if explicitly required via the -p command-line option or g_test_trap_subprocess().

Parameters

testpath

/-separated test case path name for the test.

 

test_data

Test data argument for the test function.

 

test_func

The test function to invoke for this test.

[scope async]

Since: 2.16


g_test_add_data_func_full ()

void
g_test_add_data_func_full (const char *testpath,
                           gpointer test_data,
                           GTestDataFunc test_func,
                           GDestroyNotify data_free_func);

Create a new test case, as with g_test_add_data_func(), but freeing test_data after the test run is complete.

Parameters

testpath

/-separated test case path name for the test.

 

test_data

Test data argument for the test function.

 

test_func

The test function to invoke for this test.

 

data_free_func

GDestroyNotify for test_data .

 

Since: 2.34


g_test_add()

#define             g_test_add(testpath, Fixture, tdata, fsetup, ftest, fteardown)

Hook up a new test case at testpath , similar to g_test_add_func(). A fixture data structure with setup and teardown functions may be provided, similar to g_test_create_case().

g_test_add() is implemented as a macro, so that the fsetup(), ftest() and fteardown() callbacks can expect a Fixture pointer as their first argument in a type safe manner. They otherwise have type GTestFixtureFunc.

Parameters

testpath

The test path for a new test case.

 

Fixture

The type of a fixture data structure.

 

tdata

Data argument for the test functions.

 

fsetup

The function to set up the fixture data.

 

ftest

The actual test function.

 

fteardown

The function to tear down the fixture data.

 

Since: 2.16


g_test_build_filename ()

gchar *
g_test_build_filename (GTestFileType file_type,
                       const gchar *first_path,
                       ...);

Creates the pathname to a data file that is required for a test.

This function is conceptually similar to g_build_filename() except that the first argument has been replaced with a GTestFileType argument.

The data file should either have been distributed with the module containing the test (G_TEST_DIST) or built as part of the build system of that module (G_TEST_BUILT).

In order for this function to work in srcdir != builddir situations, the G_TEST_SRCDIR and G_TEST_BUILDDIR environment variables need to have been defined. As of 2.38, this is done by the glib.mk included in GLib. Please ensure that your copy is up to date before using this function.

In case neither variable is set, this function will fall back to using the dirname portion of argv[0], possibly removing ".libs". This allows for casual running of tests directly from the commandline in the srcdir == builddir case and should also support running of installed tests, assuming the data files have been installed in the same relative path as the test binary.

Parameters

file_type

the type of file (built vs. distributed)

 

first_path

the first segment of the pathname

 

...

NULL-terminated additional path segments

 

Returns

the path of the file, to be freed using g_free()

Since: 2.38


g_test_get_filename ()

const gchar *
g_test_get_filename (GTestFileType file_type,
                     const gchar *first_path,
                     ...);

Gets the pathname to a data file that is required for a test.

This is the same as g_test_build_filename() with two differences. The first difference is that must only use this function from within a testcase function. The second difference is that you need not free the return value -- it will be automatically freed when the testcase finishes running.

It is safe to use this function from a thread inside of a testcase but you must ensure that all such uses occur before the main testcase function returns (ie: it is best to ensure that all threads have been joined).

Parameters

file_type

the type of file (built vs. distributed)

 

first_path

the first segment of the pathname

 

...

NULL-terminated additional path segments

 

Returns

the path, automatically freed at the end of the testcase

Since: 2.38


g_test_get_dir ()

const gchar *
g_test_get_dir (GTestFileType file_type);

Gets the pathname of the directory containing test files of the type specified by file_type .

This is approximately the same as calling g_test_build_filename("."), but you don't need to free the return value.

Parameters

file_type

the type of file (built vs. distributed)

 

Returns

the path of the directory, owned by GLib.

[type filename]

Since: 2.38


g_test_fail ()

void
g_test_fail (void);

Indicates that a test failed. This function can be called multiple times from the same test. You can use this function if your test failed in a recoverable way.

Do not use this function if the failure of a test could cause other tests to malfunction.

Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.

If not called from inside a test, this function does nothing.

Since: 2.30


g_test_skip ()

void
g_test_skip (const gchar *msg);

Indicates that a test was skipped.

Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.

If not called from inside a test, this function does nothing.

Parameters

msg

explanation.

[nullable]

Since: 2.38


g_test_incomplete ()

void
g_test_incomplete (const gchar *msg);

Indicates that a test failed because of some incomplete functionality. This function can be called multiple times from the same test.

Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.

If not called from inside a test, this function does nothing.

Parameters

msg

explanation.

[nullable]

Since: 2.38


g_test_failed ()

gboolean
g_test_failed (void);

Returns whether a test has already failed. This will be the case when g_test_fail(), g_test_incomplete() or g_test_skip() have been called, but also if an assertion has failed.

This can be useful to return early from a test if continuing after a failed assertion might be harmful.

The return value of this function is only meaningful if it is called from inside a test function.

Returns

TRUE if the test has failed

Since: 2.38


g_test_message ()

void
g_test_message (const char *format,
                ...);

Add a message to the test report.

Parameters

format

the format string

 

...

printf-like arguments to format

 

Since: 2.16


g_test_bug_base ()

void
g_test_bug_base (const char *uri_pattern);

Specify the base URI for bug reports.

The base URI is used to construct bug report messages for g_test_message() when g_test_bug() is called. Calling this function outside of a test case sets the default base URI for all test cases. Calling it from within a test case changes the base URI for the scope of the test case only. Bug URIs are constructed by appending a bug specific URI portion to uri_pattern , or by replacing the special string '%s' within uri_pattern if that is present.

Parameters

uri_pattern

the base pattern for bug URIs

 

Since: 2.16


g_test_bug ()

void
g_test_bug (const char *bug_uri_snippet);

This function adds a message to test reports that associates a bug URI with a test case. Bug URIs are constructed from a base URI set with g_test_bug_base() and bug_uri_snippet .

Parameters

bug_uri_snippet

Bug specific bug tracker URI portion.

 

Since: 2.16


GTestLogFatalFunc ()

gboolean
(*GTestLogFatalFunc) (const gchar *log_domain,
                      GLogLevelFlags log_level,
                      const gchar *message,
                      gpointer user_data);

Specifies the prototype of fatal log handler functions.

Parameters

log_domain

the log domain of the message

 

log_level

the log level of the message (including the fatal and recursion flags)

 

message

the message to process

 

user_data

user data, set in g_test_log_set_fatal_handler()

 

Returns

TRUE if the program should abort, FALSE otherwise

Since: 2.22


g_test_log_set_fatal_handler ()

void
g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
                              gpointer user_data);

Installs a non-error fatal log handler which can be used to decide whether log messages which are counted as fatal abort the program.

The use case here is that you are running a test case that depends on particular libraries or circumstances and cannot prevent certain known critical or warning messages. So you install a handler that compares the domain and message to precisely not abort in such a case.

Note that the handler is reset at the beginning of any test case, so you have to set it inside each test function which needs the special behavior.

This handler has no effect on g_error messages.

This handler also has no effect on structured log messages (using g_log_structured() or g_log_structured_array()). To change the fatal behaviour for specific log messages, programs must install a custom log writer function using g_log_set_writer_func().See Using Structured Logging.

Parameters

log_func

the log handler function.

 

user_data

data passed to the log handler.

 

Since: 2.22


g_test_timer_start ()

void
g_test_timer_start (void);

Start a timing test. Call g_test_timer_elapsed() when the task is supposed to be done. Call this function again to restart the timer.

Since: 2.16


g_test_timer_elapsed ()

double
g_test_timer_elapsed (void);

Get the time since the last start of the timer with g_test_timer_start().

Returns

the time since the last start of the timer, as a double

Since: 2.16


g_test_timer_last ()

double
g_test_timer_last (void);

Report the last result of g_test_timer_elapsed().

Returns

the last result of g_test_timer_elapsed(), as a double

Since: 2.16


g_test_queue_free ()

void
g_test_queue_free (gpointer gfree_pointer);

Enqueue a pointer to be released with g_free() during the next teardown phase. This is equivalent to calling g_test_queue_destroy() with a destroy callback of g_free().

Parameters

gfree_pointer

the pointer to be stored.

 

Since: 2.16


g_test_queue_destroy ()

void
g_test_queue_destroy (GDestroyNotify destroy_func,
                      gpointer destroy_data);

This function enqueus a callback destroy_func to be executed during the next test case teardown phase. This is most useful to auto destruct allocated test resources at the end of a test run. Resources are released in reverse queue order, that means enqueueing callback A before callback B will cause B() to be called before A() during teardown.

Parameters

destroy_func

Destroy callback for teardown phase.

 

destroy_data

Destroy callback data.

 

Since: 2.16


g_test_queue_unref()

#define             g_test_queue_unref(gobject)

Enqueue an object to be released with g_object_unref() during the next teardown phase. This is equivalent to calling g_test_queue_destroy() with a destroy callback of g_object_unref().

Parameters

gobject

the object to unref

 

Since: 2.16


g_test_expect_message ()

void
g_test_expect_message (const gchar *log_domain,
                       GLogLevelFlags log_level,
                       const gchar *pattern);

Indicates that a message with the given log_domain and log_level , with text matching pattern , is expected to be logged. When this message is logged, it will not be printed, and the test case will not abort.

This API may only be used with the old logging API (g_log() without G_LOG_USE_STRUCTURED defined). It will not work with the structured logging API. See Testing for Messages.

Use g_test_assert_expected_messages() to assert that all previously-expected messages have been seen and suppressed.

You can call this multiple times in a row, if multiple messages are expected as a result of a single call. (The messages must appear in the same order as the calls to g_test_expect_message().)

For example:

1
2
3
4
5
6
7
// g_main_context_push_thread_default() should fail if the
// context is already owned by another thread.
g_test_expect_message (G_LOG_DOMAIN,
                       G_LOG_LEVEL_CRITICAL,
                       "assertion*acquired_context*failed");
g_main_context_push_thread_default (bad_context);
g_test_assert_expected_messages ();

Note that you cannot use this to test g_error() messages, since g_error() intentionally never returns even if the program doesn't abort; use g_test_trap_subprocess() in this case.

If messages at G_LOG_LEVEL_DEBUG are emitted, but not explicitly expected via g_test_expect_message() then they will be ignored.

Parameters

log_domain

the log domain of the message.

[nullable]

log_level

the log level of the message

 

pattern

a glob-style pattern

 

Since: 2.34


g_test_assert_expected_messages

#define             g_test_assert_expected_messages()

Asserts that all messages previously indicated via g_test_expect_message() have been seen and suppressed.

This API may only be used with the old logging API (g_log() without G_LOG_USE_STRUCTURED defined). It will not work with the structured logging API. See Testing for Messages.

If messages at G_LOG_LEVEL_DEBUG are emitted, but not explicitly expected via g_test_expect_message() then they will be ignored.

Since: 2.34


g_test_trap_subprocess ()

void
g_test_trap_subprocess (const char *test_path,
                        guint64 usec_timeout,
                        GTestSubprocessFlags test_flags);

Respawns the test program to run only test_path in a subprocess. This can be used for a test case that might not return, or that might abort.

If test_path is NULL then the same test is re-run in a subprocess. You can use g_test_subprocess() to determine whether the test is in a subprocess or not.

test_path can also be the name of the parent test, followed by "/subprocess/" and then a name for the specific subtest (or just ending with "/subprocess" if the test only has one child test); tests with names of this form will automatically be skipped in the parent process.

If usec_timeout is non-0, the test subprocess is aborted and considered failing if its run time exceeds it.

The subprocess behavior can be configured with the GTestSubprocessFlags flags.

You can use methods such as g_test_trap_assert_passed(), g_test_trap_assert_failed(), and g_test_trap_assert_stderr() to check the results of the subprocess. (But note that g_test_trap_assert_stdout() and g_test_trap_assert_stderr() cannot be used if test_flags specifies that the child should inherit the parent stdout/stderr.)

If your main() needs to behave differently in the subprocess, you can call g_test_subprocess() (after calling g_test_init()) to see whether you are in a subprocess.

The following example tests that calling my_object_new(1000000) will abort with an error message.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
static void
test_create_large_object (void)
{
  if (g_test_subprocess ())
    {
      my_object_new (1000000);
      return;
    }

  // Reruns this same test in a subprocess
  g_test_trap_subprocess (NULL, 0, 0);
  g_test_trap_assert_failed ();
  g_test_trap_assert_stderr ("*ERROR*too large*");
}

int
main (int argc, char **argv)
{
  g_test_init (&argc, &argv, NULL);

  g_test_add_func ("/myobject/create_large_object",
                   test_create_large_object);
  return g_test_run ();
}

Parameters

test_path

Test to run in a subprocess.

[nullable]

usec_timeout

Timeout for the subprocess test in micro seconds.

 

test_flags

Flags to modify subprocess behaviour.

 

Since: 2.38


g_test_trap_has_passed ()

gboolean
g_test_trap_has_passed (void);

Check the result of the last g_test_trap_subprocess() call.

Returns

TRUE if the last test subprocess terminated successfully.

Since: 2.16


g_test_trap_reached_timeout ()

gboolean
g_test_trap_reached_timeout (void);

Check the result of the last g_test_trap_subprocess() call.

Returns

TRUE if the last test subprocess got killed due to a timeout.

Since: 2.16


g_test_trap_assert_passed

#define             g_test_trap_assert_passed()

Assert that the last test subprocess passed. See g_test_trap_subprocess().

Since: 2.16


g_test_trap_assert_failed

#define             g_test_trap_assert_failed()

Assert that the last test subprocess failed. See g_test_trap_subprocess().

This is sometimes used to test situations that are formally considered to be undefined behaviour, like inputs that fail a g_return_if_fail() check. In these situations you should skip the entire test, including the call to g_test_trap_subprocess(), unless g_test_undefined() returns TRUE to indicate that undefined behaviour may be tested.

Since: 2.16


g_test_trap_assert_stdout()

#define             g_test_trap_assert_stdout(soutpattern)

Assert that the stdout output of the last test subprocess matches soutpattern . See g_test_trap_subprocess().

Parameters

soutpattern

a glob-style pattern

 

Since: 2.16


g_test_trap_assert_stdout_unmatched()

#define             g_test_trap_assert_stdout_unmatched(soutpattern)

Assert that the stdout output of the last test subprocess does not match soutpattern . See g_test_trap_subprocess().

Parameters

soutpattern

a glob-style pattern

 

Since: 2.16


g_test_trap_assert_stderr()

#define             g_test_trap_assert_stderr(serrpattern)

Assert that the stderr output of the last test subprocess matches serrpattern . See g_test_trap_subprocess().

This is sometimes used to test situations that are formally considered to be undefined behaviour, like code that hits a g_assert() or g_error(). In these situations you should skip the entire test, including the call to g_test_trap_subprocess(), unless g_test_undefined() returns TRUE to indicate that undefined behaviour may be tested.

Parameters

serrpattern

a glob-style pattern

 

Since: 2.16


g_test_trap_assert_stderr_unmatched()

#define             g_test_trap_assert_stderr_unmatched(serrpattern)

Assert that the stderr output of the last test subprocess does not match serrpattern . See g_test_trap_subprocess().

Parameters

serrpattern

a glob-style pattern

 

Since: 2.16


g_test_trap_fork ()

gboolean
g_test_trap_fork (guint64 usec_timeout,
                  GTestTrapFlags test_trap_flags);

g_test_trap_fork is deprecated and should not be used in newly-written code.

This function is implemented only on Unix platforms, and is not always reliable due to problems inherent in fork-without-exec. Use g_test_trap_subprocess() instead.

Fork the current test program to execute a test case that might not return or that might abort.

If usec_timeout is non-0, the forked test case is aborted and considered failing if its run time exceeds it.

The forking behavior can be configured with the GTestTrapFlags flags.

In the following example, the test code forks, the forked child process produces some sample output and exits successfully. The forking parent process then asserts successful child program termination and validates child program outputs.

1
2
3
4
5
6
7
8
9
10
11
12
13
static void
test_fork_patterns (void)
{
  if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
    {
      g_print ("some stdout text: somagic17\n");
      g_printerr ("some stderr text: semagic43\n");
      exit (0); // successful test run
    }
  g_test_trap_assert_passed ();
  g_test_trap_assert_stdout ("*somagic17*");
  g_test_trap_assert_stderr ("*semagic43*");
}

Parameters

usec_timeout

Timeout for the forked test in micro seconds.

 

test_trap_flags

Flags to modify forking behaviour.

 

Returns

TRUE for the forked child and FALSE for the executing parent process.

Since: 2.16


g_test_rand_bit

#define             g_test_rand_bit()

Get a reproducible random bit (0 or 1), see g_test_rand_int() for details on test case random numbers.

Since: 2.16


g_test_rand_int ()

gint32
g_test_rand_int (void);

Get a reproducible random integer number.

The random numbers generated by the g_test_rand_*() family of functions change with every new test program start, unless the --seed option is given when starting test programs.

For individual test cases however, the random number generator is reseeded, to avoid dependencies between tests and to make --seed effective for all test cases.

Returns

a random number from the seeded random number generator.

Since: 2.16


g_test_rand_int_range ()

gint32
g_test_rand_int_range (gint32 begin,
                       gint32 end);

Get a reproducible random integer number out of a specified range, see g_test_rand_int() for details on test case random numbers.

Parameters

begin

the minimum value returned by this function

 

end

the smallest value not to be returned by this function

 

Returns

a number with begin <= number < end .

Since: 2.16


g_test_rand_double ()

double
g_test_rand_double (void);

Get a reproducible random floating point number, see g_test_rand_int() for details on test case random numbers.

Returns

a random number from the seeded random number generator.

Since: 2.16


g_test_rand_double_range ()

double
g_test_rand_double_range (double range_start,
                          double range_end);

Get a reproducible random floating pointer number out of a specified range, see g_test_rand_int() for details on test case random numbers.

Parameters

range_start

the minimum value returned by this function

 

range_end

the minimum value not returned by this function

 

Returns

a number with range_start <= number < range_end .

Since: 2.16


g_assert()

#define             g_assert(expr)

Debugging macro to terminate the application if the assertion fails. If the assertion fails (i.e. the expression is not true), an error message is logged and the application is terminated.

The macro can be turned off in final releases of code by defining G_DISABLE_ASSERT when compiling the application, so code must not depend on any side effects from expr .

Parameters

expr

the expression to check

 

g_assert_not_reached

#define             g_assert_not_reached()

Debugging macro to terminate the application if it is ever reached. If it is reached, an error message is logged and the application is terminated.

The macro can be turned off in final releases of code by defining G_DISABLE_ASSERT when compiling the application.


g_assert_cmpstr()

#define             g_assert_cmpstr(s1, cmp, s2)

Debugging macro to compare two strings. If the comparison fails, an error message is logged and the application is either terminated or the testcase marked as failed. The strings are compared using g_strcmp0().

The effect of g_assert_cmpstr (s1, op, s2) is the same as g_assert_true (g_strcmp0 (s1, s2) op 0). The advantage of this macro is that it can produce a message that includes the actual values of s1 and s2 .

1
g_assert_cmpstr (mystring, ==, "fubar");

Parameters

s1

a string (may be NULL)

 

cmp

The comparison operator to use. One of ==, !=, <, >, <=, >=.

 

s2

another string (may be NULL)

 

Since: 2.16


g_assert_cmpint()

#define             g_assert_cmpint(n1, cmp, n2)

Debugging macro to compare two integers.

The effect of g_assert_cmpint (n1, op, n2) is the same as g_assert_true (n1 op n2). The advantage of this macro is that it can produce a message that includes the actual values of n1 and n2 .

Parameters

n1

an integer

 

cmp

The comparison operator to use. One of ==, !=, <, >, <=, >=.

 

n2

another integer

 

Since: 2.16


g_assert_cmpuint()

#define             g_assert_cmpuint(n1, cmp, n2)

Debugging macro to compare two unsigned integers.

The effect of g_assert_cmpuint (n1, op, n2) is the same as g_assert_true (n1 op n2). The advantage of this macro is that it can produce a message that includes the actual values of n1 and n2 .

Parameters

n1

an unsigned integer

 

cmp

The comparison operator to use. One of ==, !=, <, >, <=, >=.

 

n2

another unsigned integer

 

Since: 2.16


g_assert_cmphex()

#define             g_assert_cmphex(n1, cmp, n2)

Debugging macro to compare to unsigned integers.

This is a variant of g_assert_cmpuint() that displays the numbers in hexadecimal notation in the message.

Parameters

n1

an unsigned integer

 

cmp

The comparison operator to use. One of ==, !=, <, >, <=, >=.

 

n2

another unsigned integer

 

Since: 2.16


g_assert_cmpfloat()

#define             g_assert_cmpfloat(n1,cmp,n2)

Debugging macro to compare two floating point numbers.

The effect of g_assert_cmpfloat (n1, op, n2) is the same as g_assert_true (n1 op n2). The advantage of this macro is that it can produce a message that includes the actual values of n1 and n2 .

Parameters

n1

an floating point number

 

cmp

The comparison operator to use. One of ==, !=, <, >, <=, >=.

 

n2

another floating point number

 

Since: 2.16


g_assert_cmpmem()

#define             g_assert_cmpmem(m1, l1, m2, l2)

Debugging macro to compare memory regions. If the comparison fails, an error message is logged and the application is either terminated or the testcase marked as failed.

The effect of g_assert_cmpmem (m1, l1, m2, l2) is the same as g_assert_true (l1 == l2 &amp;&amp; memcmp (m1, m2, l1) == 0). The advantage of this macro is that it can produce a message that includes the actual values of l1 and l2 .

1
g_assert_cmpmem (buf->data, buf->len, expected, sizeof (expected));

Parameters

m1

pointer to a buffer

 

l1

length of m1

 

m2

pointer to another buffer

 

l2

length of m2

 

Since: 2.46


g_assert_no_error()

#define             g_assert_no_error(err)

Debugging macro to check that a GError is not set.

The effect of g_assert_no_error (err) is the same as g_assert_true (err == NULL). The advantage of this macro is that it can produce a message that includes the error message and code.

Parameters

err

a GError, possibly NULL

 

Since: 2.20


g_assert_error()

#define             g_assert_error(err, dom, c)

Debugging macro to check that a method has returned the correct GError.

The effect of g_assert_error (err, dom, c) is the same as g_assert_true (err != NULL &amp;&amp; err->domain == dom &amp;&amp; err->code == c). The advantage of this macro is that it can produce a message that includes the incorrect error message and code.

This can only be used to test for a specific error. If you want to test that err is set, but don't care what it's set to, just use g_assert (err != NULL)

Parameters

err

a GError, possibly NULL

 

dom

the expected error domain (a GQuark)

 

c

the expected error code

 

Since: 2.20


g_assert_true()

#define             g_assert_true(expr)

Debugging macro to check that an expression is true.

If the assertion fails (i.e. the expression is not true), an error message is logged and the application is either terminated or the testcase marked as failed.

See g_test_set_nonfatal_assertions().

Parameters

expr

the expression to check

 

Since: 2.38


g_assert_false()

#define             g_assert_false(expr)

Debugging macro to check an expression is false.

If the assertion fails (i.e. the expression is not false), an error message is logged and the application is either terminated or the testcase marked as failed.

See g_test_set_nonfatal_assertions().

Parameters

expr

the expression to check

 

Since: 2.38


g_assert_null()

#define             g_assert_null(expr)

Debugging macro to check an expression is NULL.

If the assertion fails (i.e. the expression is not NULL), an error message is logged and the application is either terminated or the testcase marked as failed.

See g_test_set_nonfatal_assertions().

Parameters

expr

the expression to check

 

Since: 2.38


g_assert_nonnull()

#define             g_assert_nonnull(expr)

Debugging macro to check an expression is not NULL.

If the assertion fails (i.e. the expression is NULL), an error message is logged and the application is either terminated or the testcase marked as failed.

See g_test_set_nonfatal_assertions().

Parameters

expr

the expression to check

 

Since: 2.40


g_test_set_nonfatal_assertions ()

void
g_test_set_nonfatal_assertions (void);

Changes the behaviour of g_assert_cmpstr(), g_assert_cmpint(), g_assert_cmpuint(), g_assert_cmphex(), g_assert_cmpfloat(), g_assert_true(), g_assert_false(), g_assert_null(), g_assert_no_error(), g_assert_error(), g_test_assert_expected_messages() and the various g_test_trap_assert_*() macros to not abort to program, but instead call g_test_fail() and continue. (This also changes the behavior of g_test_fail() so that it will not cause the test program to abort after completing the failed test.)

Note that the g_assert_not_reached() and g_assert() are not affected by this.

This function can only be called after g_test_init().

Since: 2.38


GTestFixtureFunc ()

void
(*GTestFixtureFunc) (gpointer fixture,
                     gconstpointer user_data);

The type used for functions that operate on test fixtures. This is used for the fixture setup and teardown functions as well as for the testcases themselves.

user_data is a pointer to the data that was given when registering the test case.

fixture will be a pointer to the area of memory allocated by the test framework, of the size requested. If the requested size was zero then fixture will be equal to user_data .

Parameters

fixture

the test fixture.

[not nullable]

user_data

the data provided when registering the test

 

Since: 2.28


g_test_create_case ()

GTestCase *
g_test_create_case (const char *test_name,
                    gsize data_size,
                    gconstpointer test_data,
                    GTestFixtureFunc data_setup,
                    GTestFixtureFunc data_test,
                    GTestFixtureFunc data_teardown);

Create a new GTestCase, named test_name , this API is fairly low level, calling g_test_add() or g_test_add_func() is preferable. When this test is executed, a fixture structure of size data_size will be automatically allocated and filled with zeros. Then data_setup is called to initialize the fixture. After fixture setup, the actual test function data_test is called. Once the test run completes, the fixture structure is torn down by calling data_teardown and after that the memory is automatically released by the test framework.

Splitting up a test run into fixture setup, test function and fixture teardown is most useful if the same fixture is used for multiple tests. In this cases, g_test_create_case() will be called with the same fixture, but varying test_name and data_test arguments.

Parameters

test_name

the name for the test case

 

data_size

the size of the fixture data structure

 

test_data

test data argument for the test functions

 

data_setup

the function to set up the fixture data.

[scope async]

data_test

the actual test function.

[scope async]

data_teardown

the function to teardown the fixture data.

[scope async]

Returns

a newly allocated GTestCase.

Since: 2.16


g_test_create_suite ()

GTestSuite *
g_test_create_suite (const char *suite_name);

Create a new test suite with the name suite_name .

Parameters

suite_name

a name for the suite

 

Returns

A newly allocated GTestSuite instance.

Since: 2.16


g_test_get_root ()

GTestSuite *
g_test_get_root (void);

Get the toplevel test suite for the test path API.

Returns

the toplevel GTestSuite

Since: 2.16


g_test_suite_add ()

void
g_test_suite_add (GTestSuite *suite,
                  GTestCase *test_case);

Adds test_case to suite .

Parameters

suite

a GTestSuite

 

test_case

a GTestCase

 

Since: 2.16


g_test_suite_add_suite ()

void
g_test_suite_add_suite (GTestSuite *suite,
                        GTestSuite *nestedsuite);

Adds nestedsuite to suite .

Parameters

suite

a GTestSuite

 

nestedsuite

another GTestSuite

 

Since: 2.16


g_test_run_suite ()

int
g_test_run_suite (GTestSuite *suite);

Execute the tests within suite and all nested GTestSuites. The test suites to be executed are filtered according to test path arguments (-p testpath and -s testpath) as parsed by g_test_init(). See the g_test_run() documentation for more information on the order that tests are run in.

g_test_run_suite() or g_test_run() may only be called once in a program.

Parameters

suite

a GTestSuite

 

Returns

0 on success

Since: 2.16

Types and Values

enum GTestFileType

The type of file to return the filename for, when used with g_test_build_filename().

These two options correspond rather directly to the 'dist' and 'built' terminology that automake uses and are explicitly used to distinguish between the 'srcdir' and 'builddir' being separate. All files in your project should either be dist (in the EXTRA_DIST or dist_schema_DATA sense, in which case they will always be in the srcdir) or built (in the BUILT_SOURCES sense, in which case they will always be in the builddir).

Note: as a general rule of automake, files that are generated only as part of the build-from-git process (but then are distributed with the tarball) always go in srcdir (even if doing a srcdir != builddir build from git) and are considered as distributed files.

Members

G_TEST_DIST

a file that was included in the distribution tarball

 

G_TEST_BUILT

a file that was built on the compiling machine

 

Since: 2.38


enum GTestTrapFlags

GTestTrapFlags is deprecated and should not be used in newly-written code.

GTestTrapFlags is used only with g_test_trap_fork(), which is deprecated. g_test_trap_subprocess() uses GTestSubprocessFlags.

Test traps are guards around forked tests. These flags determine what traps to set.

Members

G_TEST_TRAP_SILENCE_STDOUT

Redirect stdout of the test child to /dev/null so it cannot be observed on the console during test runs. The actual output is still captured though to allow later tests with g_test_trap_assert_stdout().

 

G_TEST_TRAP_SILENCE_STDERR

Redirect stderr of the test child to /dev/null so it cannot be observed on the console during test runs. The actual output is still captured though to allow later tests with g_test_trap_assert_stderr().

 

G_TEST_TRAP_INHERIT_STDIN

If this flag is given, stdin of the child process is shared with stdin of its parent process. It is redirected to /dev/null otherwise.

 

enum GTestSubprocessFlags

Flags to pass to g_test_trap_subprocess() to control input and output.

Note that in contrast with g_test_trap_fork(), the default is to not show stdout and stderr.

Members

G_TEST_SUBPROCESS_INHERIT_STDIN

If this flag is given, the child process will inherit the parent's stdin. Otherwise, the child's stdin is redirected to /dev/null.

 

G_TEST_SUBPROCESS_INHERIT_STDOUT

If this flag is given, the child process will inherit the parent's stdout. Otherwise, the child's stdout will not be visible, but it will be captured to allow later tests with g_test_trap_assert_stdout().

 

G_TEST_SUBPROCESS_INHERIT_STDERR

If this flag is given, the child process will inherit the parent's stderr. Otherwise, the child's stderr will not be visible, but it will be captured to allow later tests with g_test_trap_assert_stderr().

 

GTestCase

typedef struct GTestCase  GTestCase;

An opaque structure representing a test case.


GTestSuite

typedef struct GTestSuite GTestSuite;

An opaque structure representing a test suite.

See Also

gtester, gtester-report