2014-05-15 17:41:55 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
2013-08-23 11:56:37 +00:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2013-06-07 14:28:38 +00:00
|
|
|
import datetime
|
2013-10-19 00:24:38 +00:00
|
|
|
import os
|
2014-03-31 19:25:08 +00:00
|
|
|
import tokenize
|
2014-06-08 00:04:58 +00:00
|
|
|
import unittest
|
2013-08-23 11:56:37 +00:00
|
|
|
|
2013-10-21 17:33:57 +00:00
|
|
|
from django.core.validators import RegexValidator, EmailValidator
|
2013-06-07 14:36:31 +00:00
|
|
|
from django.db import models, migrations
|
2014-01-15 14:20:47 +00:00
|
|
|
from django.db.migrations.writer import MigrationWriter, SettingsReference
|
2013-12-19 21:33:46 +00:00
|
|
|
from django.test import TestCase
|
2014-01-15 14:20:47 +00:00
|
|
|
from django.conf import settings
|
2014-03-31 20:16:34 +00:00
|
|
|
from django.utils import datetime_safe, six
|
2013-10-21 17:33:57 +00:00
|
|
|
from django.utils.deconstruct import deconstructible
|
2013-08-31 19:11:37 +00:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2014-02-09 11:17:13 +00:00
|
|
|
from django.utils.timezone import get_default_timezone
|
2013-06-07 14:28:38 +00:00
|
|
|
|
2014-06-11 13:00:52 +00:00
|
|
|
import custom_migration_operations.operations
|
|
|
|
import custom_migration_operations.more_operations
|
|
|
|
|
2013-06-07 14:28:38 +00:00
|
|
|
|
2014-06-08 00:04:58 +00:00
|
|
|
class TestModel1(object):
|
|
|
|
def upload_to(self):
|
|
|
|
return "somewhere dynamic"
|
|
|
|
thing = models.FileField(upload_to=upload_to)
|
|
|
|
|
|
|
|
|
2013-06-19 14:36:02 +00:00
|
|
|
class WriterTests(TestCase):
|
2013-06-07 14:28:38 +00:00
|
|
|
"""
|
|
|
|
Tests the migration writer (makes migration files from Migration instances)
|
|
|
|
"""
|
|
|
|
|
2013-06-07 16:56:43 +00:00
|
|
|
def safe_exec(self, string, value=None):
|
2013-06-07 14:28:38 +00:00
|
|
|
l = {}
|
|
|
|
try:
|
2013-06-07 16:56:43 +00:00
|
|
|
exec(string, globals(), l)
|
|
|
|
except Exception as e:
|
|
|
|
if value:
|
|
|
|
self.fail("Could not exec %r (from value %r): %s" % (string.strip(), value, e))
|
|
|
|
else:
|
|
|
|
self.fail("Could not exec %r: %s" % (string.strip(), e))
|
2013-06-07 14:28:38 +00:00
|
|
|
return l
|
|
|
|
|
2013-06-07 16:56:43 +00:00
|
|
|
def serialize_round_trip(self, value):
|
2013-06-07 14:28:38 +00:00
|
|
|
string, imports = MigrationWriter.serialize(value)
|
2013-06-07 16:56:43 +00:00
|
|
|
return self.safe_exec("%s\ntest_value_result = %s" % ("\n".join(imports), string), value)['test_value_result']
|
|
|
|
|
|
|
|
def assertSerializedEqual(self, value):
|
|
|
|
self.assertEqual(self.serialize_round_trip(value), value)
|
2013-06-07 14:28:38 +00:00
|
|
|
|
2014-01-15 14:20:47 +00:00
|
|
|
def assertSerializedResultEqual(self, value, target):
|
|
|
|
self.assertEqual(MigrationWriter.serialize(value), target)
|
2013-06-07 16:56:43 +00:00
|
|
|
|
|
|
|
def assertSerializedFieldEqual(self, value):
|
|
|
|
new_value = self.serialize_round_trip(value)
|
|
|
|
self.assertEqual(value.__class__, new_value.__class__)
|
|
|
|
self.assertEqual(value.max_length, new_value.max_length)
|
|
|
|
self.assertEqual(value.null, new_value.null)
|
|
|
|
self.assertEqual(value.unique, new_value.unique)
|
2013-06-07 14:28:38 +00:00
|
|
|
|
|
|
|
def test_serialize(self):
|
|
|
|
"""
|
|
|
|
Tests various different forms of the serializer.
|
|
|
|
This does not care about formatting, just that the parsed result is
|
|
|
|
correct, so we always exec() the result and check that.
|
|
|
|
"""
|
|
|
|
# Basic values
|
|
|
|
self.assertSerializedEqual(1)
|
|
|
|
self.assertSerializedEqual(None)
|
2013-08-23 11:56:37 +00:00
|
|
|
self.assertSerializedEqual(b"foobar")
|
2014-03-31 19:25:08 +00:00
|
|
|
string, imports = MigrationWriter.serialize(b"foobar")
|
|
|
|
self.assertEqual(string, "b'foobar'")
|
2013-08-23 11:56:37 +00:00
|
|
|
self.assertSerializedEqual("föobár")
|
2014-03-31 19:25:08 +00:00
|
|
|
string, imports = MigrationWriter.serialize("foobar")
|
|
|
|
self.assertEqual(string, "'foobar'")
|
2013-06-07 14:28:38 +00:00
|
|
|
self.assertSerializedEqual({1: 2})
|
|
|
|
self.assertSerializedEqual(["a", 2, True, None])
|
|
|
|
self.assertSerializedEqual(set([2, 3, "eighty"]))
|
|
|
|
self.assertSerializedEqual({"lalalala": ["yeah", "no", "maybe"]})
|
2013-08-31 19:11:37 +00:00
|
|
|
self.assertSerializedEqual(_('Hello'))
|
2013-09-05 03:36:31 +00:00
|
|
|
# Functions
|
|
|
|
with six.assertRaisesRegex(self, ValueError, 'Cannot serialize function: lambda'):
|
|
|
|
self.assertSerializedEqual(lambda x: 42)
|
2013-09-02 06:02:07 +00:00
|
|
|
self.assertSerializedEqual(models.SET_NULL)
|
|
|
|
string, imports = MigrationWriter.serialize(models.SET(42))
|
|
|
|
self.assertEqual(string, 'models.SET(42)')
|
|
|
|
self.serialize_round_trip(models.SET(42))
|
2013-06-07 14:28:38 +00:00
|
|
|
# Datetime stuff
|
|
|
|
self.assertSerializedEqual(datetime.datetime.utcnow())
|
|
|
|
self.assertSerializedEqual(datetime.datetime.utcnow)
|
2013-10-18 17:14:01 +00:00
|
|
|
self.assertSerializedEqual(datetime.datetime.today())
|
|
|
|
self.assertSerializedEqual(datetime.datetime.today)
|
2013-06-07 14:28:38 +00:00
|
|
|
self.assertSerializedEqual(datetime.date.today())
|
|
|
|
self.assertSerializedEqual(datetime.date.today)
|
2014-02-09 11:17:13 +00:00
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
self.assertSerializedEqual(datetime.datetime(2012, 1, 1, 1, 1, tzinfo=get_default_timezone()))
|
2014-03-31 20:16:34 +00:00
|
|
|
safe_date = datetime_safe.date(2014, 3, 31)
|
|
|
|
string, imports = MigrationWriter.serialize(safe_date)
|
|
|
|
self.assertEqual(string, repr(datetime.date(2014, 3, 31)))
|
|
|
|
self.assertEqual(imports, {'import datetime'})
|
|
|
|
safe_datetime = datetime_safe.datetime(2014, 3, 31, 16, 4, 31)
|
|
|
|
string, imports = MigrationWriter.serialize(safe_datetime)
|
|
|
|
self.assertEqual(string, repr(datetime.datetime(2014, 3, 31, 16, 4, 31)))
|
|
|
|
self.assertEqual(imports, {'import datetime'})
|
2013-10-21 17:33:57 +00:00
|
|
|
# Classes
|
|
|
|
validator = RegexValidator(message="hello")
|
|
|
|
string, imports = MigrationWriter.serialize(validator)
|
2014-03-31 19:25:08 +00:00
|
|
|
self.assertEqual(string, "django.core.validators.RegexValidator(message='hello')")
|
2013-10-21 17:33:57 +00:00
|
|
|
self.serialize_round_trip(validator)
|
|
|
|
validator = EmailValidator(message="hello") # Test with a subclass.
|
|
|
|
string, imports = MigrationWriter.serialize(validator)
|
2014-03-31 19:25:08 +00:00
|
|
|
self.assertEqual(string, "django.core.validators.EmailValidator(message='hello')")
|
2013-10-21 17:33:57 +00:00
|
|
|
self.serialize_round_trip(validator)
|
|
|
|
validator = deconstructible(path="custom.EmailValidator")(EmailValidator)(message="hello")
|
|
|
|
string, imports = MigrationWriter.serialize(validator)
|
2014-03-31 19:25:08 +00:00
|
|
|
self.assertEqual(string, "custom.EmailValidator(message='hello')")
|
2013-06-07 16:56:43 +00:00
|
|
|
# Django fields
|
|
|
|
self.assertSerializedFieldEqual(models.CharField(max_length=255))
|
|
|
|
self.assertSerializedFieldEqual(models.TextField(null=True, blank=True))
|
2014-01-15 14:20:47 +00:00
|
|
|
# Setting references
|
|
|
|
self.assertSerializedEqual(SettingsReference(settings.AUTH_USER_MODEL, "AUTH_USER_MODEL"))
|
|
|
|
self.assertSerializedResultEqual(
|
|
|
|
SettingsReference("someapp.model", "AUTH_USER_MODEL"),
|
|
|
|
(
|
|
|
|
"settings.AUTH_USER_MODEL",
|
|
|
|
set(["from django.conf import settings"]),
|
|
|
|
)
|
|
|
|
)
|
2014-01-22 08:06:06 +00:00
|
|
|
self.assertSerializedResultEqual(
|
2014-01-22 15:21:05 +00:00
|
|
|
((x, x * x) for x in range(3)),
|
2014-01-22 08:06:06 +00:00
|
|
|
(
|
|
|
|
"((0, 0), (1, 1), (2, 4))",
|
|
|
|
set(),
|
|
|
|
)
|
|
|
|
)
|
2013-06-07 14:28:38 +00:00
|
|
|
|
2014-05-22 11:29:30 +00:00
|
|
|
def test_serialize_empty_nonempty_tuple(self):
|
|
|
|
"""
|
|
|
|
Ticket #22679: makemigrations generates invalid code for (an empty
|
|
|
|
tuple) default_permissions = ()
|
|
|
|
"""
|
|
|
|
empty_tuple = ()
|
2014-05-23 12:50:10 +00:00
|
|
|
one_item_tuple = ('a',)
|
2014-05-22 11:29:30 +00:00
|
|
|
many_items_tuple = ('a', 'b', 'c')
|
|
|
|
self.assertSerializedEqual(empty_tuple)
|
|
|
|
self.assertSerializedEqual(one_item_tuple)
|
|
|
|
self.assertSerializedEqual(many_items_tuple)
|
|
|
|
|
2014-06-08 00:04:58 +00:00
|
|
|
@unittest.skipUnless(six.PY2, "Only applies on Python 2")
|
|
|
|
def test_serialize_direct_function_reference(self):
|
|
|
|
"""
|
|
|
|
Ticket #22436: You cannot use a function straight from its body
|
|
|
|
(e.g. define the method and use it in the same body)
|
|
|
|
"""
|
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
self.serialize_round_trip(TestModel1.thing)
|
|
|
|
|
|
|
|
def test_serialize_local_function_reference(self):
|
|
|
|
"""
|
|
|
|
Neither py2 or py3 can serialize a reference in a local scope.
|
|
|
|
"""
|
|
|
|
class TestModel2(object):
|
|
|
|
def upload_to(self):
|
|
|
|
return "somewhere dynamic"
|
|
|
|
thing = models.FileField(upload_to=upload_to)
|
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
self.serialize_round_trip(TestModel2.thing)
|
|
|
|
|
2013-06-07 14:28:38 +00:00
|
|
|
def test_simple_migration(self):
|
|
|
|
"""
|
|
|
|
Tests serializing a simple migration.
|
|
|
|
"""
|
2013-09-26 07:25:35 +00:00
|
|
|
fields = {
|
|
|
|
'charfield': models.DateTimeField(default=datetime.datetime.utcnow),
|
|
|
|
'datetimefield': models.DateTimeField(default=datetime.datetime.utcnow),
|
|
|
|
}
|
|
|
|
|
|
|
|
options = {
|
|
|
|
'verbose_name': 'My model',
|
|
|
|
'verbose_name_plural': 'My models',
|
|
|
|
}
|
|
|
|
|
2013-08-23 11:56:37 +00:00
|
|
|
migration = type(str("Migration"), (migrations.Migration,), {
|
2013-06-07 14:28:38 +00:00
|
|
|
"operations": [
|
2013-09-26 07:25:35 +00:00
|
|
|
migrations.CreateModel("MyModel", tuple(fields.items()), options, (models.Model,)),
|
|
|
|
migrations.CreateModel("MyModel2", tuple(fields.items()), bases=(models.Model,)),
|
|
|
|
migrations.CreateModel(name="MyModel3", fields=tuple(fields.items()), options=options, bases=(models.Model,)),
|
2013-06-07 14:28:38 +00:00
|
|
|
migrations.DeleteModel("MyModel"),
|
2013-09-26 07:25:35 +00:00
|
|
|
migrations.AddField("OtherModel", "datetimefield", fields["datetimefield"]),
|
2013-06-07 14:28:38 +00:00
|
|
|
],
|
|
|
|
"dependencies": [("testapp", "some_other_one")],
|
|
|
|
})
|
|
|
|
writer = MigrationWriter(migration)
|
|
|
|
output = writer.as_string()
|
2013-06-07 16:56:43 +00:00
|
|
|
# It should NOT be unicode.
|
|
|
|
self.assertIsInstance(output, six.binary_type, "Migration as_string returned unicode")
|
|
|
|
# We don't test the output formatting - that's too fragile.
|
|
|
|
# Just make sure it runs for now, and that things look alright.
|
|
|
|
result = self.safe_exec(output)
|
|
|
|
self.assertIn("Migration", result)
|
2014-03-31 19:25:08 +00:00
|
|
|
# In order to preserve compatibility with Python 3.2 unicode literals
|
|
|
|
# prefix shouldn't be added to strings.
|
|
|
|
tokens = tokenize.generate_tokens(six.StringIO(str(output)).readline)
|
2014-04-21 10:25:43 +00:00
|
|
|
for token_type, token_source, (srow, scol), __, line in tokens:
|
2014-03-31 19:25:08 +00:00
|
|
|
if token_type == tokenize.STRING:
|
|
|
|
self.assertFalse(
|
|
|
|
token_source.startswith('u'),
|
|
|
|
"Unicode literal prefix found at %d:%d: %r" % (
|
|
|
|
srow, scol, line.strip()
|
|
|
|
)
|
|
|
|
)
|
2013-10-19 00:24:38 +00:00
|
|
|
|
|
|
|
def test_migration_path(self):
|
|
|
|
test_apps = [
|
|
|
|
'migrations.migrations_test_apps.normal',
|
|
|
|
'migrations.migrations_test_apps.with_package_model',
|
2014-06-17 15:50:31 +00:00
|
|
|
'migrations.migrations_test_apps.without_init_file',
|
2013-10-19 00:24:38 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
base_dir = os.path.dirname(os.path.dirname(__file__))
|
|
|
|
|
2013-12-19 21:33:46 +00:00
|
|
|
for app in test_apps:
|
2013-12-23 09:37:34 +00:00
|
|
|
with self.modify_settings(INSTALLED_APPS={'append': app}):
|
2013-12-19 21:33:46 +00:00
|
|
|
migration = migrations.Migration('0001_initial', app.split('.')[-1])
|
|
|
|
expected_path = os.path.join(base_dir, *(app.split('.') + ['migrations', '0001_initial.py']))
|
|
|
|
writer = MigrationWriter(migration)
|
|
|
|
self.assertEqual(writer.path, expected_path)
|
2014-06-11 13:00:52 +00:00
|
|
|
|
|
|
|
def test_custom_operation(self):
|
|
|
|
migration = type(str("Migration"), (migrations.Migration,), {
|
|
|
|
"operations": [
|
|
|
|
custom_migration_operations.operations.TestOperation(),
|
|
|
|
custom_migration_operations.operations.CreateModel(),
|
|
|
|
migrations.CreateModel("MyModel", (), {}, (models.Model,)),
|
|
|
|
custom_migration_operations.more_operations.TestOperation()
|
|
|
|
],
|
|
|
|
"dependencies": []
|
|
|
|
})
|
|
|
|
writer = MigrationWriter(migration)
|
|
|
|
output = writer.as_string()
|
|
|
|
result = self.safe_exec(output)
|
|
|
|
self.assertIn("custom_migration_operations", result)
|
|
|
|
self.assertNotEqual(
|
|
|
|
result['custom_migration_operations'].operations.TestOperation,
|
|
|
|
result['custom_migration_operations'].more_operations.TestOperation
|
|
|
|
)
|