我正在对令牌创建进行单元测试(想想 PyJWT),我需要测试过期令牌是否引发异常:
from jwt.exceptions import ExpiredSignatureError
def test_invalid_logout_expired_token(self):
add_user('testuser', 'testemail@mail.com', 'hakunamatata')
current_app.config['TOKEN_EXPIRATION_SECONDS'] = -1
with self.client:
resp_login = self.client.post(
'/auth/login',
data=json.dumps({
'email': 'testemail@mail.com',
'password': 'hakunamatata'
}),
content_type='application/json'
)
token = json.loads(resp_login.data.decode())['auth_token']
response = self.client.get('/auth/logout', headers={'Authorization': f'Bearer {token}'})
data = json.loads(response.data.decode())
self.assertRaises(ExpiredSignatureError, data) # <-- isn't working
正确引发异常:
File "/usr/src/app/project/api/auth.py", line 90, in logout
resp = User.decode_auth_token(auth_token)
File "/usr/src/app/project/api/models.py", line 45, in decode_auth_token
return jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=["HS256"])
File "/usr/local/lib/python3.8/site-packages/jwt/api_jwt.py", line 119, in decode
decoded = self.decode_complete(jwt, key, algorithms, options, **kwargs)
File "/usr/local/lib/python3.8/site-packages/jwt/api_jwt.py", line 106, in decode_complete
self._validate_claims(payload, merged_options, **kwargs)
File "/usr/local/lib/python3.8/site-packages/jwt/api_jwt.py", line 142, in _validate_claims
self._validate_exp(payload, now, leeway)
File "/usr/local/lib/python3.8/site-packages/jwt/api_jwt.py", line 177, in _validate_exp
raise ExpiredSignatureError("Signature has expired")
jwt.exceptions.ExpiredSignatureError: Signature has expired
但测试运行器给出错误:
test_invalid_logout_expired_token (test_auth.TestAuthBlueprint) ... ERROR
什么是正确的方法?
更新:
def test_invalid_logout_expired_token(self):
add_user('testuser', 'testemail@mail.com', 'hakunamatata')
current_app.config['TOKEN_EXPIRATION_SECONDS'] = -1
with self.client:
resp_login = self.client.post(
'/auth/login',
data=json.dumps({
'email': 'testemail@mail.com',
'password': 'hakunamatata'
}),
content_type='application/json'
)
token = json.loads(resp_login.data.decode())['auth_token']
self.assertRaises(ExpiredSignatureError, User.decode_auth_token(token))
用户等级:
class User:
...
@staticmethod
def decode_auth_token(token):
return jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=["HS256"])
替换data
为User.decode_auth_token()
。