]> git.ozlabs.org Git - ccan/blob - ccan/rbuf/test/run.c
pipecmd: close fds in child.
[ccan] / ccan / rbuf / test / run.c
1 #include <ccan/rbuf/rbuf.h>
2 /* Include the C files directly. */
3 #include <ccan/rbuf/rbuf.c>
4 #include <ccan/tap/tap.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 #include <stdlib.h>
9
10 static bool test_realloc_fail;
11 static void *test_realloc(struct membuf *mb, void *buf, size_t n)
12 {
13         if (test_realloc_fail)
14                 return NULL;
15         return realloc(buf, n);
16 }
17
18 int main(void)
19 {
20         struct rbuf in;
21         char buf[4096];
22         char *lines[100], *p;
23         int i, fd = open("test/run.c", O_RDONLY), len;
24
25         /* This is how many tests you plan to run */
26         plan_tests(164);
27
28         /* Grab ourselves for comparison. */
29         len = read(fd, buf, sizeof(buf));
30         buf[len] = '\0';
31         lseek(fd, SEEK_SET, 0);
32
33         for (i = 0, p = buf; *p; i++) {
34                 lines[i] = p;
35                 p = strchr(p, '\n');
36                 *p = '\0';
37                 p++;
38         }
39         lines[i] = NULL;
40
41         rbuf_init(&in, fd, malloc(31), 31, test_realloc);
42         ok1(in.fd == fd);
43         ok1(membuf_num_space(&in.m) == 31);
44         test_realloc_fail = true;
45         p = rbuf_read_str(&in, '\n');
46         ok1(p);
47         ok1(strcmp(p, lines[0]) == 0);
48
49         test_realloc_fail = false;
50         p = rbuf_read_str(&in, '\n');
51         ok1(p);
52         ok1(strcmp(p, lines[1]) == 0);
53
54         for (i = 2; lines[i]; i++) {
55                 ok1(p = rbuf_read_str(&in, '\n'));
56                 ok1(strcmp(p, lines[i]) == 0);
57         }
58
59         p = rbuf_read_str(&in, '\n');
60         ok1(errno == 0);
61         ok1(p == NULL);
62         free(rbuf_cleanup(&in));
63
64         /* Another way of reading the entire (text) file. */
65         lseek(fd, SEEK_SET, 0);
66         rbuf_init(&in, fd, NULL, 0, test_realloc);
67         p = rbuf_read_str(&in, 0);
68         ok1(p);
69         ok1(strlen(p) == len);
70
71         close(fd);
72         p = rbuf_read_str(&in, 0);
73         ok1(errno == EBADF);
74         ok1(!p);
75         free(rbuf_cleanup(&in));
76
77         return exit_status();
78 }