I have a custom model in django with overriden to_python() and get_db_prep_save() methods. I discovered a bug: when dumping and reloading data it was inconsistent. The bug is fixed but I want to unittest it with simple json string.
My question is: how can I call loaddata / dumpdata inside unittest.
I want to to create following scenarios:
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
I know there is fixture=[]
field which can be used in django unittests, it could solve loading fixtures scenarios. But if someone could point me to some interface to load or dump fixture data on demand it would be great.
Thanks to @YugandharChaudhari comment I came up with solution using 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'])