[1.7.x] Fixed #22679 -- Fixed empty tuple serialization in MigrationWriter.

Thanks rockallite.wulf for the report.

Backport of ad994a3c5b from master.
This commit is contained in:
Moayad Mardini 2014-05-22 14:29:30 +03:00 committed by Baptiste Mispelon
parent fb45e666c2
commit 7d4a51e239
2 changed files with 18 additions and 2 deletions

View File

@ -206,7 +206,9 @@ class MigrationWriter(object):
if isinstance(value, set): if isinstance(value, set):
format = "set([%s])" format = "set([%s])"
elif isinstance(value, tuple): elif isinstance(value, tuple):
format = "(%s)" if len(value) > 1 else "(%s,)" # When len(value)==0, the empty tuple should be serialized as
# "()", not "(,)" because (,) is invalid Python syntax.
format = "(%s)" if len(value) != 1 else "(%s,)"
else: else:
format = "[%s]" format = "[%s]"
return format % (", ".join(strings)), imports return format % (", ".join(strings)), imports
@ -296,7 +298,9 @@ class MigrationWriter(object):
item_string, item_imports = cls.serialize(item) item_string, item_imports = cls.serialize(item)
imports.update(item_imports) imports.update(item_imports)
strings.append(item_string) strings.append(item_string)
format = "(%s)" if len(strings) > 1 else "(%s,)" # When len(strings)==0, the empty iterable should be serialized as
# "()", not "(,)" because (,) is invalid Python syntax.
format = "(%s)" if len(strings) != 1 else "(%s,)"
return format % (", ".join(strings)), imports return format % (", ".join(strings)), imports
# Uh oh. # Uh oh.
else: else:

View File

@ -125,6 +125,18 @@ class WriterTests(TestCase):
) )
) )
def test_serialize_empty_nonempty_tuple(self):
"""
Ticket #22679: makemigrations generates invalid code for (an empty
tuple) default_permissions = ()
"""
empty_tuple = ()
one_item_tuple = ('a')
many_items_tuple = ('a', 'b', 'c')
self.assertSerializedEqual(empty_tuple)
self.assertSerializedEqual(one_item_tuple)
self.assertSerializedEqual(many_items_tuple)
def test_simple_migration(self): def test_simple_migration(self):
""" """
Tests serializing a simple migration. Tests serializing a simple migration.