Skip to content

Commit

Permalink
Mocked time() so that unit tests pass reliably
Browse files Browse the repository at this point in the history
test_new_pcp_error_response() was written in such a way that the test
could assert just because the second call to time() returned a different
value. The test shouldn't have been calling time() it should have been
checking that the original value returned by time() was used.

Signed-off-by: Tobi Wulff <[email protected]>
  • Loading branch information
Greig Hamilton authored and Tobi Wulff committed Sep 6, 2016
1 parent 24e9f3d commit 10954ee
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
12 changes: 11 additions & 1 deletion pcpd/packets_pcp.c
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand Down
15 changes: 13 additions & 2 deletions tests/packets_pcp_unit_tests.c
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down

0 comments on commit 10954ee

Please sign in to comment.