tests: now we run in tmp dir, always create temporary files in this dir.
[ccan] / ccan / tdb / test / run-bad-tdb-header.c
1 #define _XOPEN_SOURCE 500
2 #include <ccan/tdb/tdb.h>
3 #include <ccan/tdb/io.c>
4 #include <ccan/tdb/tdb.c>
5 #include <ccan/tdb/lock.c>
6 #include <ccan/tdb/freelist.c>
7 #include <ccan/tdb/traverse.c>
8 #include <ccan/tdb/transaction.c>
9 #include <ccan/tdb/error.c>
10 #include <ccan/tdb/open.c>
11 #include <ccan/tdb/check.c>
12 #include <ccan/tap/tap.h>
13 #include <stdlib.h>
14 #include <err.h>
15
16 int main(int argc, char *argv[])
17 {
18         struct tdb_context *tdb;
19         struct tdb_header hdr;
20         int fd;
21
22         plan_tests(11);
23         /* Can open fine if complete crap, as long as O_CREAT. */
24         fd = open("run-bad-tdb-header.tdb", O_RDWR|O_CREAT|O_TRUNC, 0600);
25         ok1(fd >= 0);
26         ok1(write(fd, "hello world", 11) == 11);
27         close(fd);
28         tdb = tdb_open("run-bad-tdb-header.tdb", 1024, 0, O_RDWR, 0);
29         ok1(!tdb);
30         tdb = tdb_open("run-bad-tdb-header.tdb", 1024, 0, O_CREAT|O_RDWR, 0600);
31         ok1(tdb);
32         tdb_close(tdb);
33
34         /* Now, with wrong version it should *not* overwrite. */
35         fd = open("run-bad-tdb-header.tdb", O_RDWR);
36         ok1(fd >= 0);
37         ok1(read(fd, &hdr, sizeof(hdr)) == sizeof(hdr));
38         ok1(hdr.version == TDB_VERSION);
39         hdr.version++;
40         lseek(fd, 0, SEEK_SET);
41         ok1(write(fd, &hdr, sizeof(hdr)) == sizeof(hdr));
42         close(fd);
43
44         tdb = tdb_open("run-bad-tdb-header.tdb", 1024, 0, O_RDWR|O_CREAT, 0600);
45         ok1(errno == EIO);
46         ok1(!tdb);
47
48         /* With truncate, will be fine. */
49         tdb = tdb_open("run-bad-tdb-header.tdb", 1024, 0, O_RDWR|O_CREAT|O_TRUNC, 0600);
50         ok1(tdb);
51         tdb_close(tdb);
52
53         return exit_status();
54 }