繁体   English   中英

在测试REST API时如何使用令牌认证

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM