【发布时间】:2020-04-14 15:59:04
【问题描述】:
在运行测试时,我想创建然后删除一些资源。访问目标服务器需要使用令牌进行身份验证。
from django.test import TestCase
from rest_framework.test import APIClient
(...)
class MyTest(TestCase):
def setUp(self):
self.client = APIClient()
def test_creation_and_deletion(self):
payload = {"key": "value"}
# This works, but it's handled by a custom create() method from views.py:
res = self.client.post(<url>, payload)
(...)
# This doesn't work, no custom delete() method is defined anywhere:
tar_headers = {"private-token": "<token>"}
res2 = self.client.delete(res.data["target_resource_url"], headers=tar_headers)
# Either this doesn't work:
self.client.headers.update(tar_headers)
res3 = self.client.delete(res.data["target_resource_url"])
打印res2 给出以下输出:
<HttpResponseNotFound status_code=404, "text/html">
调用res3会报错:
AttributeError: 'APIClient' object has no attribute 'headers'
从例如target_resource_url 发送的删除请求只要在标头中给出令牌,邮递员就可以正常工作。
如何解决这个问题?
【问题讨论】:
-
这对您有帮助吗? DRF headers & authentication
-
HTTPBasicAuth需要用户名和密码,我认为它不接受任何其他值,因此无法在此处应用。 -
这与
HTTPBasicAuth无关,只是简单地添加client.headers.update({'x-test': 'true'}) -
报错,我只是在上面的标记中添加了
res3,请看一下。
标签: django django-rest-framework django-unittest