/* Direct unit tests for the graded interface (buf, list, store). */ #include #include #include #include "buf.h" #include "list.h" #include "store.h" #define CHECK(cond) \ do { \ if (!(cond)) { \ fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ return 1; \ } \ } while (0) static int test_buf(void) { buf_t *b = buf_new(); CHECK(b != NULL); CHECK(strcmp(buf_cstr(b), "") == 0); CHECK(buf_append(b, "hello", 5) == 0); CHECK(buf_append(b, " world", 6) == 0); CHECK(buf_len(b) == 11); CHECK(strcmp(buf_cstr(b), "hello world") == 0); buf_reset(b); CHECK(buf_len(b) == 0); CHECK(strcmp(buf_cstr(b), "") == 0); buf_free(b); return 0; } static int test_list(void) { list_t *l = list_new(); record_t *r; CHECK(l != NULL); CHECK(list_len(l) == 0); CHECK(list_append(l, record_new("zed", "z@x", "1")) == 0); CHECK(list_append(l, record_new("amy", "a@x", "2")) == 0); CHECK(list_append(l, record_new("bob", "b@x", "3")) == 0); CHECK(list_len(l) == 3); r = list_find(l, "amy"); CHECK(r != NULL && strcmp(r->field1, "a@x") == 0); CHECK(list_find(l, "nope") == NULL); CHECK(list_remove(l, "amy") == STATUS_OK); CHECK(list_len(l) == 2); CHECK(list_find(l, "amy") == NULL); CHECK(list_remove(l, "amy") == STATUS_ERR_NOTFOUND); CHECK(list_remove(l, NULL) == STATUS_ERR_ARG); list_sort(l); CHECK(strcmp(list_get(l, 0)->name, "bob") == 0); /* after sort: bob, zed */ CHECK(strcmp(list_get(l, 1)->name, "zed") == 0); list_free(l); return 0; } static int test_store(void) { list_t *l = list_new(); list_t *l2 = list_new(); int n; CHECK(l != NULL && l2 != NULL); CHECK(list_append(l, record_new("Ada Lovelace", "ada@x", "555-0100")) == 0); CHECK(list_append(l, record_new("grace", "", "third field with spaces")) == 0); CHECK(store_save(l, "/tmp/recman_unit_store.txt") == STATUS_OK); n = store_load(&l2, "/tmp/recman_unit_store.txt"); CHECK(n == 2); CHECK(list_len(l2) == 2); CHECK(strcmp(list_get(l2, 0)->name, "Ada Lovelace") == 0); CHECK(strcmp(list_get(l2, 0)->field2, "555-0100") == 0); CHECK(strcmp(list_get(l2, 1)->field1, "") == 0); CHECK(strcmp(list_get(l2, 1)->field2, "third field with spaces") == 0); /* load appends into a non-empty list */ n = store_load(&l2, "/tmp/recman_unit_store.txt"); CHECK(n == 2 && list_len(l2) == 4); /* missing file -> error, not crash */ CHECK(store_load(&l2, "/tmp/recman_unit_missing_xyz.txt") < 0); list_free(l); list_free(l2); remove("/tmp/recman_unit_store.txt"); return 0; } int main(void) { if (test_buf() != 0) return 1; if (test_list() != 0) return 1; if (test_store() != 0) return 1; puts("unit: all pass"); return 0; }