【问题标题】:Django Rest API Test Request Factory Content EmptyDjango Rest API 测试请求工厂内容为空
【发布时间】:2017-08-04 21:53:56
【问题描述】:

在以下测试中,我遇到了两个错误之一,但我无法解决。这是我在 Django 中的第一个项目,因此是第一次使用它进行测试。我读到 APIRequestFactory 将为测试创建自己的数据库,然后将其清除。与中间件没有交互。

是否可以使用 GET 调用检查数据是否被正确检索?到目前为止,我只能检查状态是否为 200。我正在进行的 GET 或 POST 调用的内容是空的。我在 RequestFactory 中看到的示例没有显示任何数据比较。如果您知道任何示例,我应该能够解决我的问题。

创建后的 Report 对象用于针对发布的数据进行测试

self.assertEqual(response.data['module'], report.module) TypeError: 列表索引必须是整数,而不是 str

我不确定要改变什么才能使这个断言成立。我已经搜索了错误消息,但似乎我没有使用 ListField 作为 report.module,因为这是 Report 的直接字段。

用 /dashboard/modules/ 中的预期 json 数据替换 report.module 时

AssertionError: [] != '[{"module":"testModule"}]'

class GetModules(TestCase):
def setUp(self):
    #access to the request factory
    self.factory = APIRequestFactory()

def test_get_modules(self):
    self.assertEqual(Report.objects.count(), 0)
    Report.objects.create(module="testModule", severity=3, title="Get Modules", data="{}")
    report = Report.objects.get(module="testModule")
    self.assertEqual(Report.objects.count(), 1)

    url = '/dashboard/modules/'
    request = self.factory.get(url)
    response = moduleList(request)

    self.assertEqual(Report.objects.count(), 1)
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(response.data, '[{"module":"testModule"  }]')

我知道该对象存在,因为在创建对象之前和之后,count 的测试返回 0,它是 1。

【问题讨论】:

    标签: python django django-rest-framework django-testing requestfactory


    【解决方案1】:

    response.data 已经是一个 python 对象而不是一个字符串,所以我猜它会等于 {"module":"testModule" }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 2019-05-20
      • 1970-01-01
      相关资源
      最近更新 更多