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