PageRenderTime 20ms CodeModel.GetById 8ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/src/example/key_value_test.c

http://cmockery.googlecode.com/
C | 80 lines | 55 code | 8 blank | 17 comment | 2 complexity | 37833d62f5961af2b7ed7f6f6a6c0adc MD5 | raw file
 1/*
 2 * Copyright 2008 Google Inc.
 3 *
 4 * Licensed under the Apache License, Version 2.0 (the "License");
 5 * you may not use this file except in compliance with the License.
 6 * You may obtain a copy of the License at
 7 *
 8 * http://www.apache.org/licenses/LICENSE-2.0
 9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#include <stdarg.h>
17#include <stddef.h>
18#include <setjmp.h>
19#include <string.h>
20#include <cmockery.h>
21
22/* This is duplicated here from the module setup_teardown.c to reduce the
23 * number of files used in this test. */
24typedef struct KeyValue {
25    unsigned int key;
26    const char* value;
27} KeyValue;
28
29void set_key_values(KeyValue * const new_key_values,
30                    const unsigned int new_number_of_key_values);
31extern KeyValue* find_item_by_value(const char * const value);
32extern void sort_items_by_key();
33
34static KeyValue key_values[] = {
35    { 10, "this" },
36    { 52, "test" },
37    { 20, "a" },
38    { 13, "is" },
39};
40
41void create_key_values(void **state) {
42    KeyValue * const items = (KeyValue*)test_malloc(sizeof(key_values));
43    memcpy(items, key_values, sizeof(key_values));
44    *state = (void*)items;
45    set_key_values(items, sizeof(key_values) / sizeof(key_values[0]));
46}
47
48void destroy_key_values(void **state) {
49    test_free(*state);
50    set_key_values(NULL, 0);
51}
52
53void test_find_item_by_value(void **state) {
54    unsigned int i;
55    for (i = 0; i < sizeof(key_values) / sizeof(key_values[0]); i++) {
56        KeyValue * const found  = find_item_by_value(key_values[i].value);
57        assert_true(found);
58        assert_int_equal(found->key, key_values[i].key);
59        assert_string_equal(found->value, key_values[i].value);
60    }
61}
62
63void test_sort_items_by_key(void **state) {
64    unsigned int i;
65    KeyValue * const kv = *state;
66    sort_items_by_key();
67    for (i = 1; i < sizeof(key_values) / sizeof(key_values[0]); i++) {
68        assert_true(kv[i - 1].key < kv[i].key);
69    }
70}
71
72int main(int argc, char* argv[]) {
73    const UnitTest tests[] = {
74        unit_test_setup_teardown(test_find_item_by_value, create_key_values,
75                                 destroy_key_values),
76        unit_test_setup_teardown(test_sort_items_by_key, create_key_values,
77                                 destroy_key_values),
78    };
79    return run_tests(tests);
80}