Understanding test_token_validation.py
This test file tests the behavior of the token_validation module. This module covers the generation and validation of the authentication header, so it's important to test it thoroughly.
The tests check that the header can be encoded and decoded with the proper keys. It also checks all the different possibilities in terms of invalid inputs: different shapes of incorrect formats, invalid decoding keys, or expired tokens.
To check for expired tokens, we use two modules: freezegun, to make the test to retrieve a specific test time (https://github.com/spulec/freezegun), and delorean, to parse dates easily (though, the module is capable of way more; check the documentation at https://delorean.readthedocs.io/en/latest/). These two modules are very easy to use and great for testing purposes.
For example, this test checks an expired token:
@freeze_time('2018-05-17 13:47:34')
def test_invalid_token_header_expired():
expiry = delorean.parse('2018-05-17 13:47:33').datetime
payload = {
'username': 'tonystark',
'exp': expiry,
}
token = token_validation.encode_token(payload, PRIVATE_KEY)
token = token.decode('utf8')
header = f'Bearer {token}'
result = token_validation.validate_token_header(header, PUBLIC_KEY)
assert None is result
Note how the freeze time is precisely 1 second after the expiry time of the token.
The public and private keys used for tests are defined in the constants.py file. There's an extra independent public key used to check what happens if you decode a token with an invalid public key.