I'm using glib's Testing framework for unit testing. My library also uses gobject, in my test unities I want to check if after the last _unref of each object the object was correctly freed. When g_test_trap_fork was available I used it after each _unref, calling _unref for a second time and then checking for g_test_trap_assert_failed ().
However, now that g_test_trap_fork is becoming deprecated I'm moving towards g_test_trap_subprocess. The problem is that now I would have to write a separated test case for each _unref to be checked and since each case could contain several objects that would imply on the repetition of every test case adding a second _unref for each one already present.
For example, I tried to fix like this:
NcmVector *v = test->v;
GVariant *var = ncm_vector_get_variant (v);
g_assert (!g_variant_is_floating (var));
g_assert (g_variant_is_container (var));
g_assert_cmpuint (ncm_vector_len (v), ==, g_variant_n_children (var));
{
NcmVector *nv = ncm_vector_new_variant (var);
gint i;
g_assert_cmpuint (ncm_vector_len (v), ==, ncm_vector_len (nv));
for (i = 0; i < ncm_vector_len (v); i++)
{
ncm_assert_cmpdouble (ncm_vector_get (v, i), ==, ncm_vector_get (nv, i));
}
ncm_vector_free (nv);
NCM_TEST_FAIL (ncm_vector_free (nv));
}
g_variant_unref (var);
NCM_TEST_FAIL (g_variant_unref (var); fprintf (stderr, "fail (%s)", g_variant_get_type_string (var)));
Where the macro NCM_TEST_FAIL is given by:
#define NCM_TEST_FAIL(cmd) \
G_STMT_START { \
if (g_test_subprocess ()) \
{ \
cmd; \
exit (0); \
} \
else \
{ \
g_test_trap_subprocess (NULL, 0, 0); \
g_test_trap_assert_failed (); \
} \
} G_STMT_END
The problem with this solution is that it can be only used once in each test case. If used for a second time, as in the example above, it would only test the first appearance of g_test_subprocess ().
I thought about checking inside of the gobject structure for the reference count just before the last _unref to check if it is == 1. But that would involve accessing a private part of that structure which I would avoid if possible.
Any ideas of how to check for erroneous code several times inside the same test case?