Django REST rest_framework.testsAPIClient post方法返回400错误请求
我的测试无法创建 Designer 对象,但我可以在服务器运行后使用 Postman 手动创建。我怀疑是 APIClient 的问题?
我正在使用rest_framework_simplejwt,它在其他单元测试中运行良好。此特定操作在 django shell 中也会失败。
test.py:
class DesignerTest(APITestCase):
"""
Tests Designer model, views and serializer functionality.
"""
def setUp(self):
"""
Setup the test environment.
"""
self.user = get_user_model().objects.create_user(
email='[email protected]',
name='Test Name',
password='passtest123'
)
self.client = APIClient()
self.refresh = RefreshToken().for_user(self.user)
self.access = self.refresh.access_token
self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.access}")
def test_designer_creation_successful(self):
"""Test that correct input successfully creates Designer object"""
payload = {
'first_name': 'Joe',
'last_name': 'Aughberry',
'date_of_birth': '1952-05-17',
'date_of_death': '2003-09-18',
'place_of_birth': 'Aukland',
'nationality': 'New Zealander',
'university': 'University of Aukland',
'website': 'www.joeaughberrydesign.com',
'added_by_user': self.user.pk
}
# Create the Desinger object through a POST request
response = self.client.post(DESIGNER_LIST_URL, data=payload)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
如果我运行 print(response)
,则会返回:
并且没有其他错误消息。
我在这里缺少什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可能为时已晚,但是如果仍然对某人有帮助。响应状态代码400点验证错误,这可能意味着某些必需字段丢失,这是请求不会传递。实际上,它几乎可以肯定会传递一个空的dict(可以通过在相应的查看集方法中打印
request.data
来检查。原因是数据通过没有任何指定的指示是JSON的传递。这可以通过两种方式固定:1。
基本上在DRF文档这里 a>。
I may be too late to respond, but what if it still helps somebody. The response status code 400 points to a validation error, which likely means that some of the required fields are missing, that is the request doesn't pass them. In fact, it almost certainly passes an empty dict (which can be checked by printing the
request.data
in the corresponding viewset method). The reason is that the data are passed without any specified indication that it is json. This can be fixed in two ways:1.
This is basically discussed in the DRF docs here.