tests: provide test_build_str()
authorBartosz Golaszewski <bartekgola@gmail.com>
Sun, 5 Nov 2017 13:21:54 +0000 (14:21 +0100)
committerBartosz Golaszewski <bartekgola@gmail.com>
Sun, 5 Nov 2017 13:31:21 +0000 (14:31 +0100)
Many test cases use asprintf() to build custom strings. This routine
can fail and the return value is tested using the TEST_ASSERT macros
but this is not the subject of the actual testing. The test case must
also free the string allocated by this function.

As a simplification: pull this functionality into the testing
framework so that we can build custom strings without keeping track of
resources. The new function will also make the whole test suite die if
the internal asprintf() call fails.

Signed-off-by: Bartosz Golaszewski <bartekgola@gmail.com>
tests/gpiod-test.c
tests/gpiod-test.h

index dcf37280a175ea3ee9de66e742d10513bc3e86bd..d64a24db558a72cb98da95142ed051c755d340e1 100644 (file)
@@ -74,6 +74,7 @@ struct test_context {
        size_t num_chips;
        bool test_failed;
        char *failed_msg;
+       char *custom_str;
        struct event_thread event;
        struct gpiotool_proc tool_proc;
        bool running;
@@ -976,6 +977,9 @@ static void teardown_test(void)
 
        free(globals.test_ctx.chips);
 
+       if (globals.test_ctx.custom_str)
+               free(globals.test_ctx.custom_str);
+
        if (mockup_loaded()) {
                status = kmod_module_remove_module(globals.module, 0);
                if (status)
@@ -1152,3 +1156,23 @@ bool test_regex_match(const char *str, const char *pattern)
 
        return ret;
 }
+
+const char *test_build_str(const char *fmt, ...)
+{
+       va_list va;
+       char *str;
+       int rv;
+
+       if (globals.test_ctx.custom_str)
+               free(globals.test_ctx.custom_str);
+
+       va_start(va, fmt);
+       rv = vasprintf(&str, fmt, va);
+       va_end(va);
+       if (rv < 0)
+               die_perr("error creating custom string");
+
+       globals.test_ctx.custom_str = str;
+
+       return str;
+}
index f753171e356fc763c97b3dad8ef6caf6e3d06a58..0f451882851aaec37e95b7b57cd4b4be8be8dc87 100644 (file)
@@ -133,6 +133,12 @@ void test_free_chip_iter_noclose(struct gpiod_chip_iter **iter);
 
 bool test_regex_match(const char *str, const char *pattern);
 
+/*
+ * Return a custom string built according to printf() formatting rules. The
+ * returned string is valid until the next call to this routine.
+ */
+const char *test_build_str(const char *fmt, ...) TEST_PRINTF(1, 2);
+
 #define TEST_ASSERT(statement)                                         \
        do {                                                            \
                if (!(statement)) {                                     \