/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. /* This is duplicated here from the module setup_teardown.c to reduce the
  22. * number of files used in this test. */
  23. typedef struct KeyValue {
  24. unsigned int key;
  25. const char* value;
  26. } KeyValue;
  27. void set_key_values(KeyValue * const new_key_values,
  28. const unsigned int new_number_of_key_values);
  29. extern KeyValue* find_item_by_value(const char * const value);
  30. extern void sort_items_by_key();
  31. static KeyValue key_values[] = {
  32. { 10, "this" },
  33. { 52, "test" },
  34. { 20, "a" },
  35. { 13, "is" },
  36. };
  37. void create_key_values(void **state) {
  38. KeyValue * const items = (KeyValue*)test_malloc(sizeof(key_values));
  39. memcpy(items, key_values, sizeof(key_values));
  40. *state = (void*)items;
  41. set_key_values(items, sizeof(key_values) / sizeof(key_values[0]));
  42. }
  43. void destroy_key_values(void **state) {
  44. test_free(*state);
  45. set_key_values(NULL, 0);
  46. }
  47. void test_find_item_by_value(void **state) {
  48. unsigned int i;
  49. for (i = 0; i < sizeof(key_values) / sizeof(key_values[0]); i++) {
  50. KeyValue * const found = find_item_by_value(key_values[i].value);
  51. assert_true(found);
  52. assert_int_equal(found->key, key_values[i].key);
  53. assert_string_equal(found->value, key_values[i].value);
  54. }
  55. }
  56. void test_sort_items_by_key(void **state) {
  57. unsigned int i;
  58. KeyValue * const kv = *state;
  59. sort_items_by_key();
  60. for (i = 1; i < sizeof(key_values) / sizeof(key_values[0]); i++) {
  61. assert_true(kv[i - 1].key < kv[i].key);
  62. }
  63. }
  64. int main(int argc, char* argv[]) {
  65. const UnitTest tests[] = {
  66. unit_test_setup_teardown(test_find_item_by_value, create_key_values,
  67. destroy_key_values),
  68. unit_test_setup_teardown(test_sort_items_by_key, create_key_values,
  69. destroy_key_values),
  70. };
  71. return run_tests(tests);
  72. }