tdb2: test: convert (non-invasive) run tests to api tests.
[ccan] / ccan / tdb2 / test / api-21-parse_record.c
1 #include <ccan/tdb2/tdb2.h>
2 #include <ccan/tap/tap.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include "logging.h"
7
8 static enum TDB_ERROR parse(TDB_DATA key, TDB_DATA data, TDB_DATA *expected)
9 {
10         if (!tdb_deq(data, *expected))
11                 return TDB_ERR_EINVAL;
12         return TDB_SUCCESS;
13 }
14
15 static enum TDB_ERROR parse_err(TDB_DATA key, TDB_DATA data, void *unused)
16 {
17         return 100;
18 }
19
20 static bool test_records(struct tdb_context *tdb)
21 {
22         int i;
23         struct tdb_data key = { (unsigned char *)&i, sizeof(i) };
24         struct tdb_data data = { (unsigned char *)&i, sizeof(i) };
25
26         for (i = 0; i < 1000; i++) {
27                 if (tdb_store(tdb, key, data, TDB_REPLACE) != 0)
28                         return false;
29         }
30
31         for (i = 0; i < 1000; i++) {
32                 if (tdb_parse_record(tdb, key, parse, &data) != TDB_SUCCESS)
33                         return false;
34         }
35
36         if (tdb_parse_record(tdb, key, parse, &data) != TDB_ERR_NOEXIST)
37                 return false;
38
39         /* Test error return from parse function. */
40         i = 0;
41         if (tdb_parse_record(tdb, key, parse_err, NULL) != 100)
42                 return false;
43
44         return true;
45 }
46
47 int main(int argc, char *argv[])
48 {
49         unsigned int i;
50         struct tdb_context *tdb;
51         int flags[] = { TDB_INTERNAL, TDB_DEFAULT, TDB_NOMMAP,
52                         TDB_INTERNAL|TDB_CONVERT, TDB_CONVERT,
53                         TDB_NOMMAP|TDB_CONVERT,
54                         TDB_INTERNAL|TDB_VERSION1, TDB_VERSION1,
55                         TDB_NOMMAP|TDB_VERSION1,
56                         TDB_INTERNAL|TDB_CONVERT|TDB_VERSION1,
57                         TDB_CONVERT|TDB_VERSION1,
58                         TDB_NOMMAP|TDB_CONVERT|TDB_VERSION1 };
59
60         plan_tests(sizeof(flags) / sizeof(flags[0]) * 2 + 1);
61         for (i = 0; i < sizeof(flags) / sizeof(flags[0]); i++) {
62                 tdb = tdb_open("run-14-exists.tdb", flags[i],
63                                O_RDWR|O_CREAT|O_TRUNC, 0600, &tap_log_attr);
64                 if (ok1(tdb))
65                         ok1(test_records(tdb));
66                 tdb_close(tdb);
67         }
68
69         ok1(tap_log_messages == 0);
70         return exit_status();
71 }