首页 > 解决方案 > 在 django unittest 中从/向 json 字符串加载/转储夹具

问题描述

我在 django 中有一个自定义模型,其中覆盖了 to_python() 和 get_db_prep_save() 方法。我发现了一个错误:转储和重新加载数据时不一致。该错误已修复,但我想使用简单的 json 字符串对其进行单元测试。

我的问题是:如何在 unittest 中调用 loaddata / dumpdata。

我想创建以下场景:

from django.test import TestCase
class CustomModelTest(TestCase):
    def test_load_fixture(self):
        mydata = '[{"model": "some_app.custommodel", "pk": 1, "fields": {"custom_field": "some correct value"}}]'
        django.some_interface_to_load_fixture.loaddata(mydata) // data could be as json string, file, stream
        make some assertions on database model custommodel

    def test_dump_fixture(self):
        mymodel = create model object with some data
        result = django.some_interface_to_dump_fixture.dumpdata()
        make some assertions on result

我知道有fixture=[]可以在 django 单元测试中使用的字段,它可以解决加载固定装置的场景。但是,如果有人可以向我指出一些接口来按需加载或转储夹具数据,那就太好了。

标签: djangodjango-unittestdjango-fixtures

解决方案


感谢@YugandharChaudhari 的评论,我想出了使用django.core.serializers的解决方案:

import json
from django.core import serializers
from django.test import TestCase
from some_app.models import CustomModel

class CustomModelTest(TestCase):
    def test_deserializing(self):
        test_data = [
            {"model": "some_app.custommodel",
             "pk": 1,
             "fields":
                 {
                     "custom_field": "some correct value"}
             }
        ]
        result = list(serializers.deserialize('json', json.dumps(test_data)))
        self.assertEqual(result[0].object.custom_field, 'some data after deserialization')

    def test_serializing(self):
        custom_model_obj = CustomModel(id=1, custom_field='some data')
        result_json = json.loads(serializers.serialize('json', [custom_model_obj]))
        self.assertEqual('some data after serialization', result_json[0]['fields']['custom_field'])

推荐阅读