ocarina/tests/core/index.cpp

111 lines
2.7 KiB
C++

/*
* Copyright 2014 (c) Anna Schumaker.
* Test a Database
*/
#include <core/index.h>
#include "test.h"
static void test_entry()
{
const struct db_ops *index_ops = test_index_ops();
struct set_iter it;
index_entry *ie;
unsigned int i;
struct file f;
ie = (index_entry *)index_ops->dbe_alloc("Link");
test_equal(ie->primary_key(), "Link");
set_insert(&ie->ie_set, 0);
set_insert(&ie->ie_set, 1);
set_insert(&ie->ie_set, 2);
i = 0;
set_for_each(&ie->ie_set, &it) {
test_loop_equal(it.it_val, i, i);
i++;
} test_loop_passed();
file_init(&f, "index_entry", 0);
file_open(&f, OPEN_WRITE);
file_writef(&f, "Zelda\n0 \n");
ie->write(f);
file_close(&f);
index_ops->dbe_free(ie);
file_open(&f, OPEN_READ);
ie = (struct index_entry *)index_ops->dbe_read(&f);
test_equal(ie->primary_key(), "Zelda");
test_equal(set_size(&ie->ie_set), 0);
index_ops->dbe_free(ie);
ie = (struct index_entry *)index_ops->dbe_read(&f);
test_equal(ie->primary_key(), "Link");
test_equal(set_size(&ie->ie_set), 3);
file_close(&f);
i = 0;
set_for_each(&ie->ie_set, &it) {
test_loop_equal(it.it_val, i, i);
i++;
} test_loop_passed();
index_ops->dbe_free(ie);
}
static void test_stress(unsigned int N)
{
database<index_entry> index;
index_entry *ie, *ie2;
std::string key;
unsigned int i;
char c;
index_init(&index, "stress.idx", false);
/* index_insert() */
for (c = 'a'; c <= 'z'; c++) {
key = c;
ie = index_insert(&index, key.c_str(), 0);
test_loop_not_equal(ie, NULL, c - 'a');
test_loop_equal(ie->primary_key(), key, c - 'a');
for (i = 0; i < N; i++)
ie2 = index_insert(&index, key.c_str(), i);
test_loop_equal(ie, ie2, c - 'a');
test_loop_equal(set_size(&ie->ie_set), N, c - 'a');
test_loop_equal(index.db_size, c - 'a' + 1, c - 'a');
} test_loop_passed();
test_equal(index.db_size, 26);
/* index_has() */
for (c = 'a'; c <= 'z'; c += 4) {
key = c;
for (i = 0; i < N; i++)
test_loop_equal(index_has(&index, key.c_str(), i), true, i);
test_loop_equal(index_has(&index, key.c_str(), N), false, c - 'a');
} test_loop_passed();
/* index_remove() */
for (c = 'a'; c <= 'z'; c += 4) {
key = c;
for (i = 0; i < N; i++)
index_remove(&index, key.c_str(), i);
ie = db_find(&index, key.c_str());
test_loop_not_equal(ie, NULL, c - 'a');
test_loop_equal(set_size(&ie->ie_set), 0, c - 'a');
} test_loop_passed();
index_remove(&index, "ZZ", 42);
test_equal(index.db_size, 26);
db_deinit(&index);
}
static void test_basics() { test_stress(10); }
static void test_stress() { test_stress(100000); }
DECLARE_UNIT_TESTS(
UNIT_TEST("Index Entry", test_entry),
UNIT_TEST("Index Basics (N = 10)", test_basics),
UNIT_TEST("Index Stress (N = 100,000)", test_stress),
);