Merge branch 'hn/ref-api-tests-update'
[alt-git.git] / reftable / block_test.c
blob4b3ea262dcbf2d2513a894ba9ec388c0d050bdd0
1 /*
2 Copyright 2020 Google LLC
4 Use of this source code is governed by a BSD-style
5 license that can be found in the LICENSE file or at
6 https://developers.google.com/open-source/licenses/bsd
7 */
9 #include "block.h"
11 #include "system.h"
12 #include "blocksource.h"
13 #include "basics.h"
14 #include "constants.h"
15 #include "record.h"
16 #include "test_framework.h"
17 #include "reftable-tests.h"
19 static void test_block_read_write(void)
21 const int header_off = 21; /* random */
22 char *names[30];
23 const int N = ARRAY_SIZE(names);
24 const int block_size = 1024;
25 struct reftable_block block = { NULL };
26 struct block_writer bw = {
27 .last_key = STRBUF_INIT,
29 struct reftable_ref_record ref = { NULL };
30 struct reftable_record rec = { NULL };
31 int i = 0;
32 int n;
33 struct block_reader br = { 0 };
34 struct block_iter it = { .last_key = STRBUF_INIT };
35 int j = 0;
36 struct strbuf want = STRBUF_INIT;
38 block.data = reftable_calloc(block_size);
39 block.len = block_size;
40 block.source = malloc_block_source();
41 block_writer_init(&bw, BLOCK_TYPE_REF, block.data, block_size,
42 header_off, hash_size(GIT_SHA1_FORMAT_ID));
43 reftable_record_from_ref(&rec, &ref);
45 for (i = 0; i < N; i++) {
46 char name[100];
47 uint8_t hash[GIT_SHA1_RAWSZ];
48 snprintf(name, sizeof(name), "branch%02d", i);
49 memset(hash, i, sizeof(hash));
51 ref.refname = name;
52 ref.value_type = REFTABLE_REF_VAL1;
53 ref.value.val1 = hash;
55 names[i] = xstrdup(name);
56 n = block_writer_add(&bw, &rec);
57 ref.refname = NULL;
58 ref.value_type = REFTABLE_REF_DELETION;
59 EXPECT(n == 0);
62 n = block_writer_finish(&bw);
63 EXPECT(n > 0);
65 block_writer_release(&bw);
67 block_reader_init(&br, &block, header_off, block_size, GIT_SHA1_RAWSZ);
69 block_reader_start(&br, &it);
71 while (1) {
72 int r = block_iter_next(&it, &rec);
73 EXPECT(r >= 0);
74 if (r > 0) {
75 break;
77 EXPECT_STREQ(names[j], ref.refname);
78 j++;
81 reftable_record_release(&rec);
82 block_iter_close(&it);
84 for (i = 0; i < N; i++) {
85 struct block_iter it = { .last_key = STRBUF_INIT };
86 strbuf_reset(&want);
87 strbuf_addstr(&want, names[i]);
89 n = block_reader_seek(&br, &it, &want);
90 EXPECT(n == 0);
92 n = block_iter_next(&it, &rec);
93 EXPECT(n == 0);
95 EXPECT_STREQ(names[i], ref.refname);
97 want.len--;
98 n = block_reader_seek(&br, &it, &want);
99 EXPECT(n == 0);
101 n = block_iter_next(&it, &rec);
102 EXPECT(n == 0);
103 EXPECT_STREQ(names[10 * (i / 10)], ref.refname);
105 block_iter_close(&it);
108 reftable_record_release(&rec);
109 reftable_block_done(&br.block);
110 strbuf_release(&want);
111 for (i = 0; i < N; i++) {
112 reftable_free(names[i]);
116 int block_test_main(int argc, const char *argv[])
118 RUN_TEST(test_block_read_write);
119 return 0;