tests: add regex handling
authorBartosz Golaszewski <bartekgola@gmail.com>
Thu, 8 Jun 2017 13:11:45 +0000 (15:11 +0200)
committerBartosz Golaszewski <bartekgola@gmail.com>
Thu, 8 Jun 2017 13:11:45 +0000 (15:11 +0200)
Add a routine allowing to check if a string contains a substring
matching against given regex pattern.

Also: add a corresponding assertion.

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

index ae76dfb77b5de80703a27f2f57c74ca6a47167c4..49a8e7f8b4808e40f4e8f55c485989fb2552aa70 100644 (file)
@@ -21,6 +21,7 @@
 #include <libkmod.h>
 #include <libudev.h>
 #include <pthread.h>
+#include <regex.h>
 #include <sys/time.h>
 #include <sys/utsname.h>
 #include <sys/types.h>
@@ -980,3 +981,31 @@ void test_set_event(unsigned int chip_index, unsigned int line_offset,
 
        event_unlock();
 }
+
+bool test_regex_match(const char *str, const char *pattern)
+{
+       char errbuf[128];
+       regex_t regex;
+       bool ret;
+       int rv;
+
+       rv = regcomp(&regex, pattern, REG_EXTENDED | REG_NEWLINE);
+       if (rv) {
+               regerror(rv, &regex, errbuf, sizeof(errbuf));
+               die("unable to compile regex '%s': %s", pattern, errbuf);
+       }
+
+       rv = regexec(&regex, str, 0, 0, 0);
+       if (rv == REG_NOERROR) {
+               ret = true;
+       } else if (rv == REG_NOMATCH) {
+               ret = false;
+       } else {
+               regerror(rv, &regex, errbuf, sizeof(errbuf));
+               die("unable to run a regex match: %s", errbuf);
+       }
+
+       regfree(&regex);
+
+       return ret;
+}
index 63ad26c5143e2be0f06b6565e8200d4fb18f5340..5c88ad0db342b6d3cfa0d7cc19a308441062636f 100644 (file)
@@ -127,6 +127,8 @@ void test_free_str(char **str);
 void test_free_chip_iter(struct gpiod_chip_iter **iter);
 void test_free_chip_iter_noclose(struct gpiod_chip_iter **iter);
 
+bool test_regex_match(const char *str, const char *pattern);
+
 #define TEST_ASSERT(statement)                                         \
        do {                                                            \
                if (!(statement)) {                                     \
@@ -145,5 +147,6 @@ void test_free_chip_iter_noclose(struct gpiod_chip_iter **iter);
 #define TEST_ASSERT_NOTEQ(a1, a2)      TEST_ASSERT(a1 != a2)
 #define TEST_ASSERT_STR_EQ(s1, s2)     TEST_ASSERT(strcmp(s1, s2) == 0)
 #define TEST_ASSERT_STR_CONTAINS(s, p) TEST_ASSERT(strstr(s, p) != NULL)
+#define TEST_ASSERT_REGEX_MATCH(s, p)  TEST_ASSERT(test_regex_match(s, p))
 
 #endif /* __GPIOD_TEST_H__ */