1 /* $OpenBSD: test_expand.c,v 1.2 2021/04/06 09:07:33 dtucker Exp $ */ 2 /* 3 * Regress test for misc string expansion functions. 4 * 5 * Placed in the public domain. 6 */ 7 8 #include <sys/types.h> 9 #include <sys/param.h> 10 #include <stdio.h> 11 #include <stdint.h> 12 #include <stdlib.h> 13 #include <string.h> 14 15 #include "test_helper.h" 16 17 #include "log.h" 18 #include "misc.h" 19 20 void test_expand(void); 21 22 void 23 test_expand(void) 24 { 25 int parseerr; 26 char *ret; 27 28 TEST_START("dollar_expand"); 29 ASSERT_INT_EQ(setenv("FOO", "bar", 1), 0); 30 ASSERT_INT_EQ(setenv("BAR", "baz", 1), 0); 31 (void)unsetenv("BAZ"); 32 #define ASSERT_DOLLAR_EQ(x, y) do { \ 33 char *str = dollar_expand(NULL, (x)); \ 34 ASSERT_STRING_EQ(str, (y)); \ 35 free(str); \ 36 } while(0) 37 ASSERT_DOLLAR_EQ("${FOO}", "bar"); 38 ASSERT_DOLLAR_EQ(" ${FOO}", " bar"); 39 ASSERT_DOLLAR_EQ("${FOO} ", "bar "); 40 ASSERT_DOLLAR_EQ(" ${FOO} ", " bar "); 41 ASSERT_DOLLAR_EQ("${FOO}${BAR}", "barbaz"); 42 ASSERT_DOLLAR_EQ(" ${FOO} ${BAR}", " bar baz"); 43 ASSERT_DOLLAR_EQ("${FOO}${BAR} ", "barbaz "); 44 ASSERT_DOLLAR_EQ(" ${FOO} ${BAR} ", " bar baz "); 45 ASSERT_DOLLAR_EQ("$", "$"); 46 ASSERT_DOLLAR_EQ(" $", " $"); 47 ASSERT_DOLLAR_EQ("$ ", "$ "); 48 49 /* suppress error messages for error handing tests */ 50 log_init("test_misc", SYSLOG_LEVEL_QUIET, SYSLOG_FACILITY_AUTH, 1); 51 /* error checking, non existent variable */ 52 ret = dollar_expand(&parseerr, "a${BAZ}"); 53 ASSERT_PTR_EQ(ret, NULL); ASSERT_INT_EQ(parseerr, 0); 54 ret = dollar_expand(&parseerr, "${BAZ}b"); 55 ASSERT_PTR_EQ(ret, NULL); ASSERT_INT_EQ(parseerr, 0); 56 ret = dollar_expand(&parseerr, "a${BAZ}b"); 57 ASSERT_PTR_EQ(ret, NULL); ASSERT_INT_EQ(parseerr, 0); 58 /* invalid format */ 59 ret = dollar_expand(&parseerr, "${"); 60 ASSERT_PTR_EQ(ret, NULL); ASSERT_INT_EQ(parseerr, 1); 61 ret = dollar_expand(&parseerr, "${F"); 62 ASSERT_PTR_EQ(ret, NULL); ASSERT_INT_EQ(parseerr, 1); 63 ret = dollar_expand(&parseerr, "${FO"); 64 ASSERT_PTR_EQ(ret, NULL); ASSERT_INT_EQ(parseerr, 1); 65 /* empty variable name */ 66 ret = dollar_expand(&parseerr, "${}"); 67 ASSERT_PTR_EQ(ret, NULL); ASSERT_INT_EQ(parseerr, 1); 68 /* restore loglevel to default */ 69 log_init("test_misc", SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 1); 70 TEST_DONE(); 71 72 TEST_START("percent_expand"); 73 ASSERT_STRING_EQ(percent_expand("%%", "%h", "foo", NULL), "%"); 74 ASSERT_STRING_EQ(percent_expand("%h", "h", "foo", NULL), "foo"); 75 ASSERT_STRING_EQ(percent_expand("%h ", "h", "foo", NULL), "foo "); 76 ASSERT_STRING_EQ(percent_expand(" %h", "h", "foo", NULL), " foo"); 77 ASSERT_STRING_EQ(percent_expand(" %h ", "h", "foo", NULL), " foo "); 78 ASSERT_STRING_EQ(percent_expand(" %a%b ", "a", "foo", "b", "bar", NULL), 79 " foobar "); 80 TEST_DONE(); 81 82 TEST_START("percent_dollar_expand"); 83 ASSERT_STRING_EQ(percent_dollar_expand("%h${FOO}", "h", "foo", NULL), 84 "foobar"); 85 TEST_DONE(); 86 } 87