djnago unittest:即使我发送令牌,clien.get错误401 [英] djnago unittest: clien.get error 401 even if I send token
问题描述
我尝试为方法注销创建一个单元测试,为此,我有这个目的:
I try to create a unittest for method logout, I have this for this purpose:
response = client.get('/api/v1/logout')
self.assertEquals(response.status_code, 200)
但是在我的注销控制器中,我有这个:
but in my logout controller I have this:
permission_classes = (IsAuthenticated,)
因此我将上面的代码更改为:
thus I changed my above code to this:
response = self.client.post('/api/v1/login', data={'username': 'testuser', 'password': '12345678'})
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Bearer ' + response.json()['access_token'])
response = client.get('/api/v1/logout')
self.assertEquals(response.status_code, 200)
但是当我运行测试时,结果为401
but when I run my test I get 401 as result
self.assertEquals(response.status_code, 200)
AssertionError: 401 != 200
我不确定如何将令牌传递给我的请求
I am not sure how can I pass token to my request
推荐答案
tldr,用于登录使用 https://www.django-rest-framework.org/api-guide/testing/#forcing-authentication
tldr, for login use https://www.django-rest-framework.org/api-guide/testing/#forcing-authentication
为什么?
unittest 一次只能测试一个单元.
unittest as the name suggests should test only a single unit at a time.
在这里,我们正在测试两件事,即使不是显式但隐式的.
Here we're testing two things, even though not explicitly but implicitly we're.
- 登录逻辑:我们正在传递用户名和密码,并从响应中获取access_token [即使我们未在此处进行断言,但这会影响下一个块]
- 注销逻辑:我们正在使用以前阻止和测试注销功能的access_token.
我强烈认为我们应该在单元测试中一次只测试单个组件,否则称为集成测试.
I strongly think that we should testing only single component at a time in unit test else call it integration test.
对于我们当前的情况,我们可以编写两个测试用例:
For our current scenario we can write two test cases:
- 测试登录逻辑:传递用户名和密码并断言正确的access_token返回.
- 测试注销逻辑:模拟登录逻辑,仅测试注销逻辑.
对于模拟登录,我们可以使用类似这样的方式 https://www.django-rest-framework.org/api-guide/testing/#forcing-authentication
For mocking login we can use something like this https://www.django-rest-framework.org/api-guide/testing/#forcing-authentication
这篇关于djnago unittest:即使我发送令牌,clien.get错误401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!