From c8220a2cd2178a4975f8dc6c09ab59098cf86a12 Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Thu, 8 Jun 2017 15:11:45 +0200 Subject: [PATCH] tests: add regex handling 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 --- tests/gpiod-test.c | 29 +++++++++++++++++++++++++++++ tests/gpiod-test.h | 3 +++ 2 files changed, 32 insertions(+) diff --git a/tests/gpiod-test.c b/tests/gpiod-test.c index ae76dfb..49a8e7f 100644 --- a/tests/gpiod-test.c +++ b/tests/gpiod-test.c @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -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(®ex, pattern, REG_EXTENDED | REG_NEWLINE); + if (rv) { + regerror(rv, ®ex, errbuf, sizeof(errbuf)); + die("unable to compile regex '%s': %s", pattern, errbuf); + } + + rv = regexec(®ex, str, 0, 0, 0); + if (rv == REG_NOERROR) { + ret = true; + } else if (rv == REG_NOMATCH) { + ret = false; + } else { + regerror(rv, ®ex, errbuf, sizeof(errbuf)); + die("unable to run a regex match: %s", errbuf); + } + + regfree(®ex); + + return ret; +} diff --git a/tests/gpiod-test.h b/tests/gpiod-test.h index 63ad26c..5c88ad0 100644 --- a/tests/gpiod-test.h +++ b/tests/gpiod-test.h @@ -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__ */ -- 2.30.2