2 * SPDX-License-Identifier: ISC
4 * Copyright (c) 2019 Todd C. Miller <Todd.Miller@sudo.ws>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 #include <sys/types.h>
22 #include <sys/socket.h>
28 #endif /* HAVE_STRING_H */
31 #endif /* HAVE_STRINGS_H */
35 # include "compat/stdbool.h"
39 #include "sudo_compat.h"
40 #include "sudo_fatal.h"
41 #include "sudo_util.h"
43 __dso_public int main(int argc, char *argv[]);
46 * Test that sudo_getdelim() works as expected.
49 struct getdelim_test {
51 const char *output[4];
56 * TODO: test error case.
57 * test realloc case (buf > LINE_MAX)
59 static struct getdelim_test test_data[] = {
60 { "a\nb\nc\n", { "a\n", "b\n", "c\n", NULL }, '\n' },
61 { "a\nb\nc", { "a\n", "b\n", "c", NULL }, '\n' },
62 { "a\tb\tc\t", { "a\t", "b\t", "c\t", NULL }, '\t' },
63 { "a\tb\tc", { "a\t", "b\t", "c", NULL }, '\t' },
64 { NULL, { NULL }, '\0' }
67 static int errors = 0, ntests = 0;
70 runtests(char **buf, size_t *buflen)
76 for (i = 0; test_data[i].input != NULL; i++) {
77 if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1)
78 sudo_fatal_nodebug("socketpair");
80 switch ((pid = fork())) {
82 sudo_fatal_nodebug("fork");
86 if (send(sv[1], test_data[i].input, strlen(test_data[i].input), 0) == -1) {
87 sudo_warn_nodebug("send");
98 if ((fp = fdopen(sv[0], "r")) == NULL)
99 sudo_fatal_nodebug("fdopen");
101 for (j = 0; test_data[i].output[j] != NULL; j++) {
104 if (getdelim(buf, buflen, test_data[i].delim, fp) == -1)
105 sudo_fatal_nodebug("getdelim");
107 if (strcmp(*buf, test_data[i].output[j]) != 0) {
108 sudo_warnx_nodebug("failed test #%d: expected %s, got %s",
109 ntests, test_data[i].output[j], *buf);
116 if (getdelim(buf, buflen, test_data[i].delim, fp) != -1) {
117 sudo_warnx_nodebug("failed test #%d: expected EOF, got %s",
122 sudo_warn_nodebug("failed test #%d: expected EOF, got error",
128 waitpid(pid, NULL, 0);
134 main(int argc, char *argv[])
139 initprogname(argc > 0 ? argv[0] : "getdelim_test");
141 runtests(&buf, &buflen);
143 /* XXX - redo tests with preallocated buffer filled with junk */
145 printf("%s: %d tests run, %d errors, %d%% success rate\n",
146 getprogname(), ntests, errors, (ntests - errors) * 100 / ntests);