Django Rest Framework 测试用例问题:'HttpResponseNotAllowed' 对象没有属性 'data'

Neo*_*Neo 3 python django unit-testing django-rest-framework

我的测试文件代码:

from rest_framework import status
from rest_framework.test import APITestCase

class CategoryTests(APITestCase):

  def test_create_create(self):

    url = '/category/add/'
    data = {"name":"Sports","description":"get live updates here"}
    response = self.client.post(url, data, format='json')
    self.assertEqual(response.data, data)
Run Code Online (Sandbox Code Playgroud)

我得到的错误:

Traceback (most recent call last):
File "/Users/test/webapp/apps/core/tests.py", line 16, in test_create_create
self.assertEqual(response.data, data)
AttributeError: 'HttpResponseNotAllowed' object has no attribute 'data'
Run Code Online (Sandbox Code Playgroud)

事实上,测试甚至没有调用确切的 api 语句(我在 api 代码中使用调试语句检查了这一点)。请让我知道可能出了什么问题,或者您需要更多关于此的信息。

Mar*_*way 5

尝试使用 DRF 扩展测试客户端:

from rest_framework import status
from rest_framework.test import APITestCase, APIClient

class CategoryTests(APITestCase):
  client = APIClient()

  def test_create_create(self):

    url = '/category/add/'
    data = {"name":"Sports","description":"get live updates here"}
    response = self.client.post(url, data, format='json')
    self.assertEquals(response.data, data)
Run Code Online (Sandbox Code Playgroud)