From ad994a3c5b5911a12a5e2f2a8d06c036be1b8ad8 Mon Sep 17 00:00:00 2001 From: Moayad Mardini Date: Thu, 22 May 2014 14:29:30 +0300 Subject: [PATCH] Fixed #22679 -- Fixed empty tuple serialization in MigrationWriter. Thanks rockallite.wulf for the report. --- django/db/migrations/writer.py | 8 ++++++-- tests/migrations/test_writer.py | 12 ++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/django/db/migrations/writer.py b/django/db/migrations/writer.py index da6aed4308..c8a3a6cf76 100644 --- a/django/db/migrations/writer.py +++ b/django/db/migrations/writer.py @@ -206,7 +206,9 @@ class MigrationWriter(object): if isinstance(value, set): format = "set([%s])" 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: format = "[%s]" return format % (", ".join(strings)), imports @@ -296,7 +298,9 @@ class MigrationWriter(object): item_string, item_imports = cls.serialize(item) imports.update(item_imports) 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 # Uh oh. else: diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py index 58b5aa6cac..f73f08fb9c 100644 --- a/tests/migrations/test_writer.py +++ b/tests/migrations/test_writer.py @@ -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): """ Tests serializing a simple migration.