【发布时间】:2016-05-16 20:48:07
【问题描述】:
我正在处理一个 django 网络项目,但我似乎找不到任何答案。 我正在尝试测试一个像这样简单的视图:
def list(request):
return JsonResponse( {"foo": "bar"} )
它似乎运行良好。如果我在浏览器上打开该网站并检查页面信息,它会显示“类型:应用程序/json”。
但是,当我在 travis ci 上运行以下测试时:
def setUpTestData(cls):
cls.client = Client()
#A few lines of setting up test-data
def test_content_type(self):
response = self.client.get('/api/list')
self.assertEqual(response['content-type'], 'application/json')
我得到以下失败:
FAIL: test_content_type (researchlibrary.api.tests.test_list.ListTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/travis/build/FUB-HCC/ACE-Research-Library/researchlibrary/api/tests/test_list.py", line 25, in test_content_type
self.assertEqual(response['content-type'], 'application/json')
AssertionError: 'text/html' != 'application/json'
- text/html
+ application/json
网址都很好。测试收到正确的页面,只是类型似乎是 text/html 而不是 application/json,我不知道为什么会这样。
有人知道为什么会这样吗?
编辑:将 self.client.get('/api/list') 更改为 self.client.get('/api/list/') 解决了问题。
【问题讨论】:
-
我认为您应该检查响应的内容。您可能会收到错误页面,而不是通常的响应。
-
@LudwikTrammer 你是对的。键入地址
localhost/api/list会返回正确的响应,但不知何故,测试似乎并非如此。我尝试将其更改为self.client.get('/api/list/'),这确实起到了作用。谢谢 :D 我现在觉得有点傻^^ -
@LudwikTrammer 您应该创建它作为答案。
-
@cwallenpoole 这只是一个猜测,我什至不正确,尽管 OP 声称 ;) 原因不是使用 text/html 发送的错误页面,而是 HTTP 重定向。
标签: python json django travis-ci jsonresponse