]> git.ozlabs.org Git - ccan/blob - ccan/rbuf/test/run-all.c
d7c1a3f1e32964379756c91ca5b8962dac7eaaa3
[ccan] / ccan / rbuf / test / run-all.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         int i, size, fd = open("run-all-file", O_WRONLY|O_CREAT, 0600);
23
24         /* This is how many tests you plan to run */
25         plan_tests(8);
26
27         /* Make sure we're bigger than a single buffer! */
28         size = rbuf_good_size(fd)*2;
29         for (i = 0; i * sizeof(buf) < size; i++) {
30                 memset(buf, 0x42 + i, sizeof(buf));
31                 write(fd, buf, sizeof(buf));
32         }
33         close(fd);
34
35         ok1(rbuf_open(&in, "run-all-file", NULL, 0, test_realloc));
36         /* Can't fill if realloc fails. */
37         test_realloc_fail = true;
38         ok1(!rbuf_fill(&in));
39         ok1(errno == ENOMEM);
40         test_realloc_fail = false;
41         ok1(rbuf_fill(&in));
42         /* But can't load in whole file. */
43         test_realloc_fail = true;
44         ok1(!rbuf_fill_all(&in));
45         ok1(errno == ENOMEM);
46         test_realloc_fail = false;
47         ok1(rbuf_fill_all(&in));
48         ok1(rbuf_len(&in) == size);
49         for (i = 0; i * sizeof(buf) < size; i++) {
50                 memset(buf, 0x42 + i, sizeof(buf));
51                 if (memcmp(buf, rbuf_start(&in), sizeof(buf)) != 0) {
52                         fail("Bad buffer contents");
53                         break;
54                 }
55                 rbuf_consume(&in, sizeof(buf));
56         }
57         free(membuf_cleanup(&in.m));
58
59         /* This exits depending on whether all tests passed */
60         return exit_status();
61 }