官术网_书友最值得收藏!

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.

It is worth saying it again: please do not use any of these keys. These keys are for running tests only and are available to anyone who has access to this book.
主站蜘蛛池模板: 阳新县| 阿合奇县| 鄂托克旗| 辛集市| 南通市| 新巴尔虎左旗| 泽库县| 祁连县| 新兴县| 修文县| 鄂州市| 襄汾县| 蓬安县| 阜南县| 原平市| 浦江县| 文昌市| 康平县| 镇原县| 株洲县| 和田市| 永济市| 荆州市| 潍坊市| 麻城市| 安仁县| 陇川县| 连州市| 开平市| 清远市| 连南| 时尚| 恭城| 嘉黎县| 公安县| 阜城县| 锡林浩特市| 永城市| 南皮县| 盐津县| 休宁县|