[英]How to use token authentication while testing REST API
我正在嘗試使用令牌來測試API請求。 我能夠提取令牌,但是我很難找到一種使用令牌的方法。
這是我獲取令牌的方式:
@pytest.mark.django_db
class TestUserAPI(APITestCase):
def setUp(self):
self.created_user = UserFactory()
User.objects.create_user(username='test', password='pass1234')
def test_authentification(self):
request = self.client.post('http://localhost:8000/api/v1/auth/',
{
"username": "test",
"password": "pass1234"
})
TestUserAPI.token = request.data["token"]
assert request.status_code == 200
這就是我的用法:
def test_profile(self):
request = self.client.get('http://localhost:8000/api/v1/profile/',
TokenAuthentication = 'token {}'.format(TestUserAPI.token))
assert request.status_code == status.HTTP_200_OK
它給我401錯誤。 使用令牌的正確方法是什么?
解決方案很簡單,這是因為我缺乏測試經驗。 test_profile函數不會在test_authentification函數中注冊已詢問令牌的信息。 因此,我必須將它們都放入SetUp函數中,以便為類中的每個函數注冊令牌。
根據文檔,正確的標頭格式為Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
根據官方文檔,令牌密鑰應為Authentication,令牌應為尾隨Token和空白。 在您的代碼中,將令牌{}更改為令牌{}。 如果問題仍然存在,請嘗試通過打印request.META來在視圖中打印請求標頭以檢查密鑰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.