diff --git a/pcpd/packets_pcp.c b/pcpd/packets_pcp.c index 9dfbd32..6d19ef4 100644 --- a/pcpd/packets_pcp.c +++ b/pcpd/packets_pcp.c @@ -129,6 +129,16 @@ new_pcp_peer_request (u_int32_t requested_lifetime, const char *ip6str) return peer_req; } +/** + * A wrapper for time, this allows the unit tests to mock time and ensure + * that the correct time is being returned from functions. + */ +time_t __attribute__ ((noinline)) +pcp_time (time_t *t) +{ + return time (t); +} + /** * @brief new_pcp_error_response - Create a new error PCP response * @param r_opcode - The r_opcode value in the original packet @@ -145,7 +155,7 @@ new_pcp_error_response (u_int8_t r_opcode, result_code result, u_int32_t lifetim error_resp->reserved = 0; error_resp->result_code = result; error_resp->lifetime = lifetime; - error_resp->epoch_time = time (NULL); + error_resp->epoch_time = pcp_time (NULL); error_resp->reserved_array[0] = 0; error_resp->reserved_array[1] = 0; error_resp->reserved_array[2] = 0; diff --git a/tests/packets_pcp_unit_tests.c b/tests/packets_pcp_unit_tests.c index adf14a1..35ed121 100644 --- a/tests/packets_pcp_unit_tests.c +++ b/tests/packets_pcp_unit_tests.c @@ -707,15 +707,26 @@ test_new_pcp_map_response (void) free (map_resp); } +time_t pcp_time (time_t *t); +time_t error_response_time; + +time_t +my_time_for_error_response (time_t *t) +{ + error_response_time = time (t); + return error_response_time; +} + void test_new_pcp_error_response (void) { + np_mock (pcp_time, my_time_for_error_response); + pcp_response_header *resp = new_pcp_error_response (MAP_OPCODE, EXCESSIVE_REMOTE_PEERS, 3000); - // Test may fail if one second passes so check epoch time first to reduce chance of failing - NP_ASSERT_EQUAL (resp->epoch_time, (u_int32_t) time (NULL)); + NP_ASSERT_EQUAL (resp->epoch_time, (u_int32_t) error_response_time); NP_ASSERT_EQUAL (resp->version, PCP_VERSION); NP_ASSERT_EQUAL (resp->r_opcode, R_RESPONSE (MAP_OPCODE));