Ejemplo n.º 1
0
 def test_serialize_multiline_strings(self):
     self.assertSerializedEqual(b"foo\nbar")
     string, imports = MigrationWriter.serialize(b"foo\nbar")
     self.assertEqual(string, "b'foo\\nbar'")
     self.assertSerializedEqual("föo\nbár")
     string, imports = MigrationWriter.serialize("foo\nbar")
     self.assertEqual(string, "'foo\\nbar'")
Ejemplo n.º 2
0
    def test_migration_file_header_comments(self):
        """
        Test comments at top of file.
        """
        migration = type("Migration", (migrations.Migration, ),
                         {"operations": []})
        dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=utc)
        with mock.patch('djmodels.db.migrations.writer.now', lambda: dt):
            writer = MigrationWriter(migration)
            output = writer.as_string()

        self.assertTrue(
            output.startswith(
                "# Generated by Django %(version)s on 2015-07-31 04:40\n" % {
                    'version': get_version(),
                }))
Ejemplo n.º 3
0
    def test_serialize_enums(self):
        class TextEnum(enum.Enum):
            A = 'a-value'
            B = 'value-b'

        class BinaryEnum(enum.Enum):
            A = b'a-value'
            B = b'value-b'

        class IntEnum(enum.IntEnum):
            A = 1
            B = 2

        self.assertSerializedResultEqual(
            TextEnum.A, ("migrations.test_writer.TextEnum('a-value')",
                         {'import migrations.test_writer'}))
        self.assertSerializedResultEqual(
            BinaryEnum.A, ("migrations.test_writer.BinaryEnum(b'a-value')",
                           {'import migrations.test_writer'}))
        self.assertSerializedResultEqual(IntEnum.B,
                                         ("migrations.test_writer.IntEnum(2)",
                                          {'import migrations.test_writer'}))

        field = models.CharField(default=TextEnum.B,
                                 choices=[(m.value, m) for m in TextEnum])
        string = MigrationWriter.serialize(field)[0]
        self.assertEqual(
            string, "models.CharField(choices=["
            "('a-value', migrations.test_writer.TextEnum('a-value')), "
            "('value-b', migrations.test_writer.TextEnum('value-b'))], "
            "default=migrations.test_writer.TextEnum('value-b'))")
        field = models.CharField(default=BinaryEnum.B,
                                 choices=[(m.value, m) for m in BinaryEnum])
        string = MigrationWriter.serialize(field)[0]
        self.assertEqual(
            string, "models.CharField(choices=["
            "(b'a-value', migrations.test_writer.BinaryEnum(b'a-value')), "
            "(b'value-b', migrations.test_writer.BinaryEnum(b'value-b'))], "
            "default=migrations.test_writer.BinaryEnum(b'value-b'))")
        field = models.IntegerField(default=IntEnum.A,
                                    choices=[(m.value, m) for m in IntEnum])
        string = MigrationWriter.serialize(field)[0]
        self.assertEqual(
            string, "models.IntegerField(choices=["
            "(1, migrations.test_writer.IntEnum(1)), "
            "(2, migrations.test_writer.IntEnum(2))], "
            "default=migrations.test_writer.IntEnum(1))")
Ejemplo n.º 4
0
 def test_serialize_functions(self):
     with self.assertRaisesMessage(ValueError,
                                   'Cannot serialize function: lambda'):
         self.assertSerializedEqual(lambda x: 42)
     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))
Ejemplo n.º 5
0
 def write_migration_files(self, changes):
     """
     Take a changes dict and write them out as migration files.
     """
     directory_created = {}
     for app_label, app_migrations in changes.items():
         if self.verbosity >= 1:
             self.stdout.write(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label) + "\n")
         for migration in app_migrations:
             # Describe the migration
             writer = MigrationWriter(migration)
             if self.verbosity >= 1:
                 # Display a relative path if it's below the current working
                 # directory, or an absolute path otherwise.
                 try:
                     migration_string = os.path.relpath(writer.path)
                 except ValueError:
                     migration_string = writer.path
                 if migration_string.startswith('..'):
                     migration_string = writer.path
                 self.stdout.write("  %s\n" % (self.style.MIGRATE_LABEL(migration_string),))
                 for operation in migration.operations:
                     self.stdout.write("    - %s\n" % operation.describe())
             if not self.dry_run:
                 # Write the migrations file to the disk.
                 migrations_directory = os.path.dirname(writer.path)
                 if not directory_created.get(app_label):
                     if not os.path.isdir(migrations_directory):
                         os.mkdir(migrations_directory)
                     init_path = os.path.join(migrations_directory, "__init__.py")
                     if not os.path.isfile(init_path):
                         open(init_path, "w").close()
                     # We just do this once per app
                     directory_created[app_label] = True
                 migration_string = writer.as_string()
                 with open(writer.path, "w", encoding='utf-8') as fh:
                     fh.write(migration_string)
             elif self.verbosity == 3:
                 # Alternatively, makemigrations --dry-run --verbosity 3
                 # will output the migrations to stdout rather than saving
                 # the file to the disk.
                 self.stdout.write(self.style.MIGRATE_HEADING(
                     "Full migrations file '%s':" % writer.filename) + "\n"
                 )
                 self.stdout.write("%s\n" % writer.as_string())
Ejemplo n.º 6
0
 def test_models_import_omitted(self):
     """
     djmodels.db.models shouldn't be imported if unused.
     """
     migration = type(
         "Migration", (migrations.Migration, ), {
             "operations": [
                 migrations.AlterModelOptions(
                     name='model',
                     options={
                         'verbose_name': 'model',
                         'verbose_name_plural': 'models'
                     },
                 ),
             ]
         })
     writer = MigrationWriter(migration)
     output = writer.as_string()
     self.assertIn("from djmodels.db import migrations\n", output)
Ejemplo n.º 7
0
 def test_sorted_imports(self):
     """
     #24155 - Tests ordering of imports.
     """
     migration = type(
         "Migration", (migrations.Migration, ), {
             "operations": [
                 migrations.AddField(
                     "mymodel", "myfield",
                     models.DateTimeField(default=datetime.datetime(
                         2012, 1, 1, 1, 1, tzinfo=utc), )),
             ]
         })
     writer = MigrationWriter(migration)
     output = writer.as_string()
     self.assertIn(
         "import datetime\n"
         "from djmodels.db import migrations, models\n"
         "from djmodels.utils.timezone import utc\n", output)
Ejemplo n.º 8
0
 def test_custom_operation(self):
     migration = type(
         "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
     )
Ejemplo n.º 9
0
    def test_simple_migration(self):
        """
        Tests serializing a simple migration.
        """
        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',
        }

        migration = type(
            "Migration", (migrations.Migration, ), {
                "operations": [
                    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, )),
                    migrations.DeleteModel("MyModel"),
                    migrations.AddField("OtherModel", "datetimefield",
                                        fields["datetimefield"]),
                ],
                "dependencies": [("testapp", "some_other_one")],
            })
        writer = MigrationWriter(migration)
        output = writer.as_string()
        # 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)
Ejemplo n.º 10
0
    def test_deconstruct_class_arguments(self):
        # Yes, it doesn't make sense to use a class as a default for a
        # CharField. It does make sense for custom fields though, for example
        # an enumfield that takes the enum class as an argument.
        class DeconstructibleInstances:
            def deconstruct(self):
                return ('DeconstructibleInstances', [], {})

        string = MigrationWriter.serialize(
            models.CharField(default=DeconstructibleInstances))[0]
        self.assertEqual(
            string,
            "models.CharField(default=migrations.test_writer.DeconstructibleInstances)"
        )
Ejemplo n.º 11
0
    def test_migration_path(self):
        test_apps = [
            'migrations.migrations_test_apps.normal',
            'migrations.migrations_test_apps.with_package_model',
            'migrations.migrations_test_apps.without_init_file',
        ]

        base_dir = os.path.dirname(os.path.dirname(__file__))

        for app in test_apps:
            with self.modify_settings(INSTALLED_APPS={'append': app}):
                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)
Ejemplo n.º 12
0
    def test_serialize_uuid(self):
        self.assertSerializedEqual(uuid.uuid1())
        self.assertSerializedEqual(uuid.uuid4())

        uuid_a = uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8')
        uuid_b = uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2')
        self.assertSerializedResultEqual(
            uuid_a, ("uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8')",
                     {'import uuid'}))
        self.assertSerializedResultEqual(
            uuid_b, ("uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2')",
                     {'import uuid'}))

        field = models.UUIDField(choices=((uuid_a, 'UUID A'), (uuid_b,
                                                               'UUID B')),
                                 default=uuid_a)
        string = MigrationWriter.serialize(field)[0]
        self.assertEqual(
            string, "models.UUIDField(choices=["
            "(uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'), 'UUID A'), "
            "(uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2'), 'UUID B')], "
            "default=uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'))")
Ejemplo n.º 13
0
 def assertSerializedResultEqual(self, value, target):
     self.assertEqual(MigrationWriter.serialize(value), target)
Ejemplo n.º 14
0
 def test_serialize_builtins(self):
     string, imports = MigrationWriter.serialize(range)
     self.assertEqual(string, 'range')
     self.assertEqual(imports, set())
Ejemplo n.º 15
0
    def test_serialize_class_based_validators(self):
        """
        Ticket #22943: Test serialization of class-based validators, including
        compiled regexes.
        """
        validator = RegexValidator(message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string, "djmodels.core.validators.RegexValidator(message='hello')")
        self.serialize_round_trip(validator)

        # Test with a compiled regex.
        validator = RegexValidator(regex=re.compile(r'^\w+$'))
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string,
            "djmodels.core.validators.RegexValidator(regex=re.compile('^\\\\w+$'))"
        )
        self.serialize_round_trip(validator)

        # Test a string regex with flag
        validator = RegexValidator(r'^[0-9]+$', flags=re.S)
        string = MigrationWriter.serialize(validator)[0]
        if PY36:
            self.assertEqual(
                string,
                "djmodels.core.validators.RegexValidator('^[0-9]+$', flags=re.RegexFlag(16))"
            )
        else:
            self.assertEqual(
                string,
                "djmodels.core.validators.RegexValidator('^[0-9]+$', flags=16)"
            )
        self.serialize_round_trip(validator)

        # Test message and code
        validator = RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string,
            "djmodels.core.validators.RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')"
        )
        self.serialize_round_trip(validator)

        # Test with a subclass.
        validator = EmailValidator(message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string, "djmodels.core.validators.EmailValidator(message='hello')")
        self.serialize_round_trip(validator)

        validator = deconstructible(
            path="migrations.test_writer.EmailValidator")(EmailValidator)(
                message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string, "migrations.test_writer.EmailValidator(message='hello')")

        validator = deconstructible(
            path="custom.EmailValidator")(EmailValidator)(message="hello")
        with self.assertRaisesMessage(ImportError, "No module named 'custom'"):
            MigrationWriter.serialize(validator)

        validator = deconstructible(
            path="djmodels.core.validators.EmailValidator2")(EmailValidator)(
                message="hello")
        with self.assertRaisesMessage(
                ValueError,
                "Could not find object EmailValidator2 in djmodels.core.validators."
        ):
            MigrationWriter.serialize(validator)
Ejemplo n.º 16
0
    def handle_merge(self, loader, conflicts):
        """
        Handles merging together conflicted migrations interactively,
        if it's safe; otherwise, advises on how to fix it.
        """
        if self.interactive:
            questioner = InteractiveMigrationQuestioner()
        else:
            questioner = MigrationQuestioner(defaults={'ask_merge': True})

        for app_label, migration_names in conflicts.items():
            # Grab out the migrations in question, and work out their
            # common ancestor.
            merge_migrations = []
            for migration_name in migration_names:
                migration = loader.get_migration(app_label, migration_name)
                migration.ancestry = [
                    mig for mig in loader.graph.forwards_plan((app_label, migration_name))
                    if mig[0] == migration.app_label
                ]
                merge_migrations.append(migration)

            def all_items_equal(seq):
                return all(item == seq[0] for item in seq[1:])

            merge_migrations_generations = zip(*(m.ancestry for m in merge_migrations))
            common_ancestor_count = sum(1 for common_ancestor_generation
                                        in takewhile(all_items_equal, merge_migrations_generations))
            if not common_ancestor_count:
                raise ValueError("Could not find common ancestor of %s" % migration_names)
            # Now work out the operations along each divergent branch
            for migration in merge_migrations:
                migration.branch = migration.ancestry[common_ancestor_count:]
                migrations_ops = (loader.get_migration(node_app, node_name).operations
                                  for node_app, node_name in migration.branch)
                migration.merged_operations = sum(migrations_ops, [])
            # In future, this could use some of the Optimizer code
            # (can_optimize_through) to automatically see if they're
            # mergeable. For now, we always just prompt the user.
            if self.verbosity > 0:
                self.stdout.write(self.style.MIGRATE_HEADING("Merging %s" % app_label))
                for migration in merge_migrations:
                    self.stdout.write(self.style.MIGRATE_LABEL("  Branch %s" % migration.name))
                    for operation in migration.merged_operations:
                        self.stdout.write("    - %s\n" % operation.describe())
            if questioner.ask_merge(app_label):
                # If they still want to merge it, then write out an empty
                # file depending on the migrations needing merging.
                numbers = [
                    MigrationAutodetector.parse_number(migration.name)
                    for migration in merge_migrations
                ]
                try:
                    biggest_number = max(x for x in numbers if x is not None)
                except ValueError:
                    biggest_number = 1
                subclass = type("Migration", (Migration,), {
                    "dependencies": [(app_label, migration.name) for migration in merge_migrations],
                })
                migration_name = "%04i_%s" % (
                    biggest_number + 1,
                    self.migration_name or ("merge_%s" % get_migration_name_timestamp())
                )
                new_migration = subclass(migration_name, app_label)
                writer = MigrationWriter(new_migration)

                if not self.dry_run:
                    # Write the merge migrations file to the disk
                    with open(writer.path, "w", encoding='utf-8') as fh:
                        fh.write(writer.as_string())
                    if self.verbosity > 0:
                        self.stdout.write("\nCreated new merge migration %s" % writer.path)
                elif self.verbosity == 3:
                    # Alternatively, makemigrations --merge --dry-run --verbosity 3
                    # will output the merge migrations to stdout rather than saving
                    # the file to the disk.
                    self.stdout.write(self.style.MIGRATE_HEADING(
                        "Full merge migrations file '%s':" % writer.filename) + "\n"
                    )
                    self.stdout.write("%s\n" % writer.as_string())
Ejemplo n.º 17
0
    def handle(self, **options):

        self.verbosity = options['verbosity']
        self.interactive = options['interactive']
        app_label = options['app_label']
        start_migration_name = options['start_migration_name']
        migration_name = options['migration_name']
        no_optimize = options['no_optimize']
        squashed_name = options['squashed_name']
        # Validate app_label.
        try:
            apps.get_app_config(app_label)
        except LookupError as err:
            raise CommandError(str(err))
        # Load the current graph state, check the app and migration they asked for exists
        loader = MigrationLoader(connections[DEFAULT_DB_ALIAS])
        if app_label not in loader.migrated_apps:
            raise CommandError(
                "App '%s' does not have migrations (so squashmigrations on "
                "it makes no sense)" % app_label
            )

        migration = self.find_migration(loader, app_label, migration_name)

        # Work out the list of predecessor migrations
        migrations_to_squash = [
            loader.get_migration(al, mn)
            for al, mn in loader.graph.forwards_plan((migration.app_label, migration.name))
            if al == migration.app_label
        ]

        if start_migration_name:
            start_migration = self.find_migration(loader, app_label, start_migration_name)
            start = loader.get_migration(start_migration.app_label, start_migration.name)
            try:
                start_index = migrations_to_squash.index(start)
                migrations_to_squash = migrations_to_squash[start_index:]
            except ValueError:
                raise CommandError(
                    "The migration '%s' cannot be found. Maybe it comes after "
                    "the migration '%s'?\n"
                    "Have a look at:\n"
                    "  python manage.py showmigrations %s\n"
                    "to debug this issue." % (start_migration, migration, app_label)
                )

        # Tell them what we're doing and optionally ask if we should proceed
        if self.verbosity > 0 or self.interactive:
            self.stdout.write(self.style.MIGRATE_HEADING("Will squash the following migrations:"))
            for migration in migrations_to_squash:
                self.stdout.write(" - %s" % migration.name)

            if self.interactive:
                answer = None
                while not answer or answer not in "yn":
                    answer = input("Do you wish to proceed? [yN] ")
                    if not answer:
                        answer = "n"
                        break
                    else:
                        answer = answer[0].lower()
                if answer != "y":
                    return

        # Load the operations from all those migrations and concat together,
        # along with collecting external dependencies and detecting
        # double-squashing
        operations = []
        dependencies = set()
        # We need to take all dependencies from the first migration in the list
        # as it may be 0002 depending on 0001
        first_migration = True
        for smigration in migrations_to_squash:
            if smigration.replaces:
                raise CommandError(
                    "You cannot squash squashed migrations! Please transition "
                    "it to a normal migration first: "
                    "https://docs.djangoproject.com/en/%s/topics/migrations/#squashing-migrations" % get_docs_version()
                )
            operations.extend(smigration.operations)
            for dependency in smigration.dependencies:
                if isinstance(dependency, SwappableTuple):
                    if settings.AUTH_USER_MODEL == dependency.setting:
                        dependencies.add(("__setting__", "AUTH_USER_MODEL"))
                    else:
                        dependencies.add(dependency)
                elif dependency[0] != smigration.app_label or first_migration:
                    dependencies.add(dependency)
            first_migration = False

        if no_optimize:
            if self.verbosity > 0:
                self.stdout.write(self.style.MIGRATE_HEADING("(Skipping optimization.)"))
            new_operations = operations
        else:
            if self.verbosity > 0:
                self.stdout.write(self.style.MIGRATE_HEADING("Optimizing..."))

            optimizer = MigrationOptimizer()
            new_operations = optimizer.optimize(operations, migration.app_label)

            if self.verbosity > 0:
                if len(new_operations) == len(operations):
                    self.stdout.write("  No optimizations possible.")
                else:
                    self.stdout.write(
                        "  Optimized from %s operations to %s operations." %
                        (len(operations), len(new_operations))
                    )

        # Work out the value of replaces (any squashed ones we're re-squashing)
        # need to feed their replaces into ours
        replaces = []
        for migration in migrations_to_squash:
            if migration.replaces:
                replaces.extend(migration.replaces)
            else:
                replaces.append((migration.app_label, migration.name))

        # Make a new migration with those operations
        subclass = type("Migration", (migrations.Migration,), {
            "dependencies": dependencies,
            "operations": new_operations,
            "replaces": replaces,
        })
        if start_migration_name:
            if squashed_name:
                # Use the name from --squashed-name.
                prefix, _ = start_migration.name.split('_', 1)
                name = '%s_%s' % (prefix, squashed_name)
            else:
                # Generate a name.
                name = '%s_squashed_%s' % (start_migration.name, migration.name)
            new_migration = subclass(name, app_label)
        else:
            name = '0001_%s' % (squashed_name or 'squashed_%s' % migration.name)
            new_migration = subclass(name, app_label)
            new_migration.initial = True

        # Write out the new migration file
        writer = MigrationWriter(new_migration)
        with open(writer.path, "w", encoding='utf-8') as fh:
            fh.write(writer.as_string())

        if self.verbosity > 0:
            self.stdout.write(self.style.MIGRATE_HEADING("Created new squashed migration %s" % writer.path))
            self.stdout.write("  You should commit this migration but leave the old ones in place;")
            self.stdout.write("  the new migration will be used for new installs. Once you are sure")
            self.stdout.write("  all instances of the codebase have applied the migrations you squashed,")
            self.stdout.write("  you can delete them.")
            if writer.needs_manual_porting:
                self.stdout.write(self.style.MIGRATE_HEADING("Manual porting required"))
                self.stdout.write("  Your migrations contained functions that must be manually copied over,")
                self.stdout.write("  as we could not safely copy their implementation.")
                self.stdout.write("  See the comment at the top of the squashed migration for details.")
Ejemplo n.º 18
0
 def serialize_round_trip(self, value):
     string, imports = MigrationWriter.serialize(value)
     return self.safe_exec(
         "%s\ntest_value_result = %s" % ("\n".join(imports), string),
         value)['test_value_result']