django - 尽管调用正常,但测试 Django Rest Framework POST 返回 500

标签 django django-rest-framework

更新

这个问题是由于我没有在 APIClient 的 header 中包含 token 引起的。这已解决。

我在 /test-endpoint 有一个标准的 ModelViewSet .我正在尝试使用 APIClient 来测试端点。

from rest_framework.test import APIClient
... # During this process, a file is uploaded to S3. Could this cause the issue? Again, no errors are thrown. I just get a 500.
self.client = APIClient()
...
sample_call = {
    "name": "test_document",
    "description": "test_document_description"
}
response = self.client.post('/test-endpoint', sample_call, format='json')
self.assertEqual(response.status_code, 201)

此调用适用于我在 sample_call 中设置的参数。它返回 201。但是,当我运行测试时,我得到 500。如何修改它以使 201 通过?

我用 python src/manage.py test modulename 运行测试

为了排除明显的问题,我将示例调用复制粘贴到 Postman 中,然后毫无问题地运行它。我相信 500 状态代码来自这样一个事实,即我正在测试调用而不是在实时环境中使用它。

除了 AssertionError 之外,不会抛出任何错误消息:

AssertionError: 500 != 201



测试的完整输出
/home/bryant/.virtualenvs/REDACTED/lib/python3.4/site- packages/django_boto/s3/shortcuts.py:28: RemovedInDjango110Warning:  Backwards compatibility for storage backends without support for the     `max_length` argument in Storage.get_available_name() will be removed in Django 1.10.
s3.save(full_path, fl)

F
======================================================================
FAIL: test_create (sample.tests.SampleTestCase)
Test CREATE Document
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/bryant/api/redacted/src/sample/tests.py", line 31, in test_create
self.assertEqual(response.status_code, 201)
AssertionError: 500 != 201

----------------------------------------------------------------------
Ran 1 test in 2.673s

FAILED (failures=1)
Destroying test database for alias 'default'...

预计会出现 S3 警告。否则,一切都显得正常。

最佳答案

要在 Django/DRF 中调试失败的测试用例:

  • import pdb; pdb.set_trace()就在断言之前,查看 request.content按照@Igonato 的建议,或者您可以添加 print(request.content) ,没有什么可耻的。
  • 通过添加 -v 3 来增加测试的详细程度
  • 使用点表示法调查特定的测试用例:python src/manage.py test modulename.tests.<TestCase>.<function>

  • 我希望这些是有用的,请记住。

    关于django - 尽管调用正常,但测试 Django Rest Framework POST 返回 500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44292377/

    相关文章:

    Django Rest框架返回 "detail": "Not found."

    django - sorl thumbnail + django 生产中的问题

    python - Django 2.x drf-yasg 如何在自定义方法中创建 API(如 Swagger )

    python - 从 Django Web 表单解析 csv 时出现问题

    database - Django 仅基于日期过滤日期时间

    Django rest 框架 DateField 格式

    javascript - 使用javascript fetch将数据发布到django rest框架

    python - django-rest-swagger : how to group endpoints?

    python - 无法将 Django 模型导入 celery 任务

    Django:项目名称的作用