gpt4 book ai didi

python - 如何在测试 REST API 时使用 token 认证

转载 作者:行者123 更新时间:2023-11-28 21:22:44 24 4
gpt4 key购买 nike

我正在尝试使用 token 来测试 API 请求。我能够提取 token ,但我很难找到使用它的方法。

这是我获得 token 的方式:

@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 错误。 token的正确使用方法是什么?

最佳答案

解决方案很简单,这是因为我没有测试经验。 test_profile 函数没有注册已在 test_authentification 函数中请求的 token 。所以我不得不将它们都放在 SetUp 函数中,以便为类中的每个函数注册 token 。

关于python - 如何在测试 REST API 时使用 token 认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47729164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com