Django Rest框架测试响应头
我正在尝试创建自动化测试,我想要的是在我的测试用例中检查是否有一个位置头,它应该基于views.py中的代码(已经在Advanced REST Client中测试过)。但是,我无法在tests.py中解析它 这是我的代码:Django Rest框架测试响应头,django,django-rest-framework,Django,Django Rest Framework,我正在尝试创建自动化测试,我想要的是在我的测试用例中检查是否有一个位置头,它应该基于views.py中的代码(已经在Advanced REST Client中测试过)。但是,我无法在tests.py中解析它 这是我的代码: from rest_framework import status from rest_framework.test import APITestCase url_1 = reverse('artists-list') class ArtistTest(APITestCas
from rest_framework import status
from rest_framework.test import APITestCase
url_1 = reverse('artists-list')
class ArtistTest(APITestCase):
# Check the response if there is no data
def test_get(self):
# Checks the artists
# self.client attribute will be an APIClient instance
# Basically it will act as a client
response = self.client.get(url_1)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
self.assertEqual(response.content, '') # There should be no data
# self.assertEqual(len(data), 0)
# print ("%s.%s DONE - 1" % (self.__class__.__name__, inspect.stack()[0][3]))
def test_post(self):
_data = {"name": "50 Cent", "birth_date":"2005-02-13"}
response = self.client.post(url_1, _data)
print "----"
print response.headers
data = json.loads(response.content)["data"]
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(data, _data)
self.assertEqual(Artist.objects.count(), 1)
self.assertEqual(Artist.objects.get().name, '50 Cent')
p.S.
请注意:
print response.headers # this throws an error
print response # shows the header but I want it to be parsed
万一有人遇到同样的问题。打印或返回位置标题的代码为:
# url, just set your endpoint here
# data, just set the data that you will request here
response = self.client.post(url, data)
response["Location"]
来源:有几个选项:
>>> response.has_header('Location')
True
>>> response.get('Location') # None if key not in headers
My location
>>> response['Location'] # KeyError if key doesn't exist
My location
>>> response._headers # headers as dict
{'allow': ('Allow', 'GET, POST, HEAD, OPTIONS'), 'Location': ...}
>>> response.serialize_headers() # headers as bytestring (in Python 3)
b'Allow: GET, POST, HEAD, OPTIONS\r\nLocation: ...'