]> git.ozlabs.org Git - ccan/blob - ccan/failtest/test/run-open.c
failtest: handle 2-argument open()
[ccan] / ccan / failtest / test / run-open.c
1 #include <stdlib.h>
2 #include <setjmp.h>
3 #include <stdio.h>
4 #include <stdarg.h>
5 #include <assert.h>
6 #include <ccan/tap/tap.h>
7 /* Include the C files directly. */
8 #include <ccan/failtest/failtest.c>
9
10 int main(void)
11 {
12         int fd, pfd[2], err;
13         char buf[] = "Hello world!";
14         struct stat st;
15
16         plan_tests(12);
17
18         pipe(pfd);
19         fd = failtest_open("run-open-scratchpad", "run-open.c", 1,
20                            O_RDWR|O_CREAT, 0600);
21         if (fd == -1) {
22                 /* We are the child: write error code for parent to check. */
23                 err = errno;
24                 write(pfd[1], &err, sizeof(err));
25                 failtest_exit(0);
26         }
27         /* Check it is read-write. */
28         ok1(write(fd, buf, strlen(buf)) == strlen(buf));
29         lseek(fd, SEEK_SET, 0);
30         ok1(read(fd, buf, strlen("Hello world!")) == strlen("Hello world!"));
31         ok1(strcmp(buf, "Hello world!") == 0);
32
33         /* Check name and perms. */
34         ok1(stat("run-open-scratchpad", &st) == 0);
35         ok1(st.st_size == strlen(buf));
36         ok1(S_ISREG(st.st_mode));
37         ok1((st.st_mode & 0777) == 0600);
38
39         /* Check child got correct errno. */
40         ok1(read(pfd[0], &err, sizeof(err)) == sizeof(err));
41         ok1(err == EACCES);
42
43         /* Clean up. */
44         close(fd);
45         close(pfd[0]);
46         close(pfd[1]);
47
48         /* Two-arg open. */
49         pipe(pfd);
50         fd = failtest_open("run-open-scratchpad", "run-open.c", 1, O_RDONLY);
51         if (fd == -1) {
52                 /* We are the child: write error code for parent to check. */
53                 err = errno;
54                 write(pfd[1], &err, sizeof(err));
55                 failtest_exit(0);
56         }
57         /* Check it is read-only. */
58         ok1(write(fd, buf, strlen(buf)) == -1);
59         ok1(read(fd, buf, strlen("Hello world!")) == strlen("Hello world!"));
60         ok1(strcmp(buf, "Hello world!") == 0);
61         /* Clean up. */
62         close(fd);
63         close(pfd[0]);
64         close(pfd[1]);
65
66         return exit_status();
67 }