Moved more serializers_regress to serializers tests

This commit is contained in:
Claude Paroz 2015-09-26 12:46:00 +02:00
parent d59d3caf32
commit ddd6a530e3
4 changed files with 99 additions and 94 deletions

View File

@ -159,6 +159,26 @@ class Player(models.Model):
return '%s (%d) playing for %s' % (self.name, self.rank, self.team.to_string())
class BaseModel(models.Model):
parent_data = models.IntegerField()
class ProxyBaseModel(BaseModel):
class Meta:
proxy = True
class ProxyProxyBaseModel(ProxyBaseModel):
class Meta:
proxy = True
class ComplexModel(models.Model):
field1 = models.CharField(max_length=10)
field2 = models.CharField(max_length=10)
field3 = models.CharField(max_length=10)
# ******** Models for test_natural.py ***********
class NaturalKeyAnchorManager(models.Manager):

View File

@ -4,8 +4,10 @@ from __future__ import unicode_literals
from datetime import datetime
from django.core import serializers
from django.core.serializers import SerializerDoesNotExist
from django.core.serializers.base import ProgressBar
from django.db import connection, transaction
from django.http import HttpResponse
from django.test import (
SimpleTestCase, mock, override_settings, skipUnlessDBFeature,
)
@ -14,8 +16,8 @@ from django.utils.functional import curry
from django.utils.six import StringIO
from .models import (
Actor, Article, Author, AuthorProfile, Category, Movie, Player, Score,
Team,
Actor, Article, Author, AuthorProfile, BaseModel, Category, ComplexModel,
Movie, Player, ProxyBaseModel, ProxyProxyBaseModel, Score, Team,
)
@ -51,6 +53,10 @@ class SerializerRegistrationTests(SimpleTestCase):
self.assertNotIn('xml', public_formats)
self.assertIn('json3', public_formats)
def test_unregister_unknown_serializer(self):
with self.assertRaises(SerializerDoesNotExist):
serializers.unregister_serializer("nonsense")
def test_builtin_serializers(self):
"Requesting a list of serializer formats popuates the registry"
all_formats = set(serializers.get_serializer_formats())
@ -65,8 +71,29 @@ class SerializerRegistrationTests(SimpleTestCase):
self.assertIn('python', all_formats)
self.assertNotIn('python', public_formats)
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
with self.assertRaises(SerializerDoesNotExist) as cm:
serializers.get_serializer("nonsense")
self.assertEqual(cm.exception.args, ("nonsense",))
def test_get_unknown_deserializer(self):
with self.assertRaises(SerializerDoesNotExist):
serializers.get_deserializer("nonsense")
class SerializersTestBase(object):
serializer_name = None # Set by subclasses to the serialization format name
@staticmethod
def _comparison_value(value):
return value
@ -108,6 +135,38 @@ class SerializersTestBase(object):
models = list(serializers.deserialize(self.serializer_name, serial_str))
self.assertEqual(len(models), 2)
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)
# Check that the two are the same
if isinstance(stream, StringIO):
self.assertEqual(string_data, stream.getvalue())
else:
self.assertEqual(string_data, stream.content.decode('utf-8'))
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))
# Check that the deserialized object contains data in only the serialized fields.
self.assertEqual(result.object.field1, 'first')
self.assertEqual(result.object.field2, '')
self.assertEqual(result.object.field3, 'third')
def test_altering_serialized_output(self):
"""
Tests the ability to create new objects by
@ -294,6 +353,18 @@ class SerializersTestBase(object):
deserial_obj.save(force_insert=False)
mock_model.save_base.assert_called_with(deserial_obj.object, raw=True, using=None, force_insert=False)
@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', ''))
class SerializersTransactionTestBase(object):

View File

@ -261,11 +261,6 @@ class FKToUUID(models.Model):
data = models.ForeignKey(UUIDData, models.CASCADE)
class ComplexModel(models.Model):
field1 = models.CharField(max_length=10)
field2 = models.CharField(max_length=10)
field3 = models.CharField(max_length=10)
# Tests for handling fields with pre_save functions, or
# models with save functions that modify data
@ -314,16 +309,6 @@ class ExplicitInheritBaseModel(BaseModel):
child_data = models.IntegerField()
class ProxyBaseModel(BaseModel):
class Meta:
proxy = True
class ProxyProxyBaseModel(ProxyBaseModel):
class Meta:
proxy = True
class LengthModel(models.Model):
data = models.IntegerField()

View File

@ -13,16 +13,15 @@ import decimal
import uuid
from django.core import serializers
from django.core.serializers import SerializerDoesNotExist
from django.db import connection, models
from django.http import HttpResponse
from django.test import TestCase, skipUnlessDBFeature
from django.test import TestCase
from django.utils import six
from django.utils.functional import curry
from .models import (
Anchor, AutoNowDateTimeData, BaseModel, BigIntegerData, BinaryData,
BooleanData, BooleanPKData, CharData, CharPKData, ComplexModel, DateData,
Anchor, AutoNowDateTimeData, BigIntegerData, BinaryData,
BooleanData, BooleanPKData, CharData, CharPKData, DateData,
DateTimeData, DecimalData, DecimalPKData, EmailData, EmailPKData,
ExplicitInheritBaseModel, FileData, FilePathData, FilePathPKData, FKData,
FKDataToField, FKDataToO2O, FKSelfData, FKToUUID,
@ -31,9 +30,8 @@ from .models import (
IntegerData, IntegerPKData, Intermediate, LengthModel, M2MData,
M2MIntermediateData, M2MSelfData, ModifyingSaveData,
NullBooleanData, O2OData, PositiveIntegerData, PositiveIntegerPKData,
PositiveSmallIntegerData, PositiveSmallIntegerPKData, ProxyBaseModel,
ProxyProxyBaseModel, SlugData, SlugPKData, SmallData, SmallPKData, Tag,
TextData, TimeData, UniqueAnchor, UUIDData,
PositiveSmallIntegerData, PositiveSmallIntegerPKData, SlugData, SlugPKData,
SmallData, SmallPKData, Tag, TextData, TimeData, UniqueAnchor, UUIDData,
)
# A set of functions that can be used to recreate
@ -387,42 +385,8 @@ if connection.features.allows_auto_pk_0:
])
@skipUnlessDBFeature('can_defer_constraint_checks')
class SerializerTests(TestCase):
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
with self.assertRaises(SerializerDoesNotExist) as cm:
serializers.get_serializer("nonsense")
self.assertEqual(cm.exception.args, ("nonsense",))
def test_unregister_unknown_serializer(self):
with self.assertRaises(SerializerDoesNotExist):
serializers.unregister_serializer("nonsense")
def test_get_unknown_deserializer(self):
with self.assertRaises(SerializerDoesNotExist):
serializers.get_deserializer("nonsense")
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', ''))
pass
def serializerTest(format, self):
@ -457,41 +421,6 @@ def serializerTest(format, self):
self.assertEqual(count, klass.objects.count())
def fieldsTest(format, self):
obj = ComplexModel(field1='first', field2='second', field3='third')
obj.save_base(raw=True)
# Serialize then deserialize the test database
serialized_data = serializers.serialize(format, [obj], indent=2, fields=('field1', 'field3'))
result = next(serializers.deserialize(format, serialized_data))
# Check that the deserialized object contains data in only the serialized fields.
self.assertEqual(result.object.field1, 'first')
self.assertEqual(result.object.field2, '')
self.assertEqual(result.object.field3, 'third')
def streamTest(format, self):
obj = ComplexModel(field1='first', field2='second', field3='third')
obj.save_base(raw=True)
# Serialize the test database to a stream
for stream in (six.StringIO(), HttpResponse()):
serializers.serialize(format, [obj], indent=2, stream=stream)
# Serialize normally for a comparison
string_data = serializers.serialize(format, [obj], indent=2)
# Check that the two are the same
if isinstance(stream, six.StringIO):
self.assertEqual(string_data, stream.getvalue())
else:
self.assertEqual(string_data, stream.content.decode('utf-8'))
for format in [f for f in serializers.get_serializer_formats()
if not isinstance(serializers.get_serializer(f), serializers.BadSerializer) and not f == 'geojson']:
setattr(SerializerTests, 'test_' + format + '_serializer', curry(serializerTest, format))
setattr(SerializerTests, 'test_' + format + '_serializer_fields', curry(fieldsTest, format))
if format != 'python':
setattr(SerializerTests, 'test_' + format + '_serializer_stream', curry(streamTest, format))