tdb2: test: import tdb1's tests.
[ccan] / ccan / tdb2 / test / run-tdb1-bad-tdb-header.c
1 #include "tdb2-source.h"
2 #include <ccan/tap/tap.h>
3 #include <stdlib.h>
4 #include <err.h>
5 #include "tdb1-logging.h"
6
7 int main(int argc, char *argv[])
8 {
9         struct tdb1_context *tdb;
10         struct tdb1_header hdr;
11         int fd;
12
13         plan_tests(11);
14         /* Can open fine if complete crap, as long as O_CREAT. */
15         fd = open("run-bad-tdb-header.tdb", O_RDWR|O_CREAT|O_TRUNC, 0600);
16         ok1(fd >= 0);
17         ok1(write(fd, "hello world", 11) == 11);
18         close(fd);
19         tdb = tdb1_open_ex("run-bad-tdb-header.tdb", 1024, 0, O_RDWR, 0,
20                           &taplogctx, NULL);
21         ok1(!tdb);
22         tdb = tdb1_open_ex("run-bad-tdb-header.tdb", 1024, 0, O_CREAT|O_RDWR,
23                           0600, &taplogctx, NULL);
24         ok1(tdb);
25         tdb1_close(tdb);
26
27         /* Now, with wrong version it should *not* overwrite. */
28         fd = open("run-bad-tdb-header.tdb", O_RDWR);
29         ok1(fd >= 0);
30         ok1(read(fd, &hdr, sizeof(hdr)) == sizeof(hdr));
31         ok1(hdr.version == TDB1_VERSION);
32         hdr.version++;
33         lseek(fd, 0, SEEK_SET);
34         ok1(write(fd, &hdr, sizeof(hdr)) == sizeof(hdr));
35         close(fd);
36
37         tdb = tdb1_open_ex("run-bad-tdb-header.tdb", 1024, 0, O_RDWR|O_CREAT,
38                           0600, &taplogctx, NULL);
39         ok1(errno == EIO);
40         ok1(!tdb);
41
42         /* With truncate, will be fine. */
43         tdb = tdb1_open_ex("run-bad-tdb-header.tdb", 1024, 0,
44                           O_RDWR|O_CREAT|O_TRUNC, 0600, &taplogctx, NULL);
45         ok1(tdb);
46         tdb1_close(tdb);
47
48         return exit_status();
49 }