我正在使用Python 3.4和Django 1.7.我的视野是JsonResponse.

def add_item_to_collection(request):
    #(...)
    return JsonResponse({'status':'success'})

我想使用单元测试验证该视图是否返回正确的响应:

class AddItemToCollectionTest(TestCase):

    def test_success_when_not_added_before(self):
        response = self.client.post('/add-item-to-collection')
        self.assertEqual(response.status_code, 200)
        self.assertJSONEqual(response.content, {'status': 'success'})

然而,assertJSONEqual()行引发了一个例外:

Error
Traceback (most recent call last):
  File "E:\Projects\collecthub\app\collecthub\collecting\tests.py", line 148, in test_success_when_added_before
    self.assertJSONEqual(response.content, {'status': 'OK'})
  File "E:\Projects\collecthub\venv\lib\site-packages\django\test\testcases.py", line 675, in assertJSONEqual
    data = json.loads(raw)
  File "C:\Python34\Lib\json\__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'

当响应包含JSON时,判断响应内容的正确方法是什么?为什么当我try 将原始值与assertJSONEqual()中的dict进行比较时会出现类型错误?

推荐答案

看起来您正在使用Python 3,所以在将response.content传递给self.assertJSONEqual之前,需要将其转换为UTF-8编码字符串:

class AddItemToCollectionTest(TestCase):

    def test_success_when_not_added_before(self):
        response = self.client.post('/add-item-to-collection')
        self.assertEqual(response.status_code, 200)
        self.assertJSONEqual(
            str(response.content, encoding='utf8'),
            {'status': 'success'}
        )

如果希望同时支持Python 2.7和Python 3,请使用django ships with提供的six兼容性库:

from __future__ import unicode_literals
from django.utils import six

class AddItemToCollectionTest(TestCase):

    def test_success_when_not_added_before(self):
        response = self.client.post('/add-item-to-collection')
        self.assertEqual(response.status_code, 200)

        response_content = response.content
        if six.PY3:
            response_content = str(response_content, encoding='utf8')

        self.assertJSONEqual(
            response_content,
            {'status': 'success'}
        )

Python-3.x相关问答推荐

如何翻转以列形式给出的日期间隔并提取多个重叠时段内每小时的音量?

根据其他数据框架的列顺序从数据框架中进行 Select

按小时和日期对Pandas 数据帧进行分组

将字符串转换为python日期时间时出错

ValueError at /register/ 视图authenticate.views.register_user 未返回HttpResponse 对象.它返回 None 相反

移动所有列的数据帧值以使其单调递增

切片的Python复杂性与元组的星号相结合

来自嵌套字典的完整地址

使用gekko python的混合整数非线性规划

这种类型提示有什么作用?

有效地缩短列表,直到第一次和最后一次出现不同于 None 的值

命名元组内命名元组的 Python 语法

python total_ordering:为什么使用 __lt__ 和 __eq__ 而不是 __le__?

Python 异步调试示例

sys.stdin.readline() 和 input():读取输入行时哪个更快,为什么?

在计算之前删除包含某些值的组合

将 args、kwargs 传递给 run_in_executor

接收导入错误:没有名为 *** 的模块,但有 __init__.py

类方法和实例方法同名

为什么某些代码在 Python2 中是确定性的,而在 Python 3 中是非确定性的?