2021-09-02 17:15:40 +08:00
|
|
|
import pickle
|
2015-01-28 20:35:27 +08:00
|
|
|
from datetime import datetime
|
2017-09-07 01:11:18 +08:00
|
|
|
from functools import partialmethod
|
2017-01-07 19:11:46 +08:00
|
|
|
from io import StringIO
|
2017-09-18 16:06:01 +08:00
|
|
|
from unittest import mock, skipIf
|
2010-09-19 22:04:34 +08:00
|
|
|
|
2015-09-26 16:43:12 +08:00
|
|
|
from django.core import serializers
|
2015-09-26 18:46:00 +08:00
|
|
|
from django.core.serializers import SerializerDoesNotExist
|
2021-09-02 17:15:40 +08:00
|
|
|
from django.core.serializers.base import PickleSerializer, ProgressBar
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.db import connection, transaction
|
2015-09-26 18:46:00 +08:00
|
|
|
from django.http import HttpResponse
|
2017-01-20 01:16:04 +08:00
|
|
|
from django.test import SimpleTestCase, override_settings, skipUnlessDBFeature
|
2020-01-30 17:28:32 +08:00
|
|
|
from django.test.utils import Approximate, ignore_warnings
|
|
|
|
from django.utils.deprecation import RemovedInDjango50Warning
|
2010-09-19 22:04:34 +08:00
|
|
|
|
2015-01-28 20:35:27 +08:00
|
|
|
from .models import (
|
2019-06-27 15:47:13 +08:00
|
|
|
Actor,
|
|
|
|
Article,
|
|
|
|
Author,
|
|
|
|
AuthorProfile,
|
|
|
|
BaseModel,
|
|
|
|
Category,
|
|
|
|
Child,
|
|
|
|
ComplexModel,
|
|
|
|
Movie,
|
|
|
|
Player,
|
|
|
|
ProxyBaseModel,
|
|
|
|
ProxyProxyBaseModel,
|
|
|
|
Score,
|
|
|
|
Team,
|
2015-01-28 20:35:27 +08:00
|
|
|
)
|
|
|
|
|
2010-09-19 22:04:34 +08:00
|
|
|
|
2013-10-14 21:14:17 +08:00
|
|
|
@override_settings(
|
2013-11-03 05:34:05 +08:00
|
|
|
SERIALIZATION_MODULES={
|
2013-10-27 09:27:42 +08:00
|
|
|
"json2": "django.core.serializers.json",
|
2013-10-14 21:14:17 +08:00
|
|
|
}
|
|
|
|
)
|
2015-04-18 05:38:20 +08:00
|
|
|
class SerializerRegistrationTests(SimpleTestCase):
|
2011-01-27 10:29:17 +08:00
|
|
|
def setUp(self):
|
|
|
|
self.old_serializers = serializers._serializers
|
|
|
|
serializers._serializers = {}
|
|
|
|
|
|
|
|
def tearDown(self):
|
|
|
|
serializers._serializers = self.old_serializers
|
|
|
|
|
|
|
|
def test_register(self):
|
|
|
|
"Registering a new serializer populates the full registry. Refs #14823"
|
|
|
|
serializers.register_serializer("json3", "django.core.serializers.json")
|
|
|
|
|
|
|
|
public_formats = serializers.get_public_serializer_formats()
|
|
|
|
self.assertIn("json3", public_formats)
|
|
|
|
self.assertIn("json2", public_formats)
|
|
|
|
self.assertIn("xml", public_formats)
|
|
|
|
|
|
|
|
def test_unregister(self):
|
|
|
|
"""
|
|
|
|
Unregistering a serializer doesn't cause the registry to be
|
|
|
|
repopulated.
|
2022-02-04 15:08:27 +08:00
|
|
|
"""
|
2011-01-27 10:29:17 +08:00
|
|
|
serializers.unregister_serializer("xml")
|
|
|
|
serializers.register_serializer("json3", "django.core.serializers.json")
|
|
|
|
|
|
|
|
public_formats = serializers.get_public_serializer_formats()
|
|
|
|
|
|
|
|
self.assertNotIn("xml", public_formats)
|
|
|
|
self.assertIn("json3", public_formats)
|
|
|
|
|
2015-09-26 18:46:00 +08:00
|
|
|
def test_unregister_unknown_serializer(self):
|
|
|
|
with self.assertRaises(SerializerDoesNotExist):
|
|
|
|
serializers.unregister_serializer("nonsense")
|
|
|
|
|
2011-01-27 10:29:17 +08:00
|
|
|
def test_builtin_serializers(self):
|
2019-08-05 23:47:50 +08:00
|
|
|
"Requesting a list of serializer formats populates the registry"
|
2011-01-27 10:29:17 +08:00
|
|
|
all_formats = set(serializers.get_serializer_formats())
|
|
|
|
public_formats = set(serializers.get_public_serializer_formats())
|
|
|
|
|
|
|
|
self.assertIn("xml", all_formats),
|
|
|
|
self.assertIn("xml", public_formats)
|
|
|
|
|
|
|
|
self.assertIn("json2", all_formats)
|
|
|
|
self.assertIn("json2", public_formats)
|
|
|
|
|
|
|
|
self.assertIn("python", all_formats)
|
|
|
|
self.assertNotIn("python", public_formats)
|
|
|
|
|
2015-09-26 18:46:00 +08:00
|
|
|
def test_get_unknown_serializer(self):
|
|
|
|
"""
|
|
|
|
#15889: get_serializer('nonsense') raises a SerializerDoesNotExist
|
|
|
|
"""
|
|
|
|
with self.assertRaises(SerializerDoesNotExist):
|
|
|
|
serializers.get_serializer("nonsense")
|
|
|
|
|
|
|
|
with self.assertRaises(KeyError):
|
|
|
|
serializers.get_serializer("nonsense")
|
|
|
|
|
|
|
|
# SerializerDoesNotExist is instantiated with the nonexistent format
|
2020-02-05 04:58:07 +08:00
|
|
|
with self.assertRaisesMessage(SerializerDoesNotExist, "nonsense"):
|
2015-09-26 18:46:00 +08:00
|
|
|
serializers.get_serializer("nonsense")
|
|
|
|
|
|
|
|
def test_get_unknown_deserializer(self):
|
|
|
|
with self.assertRaises(SerializerDoesNotExist):
|
|
|
|
serializers.get_deserializer("nonsense")
|
|
|
|
|
2013-11-03 05:34:05 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class SerializersTestBase:
|
2015-09-26 18:46:00 +08:00
|
|
|
serializer_name = None # Set by subclasses to the serialization format name
|
|
|
|
|
2018-11-24 10:24:25 +08:00
|
|
|
@classmethod
|
|
|
|
def setUpTestData(cls):
|
2010-09-19 22:04:34 +08:00
|
|
|
sports = Category.objects.create(name="Sports")
|
|
|
|
music = Category.objects.create(name="Music")
|
|
|
|
op_ed = Category.objects.create(name="Op-Ed")
|
|
|
|
|
2018-11-24 10:24:25 +08:00
|
|
|
cls.joe = Author.objects.create(name="Joe")
|
|
|
|
cls.jane = Author.objects.create(name="Jane")
|
2010-09-19 22:04:34 +08:00
|
|
|
|
2018-11-24 10:24:25 +08:00
|
|
|
cls.a1 = Article(
|
|
|
|
author=cls.jane,
|
2010-09-19 22:04:34 +08:00
|
|
|
headline="Poker has no place on ESPN",
|
|
|
|
pub_date=datetime(2006, 6, 16, 11, 00),
|
|
|
|
)
|
2018-11-24 10:24:25 +08:00
|
|
|
cls.a1.save()
|
|
|
|
cls.a1.categories.set([sports, op_ed])
|
2010-09-19 22:04:34 +08:00
|
|
|
|
2018-11-24 10:24:25 +08:00
|
|
|
cls.a2 = Article(
|
|
|
|
author=cls.joe,
|
2010-09-19 22:04:34 +08:00
|
|
|
headline="Time to reform copyright",
|
|
|
|
pub_date=datetime(2006, 6, 16, 13, 00, 11, 345),
|
|
|
|
)
|
2018-11-24 10:24:25 +08:00
|
|
|
cls.a2.save()
|
|
|
|
cls.a2.categories.set([music, op_ed])
|
2010-09-19 22:04:34 +08:00
|
|
|
|
|
|
|
def test_serialize(self):
|
2016-10-27 15:53:39 +08:00
|
|
|
"""Basic serialization works."""
|
2016-04-08 10:04:45 +08:00
|
|
|
serial_str = serializers.serialize(self.serializer_name, Article.objects.all())
|
2010-09-19 22:04:34 +08:00
|
|
|
self.assertTrue(self._validate_output(serial_str))
|
|
|
|
|
|
|
|
def test_serializer_roundtrip(self):
|
2016-10-27 15:53:39 +08:00
|
|
|
"""Serialized content can be deserialized."""
|
2016-04-08 10:04:45 +08:00
|
|
|
serial_str = serializers.serialize(self.serializer_name, Article.objects.all())
|
2010-09-19 22:04:34 +08:00
|
|
|
models = list(serializers.deserialize(self.serializer_name, serial_str))
|
|
|
|
self.assertEqual(len(models), 2)
|
|
|
|
|
2015-09-26 18:46:00 +08:00
|
|
|
def test_serialize_to_stream(self):
|
|
|
|
obj = ComplexModel(field1="first", field2="second", field3="third")
|
|
|
|
obj.save_base(raw=True)
|
|
|
|
|
|
|
|
# Serialize the test database to a stream
|
|
|
|
for stream in (StringIO(), HttpResponse()):
|
|
|
|
serializers.serialize(self.serializer_name, [obj], indent=2, stream=stream)
|
|
|
|
|
|
|
|
# Serialize normally for a comparison
|
|
|
|
string_data = serializers.serialize(self.serializer_name, [obj], indent=2)
|
|
|
|
|
2016-10-27 15:53:39 +08:00
|
|
|
# The two are the same
|
2015-09-26 18:46:00 +08:00
|
|
|
if isinstance(stream, StringIO):
|
|
|
|
self.assertEqual(string_data, stream.getvalue())
|
|
|
|
else:
|
2017-02-08 01:05:47 +08:00
|
|
|
self.assertEqual(string_data, stream.content.decode())
|
2015-09-26 18:46:00 +08:00
|
|
|
|
|
|
|
def test_serialize_specific_fields(self):
|
|
|
|
obj = ComplexModel(field1="first", field2="second", field3="third")
|
|
|
|
obj.save_base(raw=True)
|
|
|
|
|
|
|
|
# Serialize then deserialize the test database
|
|
|
|
serialized_data = serializers.serialize(
|
|
|
|
self.serializer_name, [obj], indent=2, fields=("field1", "field3")
|
|
|
|
)
|
|
|
|
result = next(serializers.deserialize(self.serializer_name, serialized_data))
|
|
|
|
|
2016-10-27 15:53:39 +08:00
|
|
|
# The deserialized object contains data in only the serialized fields.
|
2015-09-26 18:46:00 +08:00
|
|
|
self.assertEqual(result.object.field1, "first")
|
|
|
|
self.assertEqual(result.object.field2, "")
|
|
|
|
self.assertEqual(result.object.field3, "third")
|
|
|
|
|
2010-09-19 22:04:34 +08:00
|
|
|
def test_altering_serialized_output(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
The ability to create new objects by modifying serialized content.
|
2010-09-19 22:04:34 +08:00
|
|
|
"""
|
2012-08-15 01:48:38 +08:00
|
|
|
old_headline = "Poker has no place on ESPN"
|
|
|
|
new_headline = "Poker has no place on television"
|
2016-04-08 10:04:45 +08:00
|
|
|
serial_str = serializers.serialize(self.serializer_name, Article.objects.all())
|
2010-09-19 22:04:34 +08:00
|
|
|
serial_str = serial_str.replace(old_headline, new_headline)
|
|
|
|
models = list(serializers.deserialize(self.serializer_name, serial_str))
|
|
|
|
|
|
|
|
# Prior to saving, old headline is in place
|
|
|
|
self.assertTrue(Article.objects.filter(headline=old_headline))
|
|
|
|
self.assertFalse(Article.objects.filter(headline=new_headline))
|
|
|
|
|
|
|
|
for model in models:
|
|
|
|
model.save()
|
|
|
|
|
|
|
|
# After saving, new headline is in place
|
|
|
|
self.assertTrue(Article.objects.filter(headline=new_headline))
|
|
|
|
self.assertFalse(Article.objects.filter(headline=old_headline))
|
|
|
|
|
|
|
|
def test_one_to_one_as_pk(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
If you use your own primary key field (such as a OneToOneField), it
|
|
|
|
doesn't appear in the serialized field list - it replaces the pk
|
|
|
|
identifier.
|
2010-09-19 22:04:34 +08:00
|
|
|
"""
|
2016-04-08 10:04:45 +08:00
|
|
|
AuthorProfile.objects.create(
|
|
|
|
author=self.joe, date_of_birth=datetime(1970, 1, 1)
|
2022-02-04 03:24:19 +08:00
|
|
|
)
|
2016-04-08 10:04:45 +08:00
|
|
|
serial_str = serializers.serialize(
|
|
|
|
self.serializer_name, AuthorProfile.objects.all()
|
2022-02-04 03:24:19 +08:00
|
|
|
)
|
2010-09-19 22:04:34 +08:00
|
|
|
self.assertFalse(self._get_field_values(serial_str, "author"))
|
|
|
|
|
|
|
|
for obj in serializers.deserialize(self.serializer_name, serial_str):
|
2017-11-29 14:06:45 +08:00
|
|
|
self.assertEqual(obj.object.pk, self.joe.pk)
|
2010-09-19 22:04:34 +08:00
|
|
|
|
|
|
|
def test_serialize_field_subset(self):
|
2016-10-27 15:53:39 +08:00
|
|
|
"""Output can be restricted to a subset of fields"""
|
2013-10-27 03:15:03 +08:00
|
|
|
valid_fields = ("headline", "pub_date")
|
2010-09-19 22:04:34 +08:00
|
|
|
invalid_fields = ("author", "categories")
|
2016-04-08 10:04:45 +08:00
|
|
|
serial_str = serializers.serialize(
|
|
|
|
self.serializer_name, Article.objects.all(), fields=valid_fields
|
|
|
|
)
|
2010-09-19 22:04:34 +08:00
|
|
|
for field_name in invalid_fields:
|
|
|
|
self.assertFalse(self._get_field_values(serial_str, field_name))
|
|
|
|
|
|
|
|
for field_name in valid_fields:
|
|
|
|
self.assertTrue(self._get_field_values(serial_str, field_name))
|
|
|
|
|
2020-04-24 04:14:32 +08:00
|
|
|
def test_serialize_unicode_roundtrip(self):
|
2016-10-27 15:53:39 +08:00
|
|
|
"""Unicode makes the roundtrip intact"""
|
2012-06-08 00:08:47 +08:00
|
|
|
actor_name = "Za\u017c\u00f3\u0142\u0107"
|
|
|
|
movie_title = "G\u0119\u015bl\u0105 ja\u017a\u0144"
|
2010-09-19 22:04:34 +08:00
|
|
|
ac = Actor(name=actor_name)
|
|
|
|
mv = Movie(title=movie_title, actor=ac)
|
|
|
|
ac.save()
|
|
|
|
mv.save()
|
|
|
|
|
|
|
|
serial_str = serializers.serialize(self.serializer_name, [mv])
|
|
|
|
self.assertEqual(self._get_field_values(serial_str, "title")[0], movie_title)
|
|
|
|
self.assertEqual(self._get_field_values(serial_str, "actor")[0], actor_name)
|
|
|
|
|
|
|
|
obj_list = list(serializers.deserialize(self.serializer_name, serial_str))
|
|
|
|
mv_obj = obj_list[0].object
|
|
|
|
self.assertEqual(mv_obj.title, movie_title)
|
|
|
|
|
2020-04-24 04:14:32 +08:00
|
|
|
def test_unicode_serialization(self):
|
|
|
|
unicode_name = "יוניקוד"
|
|
|
|
data = serializers.serialize(self.serializer_name, [Author(name=unicode_name)])
|
|
|
|
self.assertIn(unicode_name, data)
|
|
|
|
objs = list(serializers.deserialize(self.serializer_name, data))
|
|
|
|
self.assertEqual(objs[0].object.name, unicode_name)
|
|
|
|
|
2015-07-22 05:24:32 +08:00
|
|
|
def test_serialize_progressbar(self):
|
|
|
|
fake_stdout = StringIO()
|
|
|
|
serializers.serialize(
|
|
|
|
self.serializer_name,
|
|
|
|
Article.objects.all(),
|
|
|
|
progress_output=fake_stdout,
|
|
|
|
object_count=Article.objects.count(),
|
|
|
|
)
|
|
|
|
self.assertTrue(
|
|
|
|
fake_stdout.getvalue().endswith(
|
|
|
|
"[" + "." * ProgressBar.progress_width + "]\n"
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2012-02-05 02:27:07 +08:00
|
|
|
def test_serialize_superfluous_queries(self):
|
|
|
|
"""Ensure no superfluous queries are made when serializing ForeignKeys
|
|
|
|
|
|
|
|
#17602
|
|
|
|
"""
|
|
|
|
ac = Actor(name="Actor name")
|
|
|
|
ac.save()
|
|
|
|
mv = Movie(title="Movie title", actor_id=ac.pk)
|
|
|
|
mv.save()
|
|
|
|
|
|
|
|
with self.assertNumQueries(0):
|
2013-10-19 20:31:38 +08:00
|
|
|
serializers.serialize(self.serializer_name, [mv])
|
2012-02-05 02:27:07 +08:00
|
|
|
|
2020-05-24 20:14:49 +08:00
|
|
|
def test_serialize_prefetch_related_m2m(self):
|
|
|
|
# One query for the Article table and one for each prefetched m2m
|
|
|
|
# field.
|
|
|
|
with self.assertNumQueries(3):
|
|
|
|
serializers.serialize(
|
|
|
|
self.serializer_name,
|
2022-02-22 17:29:38 +08:00
|
|
|
Article.objects.prefetch_related("categories", "meta_data"),
|
2020-05-24 20:14:49 +08:00
|
|
|
)
|
|
|
|
# One query for the Article table, and two m2m queries for each
|
|
|
|
# article.
|
|
|
|
with self.assertNumQueries(5):
|
|
|
|
serializers.serialize(self.serializer_name, Article.objects.all())
|
|
|
|
|
2010-09-19 22:04:34 +08:00
|
|
|
def test_serialize_with_null_pk(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
Serialized data with no primary key results
|
2010-09-19 22:04:34 +08:00
|
|
|
in a model instance with no id
|
|
|
|
"""
|
|
|
|
category = Category(name="Reference")
|
|
|
|
serial_str = serializers.serialize(self.serializer_name, [category])
|
|
|
|
pk_value = self._get_pk_values(serial_str)[0]
|
|
|
|
self.assertFalse(pk_value)
|
|
|
|
|
2016-04-08 10:04:45 +08:00
|
|
|
cat_obj = list(serializers.deserialize(self.serializer_name, serial_str))[
|
2022-02-04 03:24:19 +08:00
|
|
|
0
|
2016-04-08 10:04:45 +08:00
|
|
|
].object
|
2016-06-17 02:19:18 +08:00
|
|
|
self.assertIsNone(cat_obj.id)
|
2010-09-19 22:04:34 +08:00
|
|
|
|
|
|
|
def test_float_serialization(self):
|
2016-10-27 15:53:39 +08:00
|
|
|
"""Float values serialize and deserialize intact"""
|
2010-09-19 22:04:34 +08:00
|
|
|
sc = Score(score=3.4)
|
|
|
|
sc.save()
|
|
|
|
serial_str = serializers.serialize(self.serializer_name, [sc])
|
2016-04-08 10:04:45 +08:00
|
|
|
deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str))
|
2010-09-19 22:04:34 +08:00
|
|
|
self.assertEqual(deserial_objs[0].object.score, Approximate(3.4, places=1))
|
|
|
|
|
2015-07-03 01:17:48 +08:00
|
|
|
def test_deferred_field_serialization(self):
|
|
|
|
author = Author.objects.create(name="Victor Hugo")
|
|
|
|
author = Author.objects.defer("name").get(pk=author.pk)
|
|
|
|
serial_str = serializers.serialize(self.serializer_name, [author])
|
|
|
|
deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str))
|
2016-11-17 23:23:17 +08:00
|
|
|
self.assertIsInstance(deserial_objs[0].object, Author)
|
2015-07-03 01:17:48 +08:00
|
|
|
|
2010-09-19 22:04:34 +08:00
|
|
|
def test_custom_field_serialization(self):
|
2016-10-27 15:53:39 +08:00
|
|
|
"""Custom fields serialize and deserialize intact"""
|
2010-09-19 22:04:34 +08:00
|
|
|
team_str = "Spartak Moskva"
|
|
|
|
player = Player()
|
|
|
|
player.name = "Soslan Djanaev"
|
|
|
|
player.rank = 1
|
|
|
|
player.team = Team(team_str)
|
|
|
|
player.save()
|
2016-04-08 10:04:45 +08:00
|
|
|
serial_str = serializers.serialize(self.serializer_name, Player.objects.all())
|
2010-09-19 22:04:34 +08:00
|
|
|
team = self._get_field_values(serial_str, "team")
|
|
|
|
self.assertTrue(team)
|
|
|
|
self.assertEqual(team[0], team_str)
|
|
|
|
|
|
|
|
deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str))
|
2016-04-08 10:04:45 +08:00
|
|
|
self.assertEqual(
|
|
|
|
deserial_objs[0].object.team.to_string(), player.team.to_string()
|
2022-02-04 03:24:19 +08:00
|
|
|
)
|
2010-09-19 22:04:34 +08:00
|
|
|
|
|
|
|
def test_pre_1000ad_date(self):
|
2016-10-27 15:53:39 +08:00
|
|
|
"""Year values before 1000AD are properly formatted"""
|
2010-09-19 22:04:34 +08:00
|
|
|
# Regression for #12524 -- dates before 1000AD get prefixed
|
|
|
|
# 0's on the year
|
|
|
|
a = Article.objects.create(
|
2013-11-03 05:34:05 +08:00
|
|
|
author=self.jane,
|
|
|
|
headline="Nobody remembers the early years",
|
|
|
|
pub_date=datetime(1, 2, 3, 4, 5, 6),
|
|
|
|
)
|
2010-09-19 22:04:34 +08:00
|
|
|
|
|
|
|
serial_str = serializers.serialize(self.serializer_name, [a])
|
|
|
|
date_values = self._get_field_values(serial_str, "pub_date")
|
2011-11-18 21:01:06 +08:00
|
|
|
self.assertEqual(date_values[0].replace("T", " "), "0001-02-03 04:05:06")
|
2010-09-19 22:04:34 +08:00
|
|
|
|
|
|
|
def test_pkless_serialized_strings(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
Serialized strings without PKs can be turned into models
|
2010-09-19 22:04:34 +08:00
|
|
|
"""
|
2016-04-08 10:04:45 +08:00
|
|
|
deserial_objs = list(
|
|
|
|
serializers.deserialize(self.serializer_name, self.pkless_str)
|
2022-02-04 03:24:19 +08:00
|
|
|
)
|
2010-09-19 22:04:34 +08:00
|
|
|
for obj in deserial_objs:
|
|
|
|
self.assertFalse(obj.object.id)
|
|
|
|
obj.save()
|
2022-02-22 17:29:38 +08:00
|
|
|
self.assertEqual(Category.objects.count(), 5)
|
2010-09-19 22:04:34 +08:00
|
|
|
|
2015-04-02 03:42:09 +08:00
|
|
|
def test_deterministic_mapping_ordering(self):
|
|
|
|
"""Mapping such as fields should be deterministically ordered. (#24558)"""
|
|
|
|
output = serializers.serialize(self.serializer_name, [self.a1], indent=2)
|
|
|
|
categories = self.a1.categories.values_list("pk", flat=True)
|
|
|
|
self.assertEqual(
|
|
|
|
output,
|
|
|
|
self.mapping_ordering_str
|
|
|
|
% {
|
|
|
|
"article_pk": self.a1.pk,
|
|
|
|
"author_pk": self.a1.author_id,
|
|
|
|
"first_category_pk": categories[0],
|
|
|
|
"second_category_pk": categories[1],
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
2015-06-05 22:58:36 +08:00
|
|
|
def test_deserialize_force_insert(self):
|
2016-10-27 15:53:39 +08:00
|
|
|
"""Deserialized content can be saved with force_insert as a parameter."""
|
2015-06-05 22:58:36 +08:00
|
|
|
serial_str = serializers.serialize(self.serializer_name, [self.a1])
|
|
|
|
deserial_obj = list(serializers.deserialize(self.serializer_name, serial_str))[
|
2022-02-04 03:24:19 +08:00
|
|
|
0
|
2015-06-05 22:58:36 +08:00
|
|
|
]
|
|
|
|
with mock.patch("django.db.models.Model") as mock_model:
|
|
|
|
deserial_obj.save(force_insert=False)
|
|
|
|
mock_model.save_base.assert_called_with(
|
|
|
|
deserial_obj.object, raw=True, using=None, force_insert=False
|
|
|
|
)
|
|
|
|
|
2015-09-26 18:46:00 +08:00
|
|
|
@skipUnlessDBFeature("can_defer_constraint_checks")
|
|
|
|
def test_serialize_proxy_model(self):
|
|
|
|
BaseModel.objects.create(parent_data=1)
|
|
|
|
base_objects = BaseModel.objects.all()
|
|
|
|
proxy_objects = ProxyBaseModel.objects.all()
|
|
|
|
proxy_proxy_objects = ProxyProxyBaseModel.objects.all()
|
|
|
|
base_data = serializers.serialize("json", base_objects)
|
|
|
|
proxy_data = serializers.serialize("json", proxy_objects)
|
|
|
|
proxy_proxy_data = serializers.serialize("json", proxy_proxy_objects)
|
|
|
|
self.assertEqual(base_data, proxy_data.replace("proxy", ""))
|
|
|
|
self.assertEqual(base_data, proxy_proxy_data.replace("proxy", ""))
|
|
|
|
|
2019-06-27 17:32:56 +08:00
|
|
|
def test_serialize_inherited_fields(self):
|
2019-06-27 15:47:13 +08:00
|
|
|
child_1 = Child.objects.create(parent_data="a", child_data="b")
|
|
|
|
child_2 = Child.objects.create(parent_data="c", child_data="d")
|
|
|
|
child_1.parent_m2m.add(child_2)
|
|
|
|
child_data = serializers.serialize(self.serializer_name, [child_1, child_2])
|
|
|
|
self.assertEqual(self._get_field_values(child_data, "parent_m2m"), [])
|
2019-06-27 17:32:56 +08:00
|
|
|
self.assertEqual(self._get_field_values(child_data, "parent_data"), [])
|
2019-06-27 15:47:13 +08:00
|
|
|
|
2022-09-03 21:53:58 +08:00
|
|
|
def test_serialize_only_pk(self):
|
|
|
|
with self.assertNumQueries(5) as ctx:
|
|
|
|
serializers.serialize(
|
|
|
|
self.serializer_name,
|
|
|
|
Article.objects.all(),
|
|
|
|
use_natural_foreign_keys=False,
|
|
|
|
)
|
|
|
|
|
|
|
|
categories_sql = ctx[1]["sql"]
|
|
|
|
self.assertNotIn(connection.ops.quote_name("meta_data_id"), categories_sql)
|
|
|
|
meta_data_sql = ctx[2]["sql"]
|
|
|
|
self.assertNotIn(connection.ops.quote_name("kind"), meta_data_sql)
|
|
|
|
|
|
|
|
def test_serialize_no_only_pk_with_natural_keys(self):
|
|
|
|
with self.assertNumQueries(5) as ctx:
|
|
|
|
serializers.serialize(
|
|
|
|
self.serializer_name,
|
|
|
|
Article.objects.all(),
|
|
|
|
use_natural_foreign_keys=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
categories_sql = ctx[1]["sql"]
|
|
|
|
self.assertNotIn(connection.ops.quote_name("meta_data_id"), categories_sql)
|
|
|
|
# CategoryMetaData has natural_key().
|
|
|
|
meta_data_sql = ctx[2]["sql"]
|
|
|
|
self.assertIn(connection.ops.quote_name("kind"), meta_data_sql)
|
|
|
|
|
2010-09-19 22:04:34 +08:00
|
|
|
|
2016-06-08 09:22:30 +08:00
|
|
|
class SerializerAPITests(SimpleTestCase):
|
|
|
|
def test_stream_class(self):
|
2017-01-19 15:39:46 +08:00
|
|
|
class File:
|
2016-06-08 09:22:30 +08:00
|
|
|
def __init__(self):
|
|
|
|
self.lines = []
|
|
|
|
|
|
|
|
def write(self, line):
|
|
|
|
self.lines.append(line)
|
|
|
|
|
|
|
|
def getvalue(self):
|
|
|
|
return "".join(self.lines)
|
|
|
|
|
|
|
|
class Serializer(serializers.json.Serializer):
|
|
|
|
stream_class = File
|
|
|
|
|
|
|
|
serializer = Serializer()
|
|
|
|
data = serializer.serialize([Score(id=1, score=3.4)])
|
|
|
|
self.assertIs(serializer.stream_class, File)
|
|
|
|
self.assertIsInstance(serializer.stream, File)
|
|
|
|
self.assertEqual(
|
|
|
|
data, '[{"model": "serializers.score", "pk": 1, "fields": {"score": 3.4}}]'
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class SerializersTransactionTestBase:
|
2013-06-04 14:09:29 +08:00
|
|
|
available_apps = ["serializers"]
|
|
|
|
|
2014-06-11 23:45:18 +08:00
|
|
|
@skipUnlessDBFeature("supports_forward_references")
|
2010-09-19 22:04:34 +08:00
|
|
|
def test_forward_refs(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
Objects ids can be referenced before they are
|
2010-09-19 22:04:34 +08:00
|
|
|
defined in the serialization data.
|
|
|
|
"""
|
2014-03-21 21:21:43 +08:00
|
|
|
# The deserialization process needs to run in a transaction in order
|
|
|
|
# to test forward reference handling.
|
|
|
|
with transaction.atomic():
|
|
|
|
objs = serializers.deserialize(self.serializer_name, self.fwd_ref_str)
|
|
|
|
with connection.constraint_checks_disabled():
|
|
|
|
for obj in objs:
|
|
|
|
obj.save()
|
2010-09-19 22:04:34 +08:00
|
|
|
|
|
|
|
for model_cls in (Category, Author, Article):
|
2022-02-22 17:29:38 +08:00
|
|
|
self.assertEqual(model_cls.objects.count(), 1)
|
2010-09-19 22:04:34 +08:00
|
|
|
art_obj = Article.objects.all()[0]
|
2022-02-22 17:29:38 +08:00
|
|
|
self.assertEqual(art_obj.categories.count(), 1)
|
2010-09-19 22:04:34 +08:00
|
|
|
self.assertEqual(art_obj.author.name, "Agnes")
|
2015-09-26 17:53:20 +08:00
|
|
|
|
|
|
|
|
2021-09-02 17:15:40 +08:00
|
|
|
class PickleSerializerTests(SimpleTestCase):
|
2020-01-30 17:28:32 +08:00
|
|
|
@ignore_warnings(category=RemovedInDjango50Warning)
|
2021-09-02 17:15:40 +08:00
|
|
|
def test_serializer_protocol(self):
|
|
|
|
serializer = PickleSerializer(protocol=3)
|
|
|
|
self.assertEqual(serializer.protocol, 3)
|
|
|
|
# If protocol is not provided, it defaults to pickle.HIGHEST_PROTOCOL
|
|
|
|
serializer = PickleSerializer()
|
|
|
|
self.assertEqual(serializer.protocol, pickle.HIGHEST_PROTOCOL)
|
|
|
|
|
2020-01-30 17:28:32 +08:00
|
|
|
@ignore_warnings(category=RemovedInDjango50Warning)
|
2021-09-02 17:15:40 +08:00
|
|
|
def test_serializer_loads_dumps(self):
|
|
|
|
serializer = PickleSerializer()
|
|
|
|
test_data = "test data"
|
|
|
|
dump = serializer.dumps(test_data)
|
|
|
|
self.assertEqual(serializer.loads(dump), test_data)
|
|
|
|
|
2020-01-30 17:28:32 +08:00
|
|
|
def test_serializer_warning(self):
|
|
|
|
msg = (
|
|
|
|
"PickleSerializer is deprecated due to its security risk. Use "
|
|
|
|
"JSONSerializer instead."
|
|
|
|
)
|
|
|
|
with self.assertRaisesMessage(RemovedInDjango50Warning, msg):
|
|
|
|
PickleSerializer()
|
|
|
|
|
2021-09-02 17:15:40 +08:00
|
|
|
|
2017-09-18 16:06:01 +08:00
|
|
|
def register_tests(test_class, method_name, test_func, exclude=()):
|
2015-09-26 17:53:20 +08:00
|
|
|
"""
|
|
|
|
Dynamically create serializer tests to ensure that all registered
|
|
|
|
serializers are automatically tested.
|
|
|
|
"""
|
2017-09-18 16:06:01 +08:00
|
|
|
for format_ in serializers.get_serializer_formats():
|
|
|
|
if format_ == "geojson" or format_ in exclude:
|
|
|
|
continue
|
|
|
|
decorated_func = skipIf(
|
|
|
|
isinstance(serializers.get_serializer(format_), serializers.BadSerializer),
|
|
|
|
"The Python library for the %s serializer is not installed." % format_,
|
|
|
|
)(test_func)
|
|
|
|
setattr(
|
|
|
|
test_class, method_name % format_, partialmethod(decorated_func, format_)
|
2022-02-04 03:24:19 +08:00
|
|
|
)
|