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 <cmockery.h>
20 #include <database.h>
21
22 extern DatabaseConnection* connect_to_customer_database();
23 extern unsigned int get_customer_id_by_name(
24 DatabaseConnection * const connection, const char * const customer_name);
25
26 // Mock query database function.
mock_query_database(DatabaseConnection * const connection,const char * const query_string,void *** const results)27 unsigned int mock_query_database(
28 DatabaseConnection* const connection, const char * const query_string,
29 void *** const results) {
30 *results = (void**)mock();
31 return (unsigned int)mock();
32 }
33
34 // Mock of the connect to database function.
connect_to_database(const char * const database_url,const unsigned int port)35 DatabaseConnection* connect_to_database(const char * const database_url,
36 const unsigned int port) {
37 return (DatabaseConnection*)mock();
38 }
39
test_connect_to_customer_database(void ** state)40 void test_connect_to_customer_database(void **state) {
41 will_return(connect_to_database, 0x0DA7ABA53);
42 assert_int_equal((int)connect_to_customer_database(), 0x0DA7ABA53);
43 }
44
45 /* This test fails as the mock function connect_to_database() will have no
46 * value to return. */
fail_connect_to_customer_database(void ** state)47 void fail_connect_to_customer_database(void **state) {
48 assert_true(connect_to_customer_database() ==
49 (DatabaseConnection*)0x0DA7ABA53);
50 }
51
test_get_customer_id_by_name(void ** state)52 void test_get_customer_id_by_name(void **state) {
53 DatabaseConnection connection = {
54 "somedatabase.somewhere.com", 12345678, mock_query_database
55 };
56 // Return a single customer ID when mock_query_database() is called.
57 int customer_ids = 543;
58 will_return(mock_query_database, &customer_ids);
59 will_return(mock_query_database, 1);
60 assert_int_equal(get_customer_id_by_name(&connection, "john doe"), 543);
61 }
62
main(int argc,char * argv[])63 int main(int argc, char* argv[]) {
64 const UnitTest tests[] = {
65 unit_test(test_connect_to_customer_database),
66 unit_test(test_get_customer_id_by_name),
67 };
68 return run_tests(tests);
69 }
70