You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

707 lines
26 KiB

  1. <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
  2. <html><head>
  3. <title>cmocka</title>
  4. </head>
  5. <body>
  6. <h1>cmocka Unit Testing Framework</h1>
  7. <p>cmocka is a lightweight library that is used to author C unit tests.</p>
  8. <ul>Contents
  9. <li><a href="#Motivation">Motivation</a></li>
  10. <li><a href="#Overview">Overview</a></li>
  11. <li><a href="#Test_Execution">Test Execution</a>
  12. <li><a href="#Exception_Handling">Exception Handling</a></li>
  13. <li><a href="#Failure_Conditions">Failure Conditions</a></li>
  14. <li><a href="#Assertions">Assertions</a></li>
  15. <ul>
  16. <li><a href="#Assert_Macros">Assert Macros</a></li>
  17. </ul>
  18. <li><a href="#Dynamic_Memory_Allocation">Dynamic Memory Allocation</a></li>
  19. <li><a href="#Mock_Functions">Mock functions</a></li>
  20. <ul>
  21. <li><a href="#Return_Values">Return Values</a></li>
  22. <li><a href="#Checking_Parameters">Checking Parameters</a></li>
  23. </ul>
  24. <li><a href="#Test_State">Test State</a></li>
  25. <li><a href="#Example">Example</a></li>
  26. </ul>
  27. <a name="Motivation"><h2>Motivation</h2></a>
  28. <p>There are a variety of C unit testing frameworks available however many of
  29. them are fairly complex and require the latest compiler technology. Some
  30. development requires the use of old compilers which makes it difficult to
  31. use some unit testing frameworks. In addition many unit testing frameworks
  32. assume the code being tested is an application or module that is targeted to
  33. the same platform that will ultimately execute the test. Because of this
  34. assumption many frameworks require the inclusion of standard C library headers
  35. in the code module being tested which may collide with the custom or
  36. incomplete implementation of the C library utilized by the code under test.</p>
  37. <p>cmocka only requires a test application is linked with the standard C
  38. library which minimizes conflicts with standard C library headers. Also,
  39. cmocka tries avoid the use of some of the newer features of C compilers.</p>
  40. <p>This results in cmocka being a relatively small library that can be used
  41. to test a variety of exotic code. If a developer wishes to simply test an
  42. application with the latest compiler then other unit testing frameworks maybe
  43. preferable.</p>
  44. <a name="Overview"><h2>Overview</h2></a>
  45. <p>cmocka tests are compiled into stand-alone executables and linked with
  46. the cmocka library, the standard C library and module being tested. Any
  47. symbols external to the module being tested should be mocked - replaced with
  48. functions that return values determined by the test - within the test
  49. application. Even though significant differences may exist between the target
  50. execution environment of a code module and the environment used to test the
  51. code the unit testing is still valid since its goal is to test the logic of a
  52. code modules at a functional level and not necessarily all of its interactions
  53. with the target execution environment.</p>
  54. <p>It may not be possible to compile a module into a test application without
  55. some modification, therefore the preprocessor symbol <b>UNIT_TESTING</b> should
  56. be defined when cmocka unit test applications are compiled so code within the
  57. module can be conditionally compiled for tests.</p>
  58. <a name="Test_Execution"><h2>Test Execution</h2></a>
  59. <p>cmocka unit test cases are functions with the signature
  60. <b>void function(void **state)</b>. cmocka test applications initialize a
  61. table with test case function pointers using <b>unit_test*()</b> macros. This
  62. table is then passed to the <b>run_tests()</b> macro to execute the tests.
  63. <b>run_tests()</b> sets up the appropriate exception / signal handlers and
  64. other data structures prior to running each test function. When a unit test
  65. is complete <b>run_tests()</b> performs various checks to determine whether
  66. the test succeeded.</p>
  67. <h4>Using run_tests()</h4>
  68. <a href="../example/run_tests.c">run_tests.c</a>
  69. <listing>
  70. #include &lt;stdarg.h&gt;
  71. #include &lt;stddef.h&gt;
  72. #include &lt;setjmp.h&gt;
  73. #include &lt;cmocka.h&gt;
  74. // A test case that does nothing and succeeds.
  75. void null_test_success(void **state) {
  76. }
  77. int main(int argc, char* argv[]) {
  78. const UnitTest tests[] = {
  79. unit_test(null_test_success),
  80. };
  81. return run_tests(tests);
  82. }
  83. </listing>
  84. <a name="Exception_Handling"><h2>Exception Handling</h2></a>
  85. <p>Before a test function is executed by <b>run_tests()</b>,
  86. exception / signal handlers are overridden with a handler that simply
  87. displays an error and exits a test function if an exception occurs. If an
  88. exception occurs outside of a test function, for example in cmocka itself,
  89. the application aborts execution and returns an error code.</p>
  90. <a name="Failure_Conditions"><h2>Failure Conditions</h2></a>
  91. <p>If a failure occurs during a test function that's executed via
  92. <b>run_tests()</b>, the test function is aborted and the application's
  93. execution resumes with the next test function.
  94. Test failures are ultimately signalled via the cmocka function <b>fail()</b>.
  95. The following events will result in the cmocka library signalling a test
  96. failure...
  97. <ul>
  98. <li><a href="#Assertions">Assertions</a></li>
  99. <li><a href="#Exception_Handling">Exceptions</a></li>
  100. <li><a href="#Dynamic_Memory_Allocation">Memory leaks</a></li>
  101. <li><a href="#Test_State">Mismatched setup and tear down functions</a></li>
  102. <li><a href="#Return_Values">Missing mock return values</a></li>
  103. <li><a href="#Return_Values">Unused mock return values</a></li>
  104. <li><a href="#Checking_Parameters">Missing expected parameter values</a></li>
  105. <li><a href="#Checking_Parameters">Unused expected parameter values</a></li>
  106. </ul>
  107. </p>
  108. <a name="Assertions"><h2>Assertions</h2></a>
  109. <p>Runtime assert macros like the standard C library's <b>assert()</b> should
  110. be redefined in modules being tested to use cmocka's <b>mock_assert()</b>
  111. function. Normally <b>mock_assert()</b> signals a
  112. <a href="#Failure_Conditions">test failure</a>. If a function is called using
  113. the <b>expect_assert_failure()</b> macro, any calls to <b>mock_assert()</b>
  114. within the function will result in the execution of the test. If no
  115. calls to <b>mock_assert()</b> occur during the function called via
  116. <b>expect_assert_failure()</b> a test failure is signalled.</p>
  117. <h4>Using mock_assert()</h4>
  118. <a href="../example/assert_module.c">assert_module.c</a>
  119. <listing>
  120. #include &lt;assert.h&gt;
  121. // If unit testing is enabled override assert with mock_assert().
  122. #ifdef UNIT_TESTING
  123. extern void mock_assert(const int result, const char* const expression,
  124. const char * const file, const int line);
  125. #undef assert
  126. #define assert(expression) \
  127. mock_assert((int)(expression), #expression, __FILE__, __LINE__);
  128. #endif // UNIT_TESTING
  129. void increment_value(int * const value) {
  130. assert(value);
  131. (*value) ++;
  132. }
  133. void decrement_value(int * const value) {
  134. if (value) {
  135. *value --;
  136. }
  137. }
  138. </listing>
  139. <a href="../example/assert_module_test.c">assert_module_test.c</a>
  140. <listing>
  141. #include &lt;stdarg.h&gt;
  142. #include &lt;stddef.h&gt;
  143. #include &lt;setjmp.h&gt;
  144. #include &lt;cmocka.h&gt;
  145. extern void increment_value(int * const value);
  146. /* This test case will fail but the assert is caught by run_tests() and the
  147. * next test is executed. */
  148. void increment_value_fail(void **state) {
  149. increment_value(NULL);
  150. }
  151. // This test case succeeds since increment_value() asserts on the NULL pointer.
  152. void increment_value_assert(void **state) {
  153. expect_assert_failure(increment_value(NULL));
  154. }
  155. /* This test case fails since decrement_value() doesn't assert on a NULL
  156. * pointer. */
  157. void decrement_value_fail(void **state) {
  158. expect_assert_failure(decrement_value(NULL));
  159. }
  160. int main(int argc, char *argv[]) {
  161. const UnitTest tests[] = {
  162. unit_test(increment_value_fail),
  163. unit_test(increment_value_assert),
  164. unit_test(decrement_value_fail),
  165. };
  166. return run_tests(tests);
  167. }
  168. </listing>
  169. <h3><a name="Assert_Macros">Assert Macros</a></h3>
  170. <p>cmocka provides an assortment of assert macros that tests applications
  171. should use use in preference to the C standard library's assert macro. On an
  172. assertion failure a cmocka assert macro will write the failure to the
  173. standard error stream and signal a test failure. Due to limitations of the
  174. C language the general C standard library assert() and cmocka's
  175. assert_true() and assert_false() macros can only display the expression that
  176. caused the assert failure. cmocka's type specific assert macros,
  177. assert_{type}_equal() and assert_{type}_not_equal(), display the data that
  178. caused the assertion failure which increases data visibility aiding
  179. debugging of failing test cases.</p>
  180. <h4>Using assert_{type}_equal() macros</h4>
  181. <a href="../example/assert_macro.c">assert_macro.c</a>
  182. <listing>
  183. #include &lt;string.h&gt;
  184. static const char* status_code_strings[] = {
  185. "Address not found",
  186. "Connection dropped",
  187. "Connection timed out",
  188. };
  189. const char* get_status_code_string(const unsigned int status_code) {
  190. return status_code_strings[status_code];
  191. };
  192. unsigned int string_to_status_code(const char* const status_code_string) {
  193. unsigned int i;
  194. for (i = 0; i < sizeof(status_code_strings) /
  195. sizeof(status_code_strings[0]); i++) {
  196. if (strcmp(status_code_strings[i], status_code_string) == 0) {
  197. return i;
  198. }
  199. }
  200. return ~0U;
  201. }
  202. </listing>
  203. <a href="../example/assert_macro_test.c">assert_macro_test.c</a>
  204. <listing>
  205. #include &lt;stdarg.h&gt;
  206. #include &lt;stddef.h&gt;
  207. #include &lt;setjmp.h&gt;
  208. #include &lt;cmocka.h&gt;
  209. extern const char* get_status_code_string(const unsigned int status_code);
  210. extern unsigned int string_to_status_code(
  211. const char* const status_code_string);
  212. /* This test will fail since the string returned by get_status_code_string(0)
  213. * doesn't match "Connection timed out". */
  214. void get_status_code_string_test(void **state) {
  215. assert_string_equal(get_status_code_string(0), "Address not found");
  216. assert_string_equal(get_status_code_string(1), "Connection timed out");
  217. }
  218. // This test will fail since the status code of "Connection timed out" isn't 1
  219. void string_to_status_code_test(void **state) {
  220. assert_int_equal(string_to_status_code("Address not found"), 0);
  221. assert_int_equal(string_to_status_code("Connection timed out"), 1);
  222. }
  223. int main(int argc, char *argv[]) {
  224. const UnitTest tests[] = {
  225. unit_test(get_status_code_string_test),
  226. unit_test(string_to_status_code_test),
  227. };
  228. return run_tests(tests);
  229. }
  230. </listing>
  231. <a name="Dynamic_Memory_Allocation"><h2>Dynamic Memory Allocation</h2></a>
  232. <p>To test for memory leaks, buffer overflows and underflows a module being
  233. tested by cmocka should replace calls to <b>malloc()</b>, <b>calloc()</b> and
  234. <b>free()</b> to <b>test_malloc()</b>, <b>test_calloc()</b> and
  235. <b>test_free()</b> respectively. Each time a block is deallocated using
  236. <b>test_free()</b> it is checked for corruption, if a corrupt block is found
  237. a <a href="#Failure_Conditions">test failure</a> is signalled. All blocks
  238. allocated using the <b>test_*()</b> allocation functions are tracked by the
  239. cmocka library. When a test completes if any allocated blocks (memory leaks)
  240. remain they are reported and a test failure is signalled.</p>
  241. <p>For simplicity cmocka currently executes all tests in one process.
  242. Therefore all test cases in a test application share a single address space
  243. which means memory corruption from a single test case could potentially cause
  244. the test application to exit prematurely.</p>
  245. <h4>Using cmocka's Allocators</h4>
  246. <a href="../example/allocate_module.c">allocate_module.c</a>
  247. <listing>
  248. #include &lt;malloc.h&gt;
  249. #ifdef UNIT_TESTING
  250. extern void* _test_malloc(const size_t size, const char* file, const int line);
  251. extern void* _test_calloc(const size_t number_of_elements, const size_t size,
  252. const char* file, const int line);
  253. extern void _test_free(void* const ptr, const char* file, const int line);
  254. #define malloc(size) _test_malloc(size, __FILE__, __LINE__)
  255. #define calloc(num, size) _test_calloc(num, size, __FILE__, __LINE__)
  256. #define free(ptr) _test_free(ptr, __FILE__, __LINE__)
  257. #endif // UNIT_TESTING
  258. void leak_memory() {
  259. int * const temporary = (int*)malloc(sizeof(int));
  260. *temporary = 0;
  261. }
  262. void buffer_overflow() {
  263. char * const memory = (char*)malloc(sizeof(int));
  264. memory[sizeof(int)] = '!';
  265. free(memory);
  266. }
  267. void buffer_underflow() {
  268. char * const memory = (char*)malloc(sizeof(int));
  269. memory[-1] = '!';
  270. free(memory);
  271. }
  272. </listing>
  273. <a href="../example/allocate_module_test.c">allocate_module_test.c</a>
  274. <listing>
  275. #include &lt;stdarg.h&gt;
  276. #include &lt;stddef.h&gt;
  277. #include &lt;setjmp.h&gt;
  278. #include &lt;cmocka.h&gt;
  279. extern void leak_memory();
  280. extern void buffer_overflow();
  281. extern void buffer_underflow();
  282. // Test case that fails as leak_memory() leaks a dynamically allocated block.
  283. void leak_memory_test(void **state) {
  284. leak_memory();
  285. }
  286. // Test case that fails as buffer_overflow() corrupts an allocated block.
  287. void buffer_overflow_test(void **state) {
  288. buffer_overflow();
  289. }
  290. // Test case that fails as buffer_underflow() corrupts an allocated block.
  291. void buffer_underflow_test(void **state) {
  292. buffer_underflow();
  293. }
  294. int main(int argc, char* argv[]) {
  295. const UnitTest tests[] = {
  296. unit_test(leak_memory_test),
  297. unit_test(buffer_overflow_test),
  298. unit_test(buffer_underflow_test),
  299. };
  300. return run_tests(tests);
  301. }
  302. </listing>
  303. <a name="Mock_Functions"><h2>Mock Functions</h2></a>
  304. <p>A unit test should ideally isolate the function or module being tested
  305. from any external dependencies. This can be performed using mock functions
  306. that are either statically or dynamically linked with the module being tested.
  307. Mock functions must be statically linked when the code being tested directly
  308. references external functions. Dynamic linking is simply the process of
  309. setting a function pointer in a table used by the tested module to reference
  310. a mock function defined in the unit test.</p>
  311. <a name="Return_Values"><h3>Return Values</h3></a>
  312. <p>In order to simplify the implementation of mock functions cmocka provides
  313. functionality which stores return values for mock functions in each test
  314. case using <b>will_return()</b>. These values are then returned by each mock
  315. function using calls to <b>mock()</b>.
  316. Values passed to <b>will_return()</b> are added to a queue for each function
  317. specified. Each successive call to <b>mock()</b> from a function removes a
  318. return value from the queue. This makes it possible for a mock function to use
  319. multiple calls to <b>mock()</b> to return output parameters in addition to a
  320. return value. In addition this allows the specification of return values for
  321. multiple calls to a mock function.</p>
  322. <h4>Using will_return()</h4>
  323. <a href="../example/database.h">database.h</a>
  324. <listing>
  325. typedef struct DatabaseConnection DatabaseConnection;
  326. /* Function that takes an SQL query string and sets results to an array of
  327. * pointers with the result of the query. The value returned specifies the
  328. * number of items in the returned array of results. The returned array of
  329. * results are statically allocated and should not be deallocated using free()
  330. */
  331. typedef unsigned int (*QueryDatabase)(
  332. DatabaseConnection* const connection, const char * const query_string,
  333. void *** const results);
  334. // Connection to a database.
  335. struct DatabaseConnection {
  336. const char *url;
  337. unsigned int port;
  338. QueryDatabase query_database;
  339. };
  340. // Connect to a database.
  341. DatabaseConnection* connect_to_database(const char * const url,
  342. const unsigned int port);
  343. </listing>
  344. <a href="../example/customer_database.c">customer_database.c</a>
  345. <listing>
  346. #include &lt;stddef.h&gt;
  347. #include &lt;stdio.h&gt;
  348. #include &lt;database.h&gt;
  349. #ifdef _WIN32
  350. #define snprintf _snprintf
  351. #endif // _WIN32
  352. // Connect to the database containing customer information.
  353. DatabaseConnection* connect_to_customer_database() {
  354. return connect_to_database("customers.abcd.org", 321);
  355. }
  356. /* Find the ID of a customer by his/her name returning a value > 0 if
  357. * successful, 0 otherwise. */
  358. unsigned int get_customer_id_by_name(
  359. DatabaseConnection * const connection,
  360. const char * const customer_name) {
  361. char query_string[256];
  362. int number_of_results;
  363. void **results;
  364. snprintf(query_string, sizeof(query_string),
  365. "SELECT ID FROM CUSTOMERS WHERE NAME = %s", customer_name);
  366. number_of_results = connection->query_database(connection, query_string,
  367. &results);
  368. if (number_of_results != 1) {
  369. return -1;
  370. }
  371. return (unsigned int)results[0];
  372. }
  373. </listing>
  374. <a href="../example/customer_database_test.c">customer_database_test.c</a>
  375. <listing>
  376. #include &lt;stdarg.h&gt;
  377. #include &lt;stddef.h&gt;
  378. #include &lt;setjmp.h&gt;
  379. #include &lt;cmocka.h&gt;
  380. #include &lt;database.h&gt;
  381. extern DatabaseConnection* connect_to_customer_database();
  382. extern unsigned int get_customer_id_by_name(
  383. DatabaseConnection * const connection, const char * const customer_name);
  384. // Mock query database function.
  385. unsigned int mock_query_database(
  386. DatabaseConnection* const connection, const char * const query_string,
  387. void *** const results) {
  388. *results = (void**)mock();
  389. return (unsigned int)mock();
  390. }
  391. // Mock of the connect to database function.
  392. DatabaseConnection* connect_to_database(const char * const database_url,
  393. const unsigned int port) {
  394. return (DatabaseConnection*)mock();
  395. }
  396. void test_connect_to_customer_database(void **state) {
  397. will_return(connect_to_database, 0x0DA7ABA53);
  398. assert_true(connect_to_customer_database() ==
  399. (DatabaseConnection*)0x0DA7ABA53);
  400. }
  401. /* This test fails as the mock function connect_to_database() will have no
  402. * value to return. */
  403. void fail_connect_to_customer_database(void **state) {
  404. will_return(connect_to_database, 0x0DA7ABA53);
  405. assert_true(connect_to_customer_database() ==
  406. (DatabaseConnection*)0x0DA7ABA53);
  407. }
  408. void test_get_customer_id_by_name(void **state) {
  409. DatabaseConnection connection = {
  410. "somedatabase.somewhere.com", 12345678, mock_query_database
  411. };
  412. // Return a single customer ID when mock_query_database() is called.
  413. int customer_ids = 543;
  414. will_return(mock_query_database, &customer_ids);
  415. will_return(mock_query_database, 1);
  416. assert_int_equal(get_customer_id_by_name(&connection, "john doe"), 543);
  417. }
  418. int main(int argc, char* argv[]) {
  419. const UnitTest tests[] = {
  420. unit_test(test_connect_to_customer_database),
  421. unit_test(fail_connect_to_customer_database),
  422. unit_test(test_get_customer_id_by_name),
  423. };
  424. return run_tests(tests);
  425. }
  426. </listing>
  427. <a name="Checking_Parameters"><h3>Checking Parameters</h3></a>
  428. <p>In addition to storing the return values of mock functions, cmocka
  429. provides functionality to store expected values for mock function parameters
  430. using the expect_*() functions provided. A mock function parameter can then
  431. be validated using the check_expected() macro.
  432. <p>Successive calls to expect_*() macros for a parameter queues values to
  433. check the specified parameter. check_expected() checks a function parameter
  434. against the next value queued using expect_*(), if the parameter check fails a
  435. test failure is signalled. In addition if check_expected() is called and
  436. no more parameter values are queued a test failure occurs.</p>
  437. <h4>Using expect_*()</h4>
  438. <a href="../example/product_database.c">product_database.c</a>
  439. <listing>
  440. #include &lt;database.h&gt;
  441. // Connect to the database containing customer information.
  442. DatabaseConnection* connect_to_product_database() {
  443. return connect_to_database("products.abcd.org", 322);
  444. }
  445. </listing>
  446. <a href="../example/product_database_test.c">product_database_test.c</a>
  447. <listing>
  448. #include &lt;stdarg.h&gt;
  449. #include &lt;stddef.h&gt;
  450. #include &lt;setjmp.h&gt;
  451. #include &lt;cmocka.h&gt;
  452. #include &lt;database.h&gt;
  453. extern DatabaseConnection* connect_to_product_database();
  454. /* Mock connect to database function.
  455. * NOTE: This mock function is very general could be shared between tests
  456. * that use the imaginary database.h module. */
  457. DatabaseConnection* connect_to_database(const char * const url,
  458. const unsigned int port) {
  459. check_expected(url);
  460. check_expected(port);
  461. return (DatabaseConnection*)mock();
  462. }
  463. void test_connect_to_product_database(void **state) {
  464. expect_string(connect_to_database, url, "products.abcd.org");
  465. expect_value(connect_to_database, port, 322);
  466. will_return(connect_to_database, 0xDA7ABA53);
  467. assert_int_equal(connect_to_product_database(), 0xDA7ABA53);
  468. }
  469. /* This test will fail since the expected URL is different to the URL that is
  470. * passed to connect_to_database() by connect_to_product_database(). */
  471. void test_connect_to_product_database_bad_url(void **state) {
  472. expect_string(connect_to_database, url, "products.abcd.com");
  473. expect_value(connect_to_database, port, 322);
  474. will_return(connect_to_database, 0xDA7ABA53);
  475. assert_int_equal((int)connect_to_product_database(), 0xDA7ABA53);
  476. }
  477. /* This test will fail since the mock connect_to_database() will attempt to
  478. * retrieve a value for the parameter port which isn't specified by this
  479. * test function. */
  480. void test_connect_to_product_database_missing_parameter(void **state) {
  481. expect_string(connect_to_database, url, "products.abcd.org");
  482. will_return(connect_to_database, 0xDA7ABA53);
  483. assert_int_equal((int)connect_to_product_database(), 0xDA7ABA53);
  484. }
  485. int main(int argc, char* argv[]) {
  486. const UnitTest tests[] = {
  487. unit_test(test_connect_to_product_database),
  488. unit_test(test_connect_to_product_database_bad_url),
  489. unit_test(test_connect_to_product_database_missing_parameter),
  490. };
  491. return run_tests(tests);
  492. }
  493. </listing>
  494. <a name="Test_State"><h2>Test State</h2></a>
  495. <p>cmocka allows the specification of multiple setup and tear down functions
  496. for each test case. Setup functions, specified by the <b>unit_test_setup()</b>
  497. or <b>unit_test_setup_teardown()</b> macros allow common initialization to be
  498. shared between multiple test cases. In addition, tear down functions,
  499. specified by the <b>unit_test_teardown()</b> or
  500. <b>unit_test_setup_teardown()</b> macros provide a code path that is always
  501. executed for a test case even when it fails.</p>
  502. <h4>Using unit_test_setup_teardown()</h4>
  503. <a href="../example/key_value.c">key_value.c</a>
  504. <listing>
  505. #include &lt;stddef.h&gt;
  506. #include &lt;stdlib.h&gt;
  507. #include &lt;string.h&gt;
  508. typedef struct KeyValue {
  509. unsigned int key;
  510. const char* value;
  511. } KeyValue;
  512. static KeyValue *key_values = NULL;
  513. static unsigned int number_of_key_values = 0;
  514. void set_key_values(KeyValue * const new_key_values,
  515. const unsigned int new_number_of_key_values) {
  516. key_values = new_key_values;
  517. number_of_key_values = new_number_of_key_values;
  518. }
  519. // Compare two key members of KeyValue structures.
  520. int key_value_compare_keys(const void *a, const void *b) {
  521. return (int)((KeyValue*)a)->key - (int)((KeyValue*)b)->key;
  522. }
  523. // Search an array of key value pairs for the item with the specified value.
  524. KeyValue* find_item_by_value(const char * const value) {
  525. unsigned int i;
  526. for (i = 0; i < number_of_key_values; i++) {
  527. if (strcmp(key_values[i].value, value) == 0) {
  528. return &key_values[i];
  529. }
  530. }
  531. return NULL;
  532. }
  533. // Sort an array of key value pairs by key.
  534. void sort_items_by_key() {
  535. qsort(key_values, number_of_key_values, sizeof(*key_values),
  536. key_value_compare_keys);
  537. }
  538. </listing>
  539. <a href="../example/key_value_test.c">key_value_test.c</a>
  540. <listing>
  541. #include &lt;stdarg.h&gt;
  542. #include &lt;stddef.h&gt;
  543. #include &lt;setjmp.h&gt;
  544. #include &lt;string.h&gt;
  545. #include &lt;cmocka.h&gt;
  546. /* This is duplicated here from the module setup_teardown.c to reduce the
  547. * number of files used in this test. */
  548. typedef struct KeyValue {
  549. unsigned int key;
  550. const char* value;
  551. } KeyValue;
  552. void set_key_values(KeyValue * const new_key_values,
  553. const unsigned int new_number_of_key_values);
  554. extern KeyValue* find_item_by_value(const char * const value);
  555. extern void sort_items_by_key();
  556. static KeyValue key_values[] = {
  557. { 10, "this" },
  558. { 52, "test" },
  559. { 20, "a" },
  560. { 13, "is" },
  561. };
  562. void create_key_values(void **state) {
  563. KeyValue * const items = (KeyValue*)test_malloc(sizeof(key_values));
  564. memcpy(items, key_values, sizeof(key_values));
  565. *state = (void*)items;
  566. set_key_values(items, sizeof(key_values) / sizeof(key_values[0]));
  567. }
  568. void destroy_key_values(void **state) {
  569. test_free(*state);
  570. set_key_values(NULL, 0);
  571. }
  572. void test_find_item_by_value(void **state) {
  573. unsigned int i;
  574. for (i = 0; i < sizeof(key_values) / sizeof(key_values[0]); i++) {
  575. KeyValue * const found = find_item_by_value(key_values[i].value);
  576. assert_true(found);
  577. assert_int_equal(found->key, key_values[i].key);
  578. assert_string_equal(found->value, key_values[i].value);
  579. }
  580. }
  581. void test_sort_items_by_key(void **state) {
  582. unsigned int i;
  583. KeyValue * const kv = *state;
  584. sort_items_by_key();
  585. for (i = 1; i < sizeof(key_values) / sizeof(key_values[0]); i++) {
  586. assert_true(kv[i - 1].key < kv[i].key);
  587. }
  588. }
  589. int main(int argc, char* argv[]) {
  590. const UnitTest tests[] = {
  591. unit_test_setup_teardown(test_find_item_by_value, create_key_values,
  592. destroy_key_values),
  593. unit_test_setup_teardown(test_sort_items_by_key, create_key_values,
  594. destroy_key_values),
  595. };
  596. return run_tests(tests);
  597. }
  598. </listing>
  599. <a name="Example"><h2>Example</h2></a>
  600. <p>A small command line calculator
  601. <a href="../example/calculator.c">calculator.c</a> application
  602. and test application that full exercises the calculator application
  603. <a href="../example/calculator_test.c">calculator_test.c</a>
  604. are provided as an example of cmocka's features discussed in this document.
  605. </p>
  606. <hr>
  607. <address></address>
  608. <!-- hhmts start --> Last modified: Wed Jul 22 12:11:43 PDT 2009 <!-- hhmts end -->
  609. </body> </html>