更新
这个问题是由于我没有在 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/