Python django.db.migrations.state.ProjectState() Examples

The following are 30 code examples of django.db.migrations.state.ProjectState(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.migrations.state , or try the search function .
Example #1
Source File: graph.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def make_state(self, nodes=None, at_end=True, real_apps=None):
        """
        Given a migration node or nodes, returns a complete ProjectState for it.
        If at_end is False, returns the state before the migration has run.
        If nodes is not provided, returns the overall most current project state.
        """
        if nodes is None:
            nodes = list(self.leaf_nodes())
        if len(nodes) == 0:
            return ProjectState()
        if not isinstance(nodes[0], tuple):
            nodes = [nodes]
        plan = []
        for node in nodes:
            for migration in self.forwards_plan(node):
                if migration not in plan:
                    if not at_end and migration in nodes:
                        continue
                    plan.append(migration)
        project_state = ProjectState(real_apps=real_apps)
        for node in plan:
            project_state = self.nodes[node].mutate_state(project_state, preserve=False)
        return project_state 
Example #2
Source File: test_multidb.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def _test_create_model(self, app_label, should_run):
        """
        CreateModel honors multi-db settings.
        """
        operation = migrations.CreateModel(
            "Pony",
            [("id", models.AutoField(primary_key=True))],
        )
        # Test the state alteration
        project_state = ProjectState()
        new_state = project_state.clone()
        operation.state_forwards(app_label, new_state)
        # Test the database alteration
        self.assertTableNotExists("%s_pony" % app_label)
        with connection.schema_editor() as editor:
            operation.database_forwards(app_label, editor, project_state, new_state)
        if should_run:
            self.assertTableExists("%s_pony" % app_label)
        else:
            self.assertTableNotExists("%s_pony" % app_label)
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards(app_label, editor, new_state, project_state)
        self.assertTableNotExists("%s_pony" % app_label) 
Example #3
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_rename_model_state_forwards(self):
        """
        RenameModel operations shouldn't trigger the caching of rendered apps
        on state without prior apps.
        """
        state = ProjectState()
        state.add_model(ModelState('migrations', 'Foo', []))
        operation = migrations.RenameModel('Foo', 'Bar')
        operation.state_forwards('migrations', state)
        self.assertNotIn('apps', state.__dict__)
        self.assertNotIn(('migrations', 'foo'), state.models)
        self.assertIn(('migrations', 'bar'), state.models)
        # Now with apps cached.
        apps = state.apps
        operation = migrations.RenameModel('Bar', 'Foo')
        operation.state_forwards('migrations', state)
        self.assertIs(state.apps, apps)
        self.assertNotIn(('migrations', 'bar'), state.models)
        self.assertIn(('migrations', 'foo'), state.models) 
Example #4
Source File: test_operations.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_rename_model_state_forwards(self):
        """
        RenameModel operations shouldn't trigger the caching of rendered apps
        on state without prior apps.
        """
        state = ProjectState()
        state.add_model(ModelState('migrations', 'Foo', []))
        operation = migrations.RenameModel('Foo', 'Bar')
        operation.state_forwards('migrations', state)
        self.assertNotIn('apps', state.__dict__)
        self.assertNotIn(('migrations', 'foo'), state.models)
        self.assertIn(('migrations', 'bar'), state.models)
        # Now with apps cached.
        apps = state.apps
        operation = migrations.RenameModel('Bar', 'Foo')
        operation.state_forwards('migrations', state)
        self.assertIs(state.apps, apps)
        self.assertNotIn(('migrations', 'bar'), state.models)
        self.assertIn(('migrations', 'foo'), state.models) 
Example #5
Source File: test_multidb.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def _test_create_model(self, app_label, should_run):
        """
        CreateModel honors multi-db settings.
        """
        operation = migrations.CreateModel(
            "Pony",
            [("id", models.AutoField(primary_key=True))],
        )
        # Test the state alteration
        project_state = ProjectState()
        new_state = project_state.clone()
        operation.state_forwards(app_label, new_state)
        # Test the database alteration
        self.assertTableNotExists("%s_pony" % app_label)
        with connection.schema_editor() as editor:
            operation.database_forwards(app_label, editor, project_state, new_state)
        if should_run:
            self.assertTableExists("%s_pony" % app_label)
        else:
            self.assertTableNotExists("%s_pony" % app_label)
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards(app_label, editor, new_state, project_state)
        self.assertTableNotExists("%s_pony" % app_label) 
Example #6
Source File: test_multidb.py    From django-sqlserver with MIT License 6 votes vote down vote up
def _test_create_model(self, app_label, should_run):
        """
        CreateModel honors multi-db settings.
        """
        operation = migrations.CreateModel(
            "Pony",
            [("id", models.AutoField(primary_key=True))],
        )
        # Test the state alteration
        project_state = ProjectState()
        new_state = project_state.clone()
        operation.state_forwards(app_label, new_state)
        # Test the database alteration
        self.assertTableNotExists("%s_pony" % app_label)
        with connection.schema_editor() as editor:
            operation.database_forwards(app_label, editor, project_state, new_state)
        if should_run:
            self.assertTableExists("%s_pony" % app_label)
        else:
            self.assertTableNotExists("%s_pony" % app_label)
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards(app_label, editor, new_state, project_state)
        self.assertTableNotExists("%s_pony" % app_label) 
Example #7
Source File: graph.py    From python2017 with MIT License 6 votes vote down vote up
def make_state(self, nodes=None, at_end=True, real_apps=None):
        """
        Given a migration node or nodes, returns a complete ProjectState for it.
        If at_end is False, returns the state before the migration has run.
        If nodes is not provided, returns the overall most current project state.
        """
        if nodes is None:
            nodes = list(self.leaf_nodes())
        if len(nodes) == 0:
            return ProjectState()
        if not isinstance(nodes[0], tuple):
            nodes = [nodes]
        plan = []
        for node in nodes:
            for migration in self.forwards_plan(node):
                if migration not in plan:
                    if not at_end and migration in nodes:
                        continue
                    plan.append(migration)
        project_state = ProjectState(real_apps=real_apps)
        for node in plan:
            project_state = self.nodes[node].mutate_state(project_state, preserve=False)
        return project_state 
Example #8
Source File: test_operations.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_install_soname(self):
        """
        Test we can load the 'metadata_lock_info' library.
        """
        assert not plugin_exists("metadata_lock_info")

        state = ProjectState()
        operation = InstallSOName("metadata_lock_info.so")
        assert operation.describe() == "Installs library metadata_lock_info.so"

        new_state = state.clone()
        with connection.schema_editor() as editor:
            operation.database_forwards("testapp", editor, state, new_state)
        assert plugin_exists("metadata_lock_info")

        new_state = state.clone()
        with connection.schema_editor() as editor:
            operation.database_backwards("testapp", editor, new_state, state)
        assert not plugin_exists("metadata_lock_info") 
Example #9
Source File: test_operations.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_install_plugin(self):
        """
        Test we can load the example plugin that every version of MySQL ships
        with.
        """
        assert not plugin_exists("metadata_lock_info")

        state = ProjectState()
        operation = InstallPlugin("metadata_lock_info", "metadata_lock_info.so")
        assert (
            operation.describe()
            == "Installs plugin metadata_lock_info from metadata_lock_info.so"
        )
        new_state = state.clone()
        with connection.schema_editor() as editor:
            operation.database_forwards("testapp", editor, state, new_state)

        assert plugin_exists("metadata_lock_info")

        new_state = state.clone()
        with connection.schema_editor() as editor:
            operation.database_backwards("testapp", editor, new_state, state)

        assert not plugin_exists("metadata_lock_info") 
Example #10
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_field_reloads_state_on_fk_target_changes(self):
        """
        If AlterField doesn't reload state appropriately, the second AlterField
        crashes on MySQL due to not dropping the PonyRider.pony foreign key
        constraint before modifying the column.
        """
        app_label = 'alter_alter_field_reloads_state_on_fk_target_changes'
        project_state = self.apply_operations(app_label, ProjectState(), operations=[
            migrations.CreateModel('Rider', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
            ]),
            migrations.CreateModel('Pony', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
                ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE)),
            ]),
            migrations.CreateModel('PonyRider', fields=[
                ('id', models.AutoField(primary_key=True)),
                ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE)),
            ]),
        ])
        project_state = self.apply_operations(app_label, project_state, operations=[
            migrations.AlterField('Rider', 'id', models.CharField(primary_key=True, max_length=99)),
            migrations.AlterField('Pony', 'id', models.CharField(primary_key=True, max_length=99)),
        ]) 
Example #11
Source File: graph.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def make_state(self, nodes=None, at_end=True, real_apps=None):
        """
        Given a migration node or nodes, returns a complete ProjectState for it.
        If at_end is False, returns the state before the migration has run.
        If nodes is not provided, returns the overall most current project state.
        """
        if nodes is None:
            nodes = list(self.leaf_nodes())
        if len(nodes) == 0:
            return ProjectState()
        if not isinstance(nodes[0], tuple):
            nodes = [nodes]
        plan = []
        for node in nodes:
            for migration in self.forwards_plan(node):
                if migration not in plan:
                    if not at_end and migration in nodes:
                        continue
                    plan.append(migration)
        project_state = ProjectState(real_apps=real_apps)
        for node in plan:
            project_state = self.nodes[node].mutate_state(project_state, preserve=False)
        return project_state 
Example #12
Source File: graph.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def make_state(self, nodes=None, at_end=True, real_apps=None):
        """
        Given a migration node or nodes, return a complete ProjectState for it.
        If at_end is False, return the state before the migration has run.
        If nodes is not provided, return the overall most current project state.
        """
        if nodes is None:
            nodes = list(self.leaf_nodes())
        if not nodes:
            return ProjectState()
        if not isinstance(nodes[0], tuple):
            nodes = [nodes]
        plan = self._generate_plan(nodes, at_end)
        project_state = ProjectState(real_apps=real_apps)
        for node in plan:
            project_state = self.nodes[node].mutate_state(project_state, preserve=False)
        return project_state 
Example #13
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_field_reloads_state_on_fk_target_changes(self):
        """
        If AlterField doesn't reload state appropriately, the second AlterField
        crashes on MySQL due to not dropping the PonyRider.pony foreign key
        constraint before modifying the column.
        """
        app_label = 'alter_alter_field_reloads_state_on_fk_target_changes'
        project_state = self.apply_operations(app_label, ProjectState(), operations=[
            migrations.CreateModel('Rider', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
            ]),
            migrations.CreateModel('Pony', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
                ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE)),
            ]),
            migrations.CreateModel('PonyRider', fields=[
                ('id', models.AutoField(primary_key=True)),
                ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE)),
            ]),
        ])
        project_state = self.apply_operations(app_label, project_state, operations=[
            migrations.AlterField('Rider', 'id', models.CharField(primary_key=True, max_length=99)),
            migrations.AlterField('Pony', 'id', models.CharField(primary_key=True, max_length=99)),
        ]) 
Example #14
Source File: migrator.py    From django-test-migrations with MIT License 6 votes vote down vote up
def apply_initial_migration(self, targets: MigrationSpec) -> ProjectState:
        """Reverse back to the original migration."""
        targets = normalize(targets)

        style = no_style()
        # start from clean database state
        sql.drop_models_tables(self._database, style)
        sql.flush_django_migrations_table(self._database, style)

        # prepare as broad plan as possible based on full plan
        self._executor.loader.build_graph()  # reload
        full_plan = self._executor.migration_plan(
            self._executor.loader.graph.leaf_nodes(),
            clean_start=True,
        )
        plan = truncate_plan(targets, full_plan)

        # apply all migrations from generated plan on clean database
        # (only forward, so any unexpected migration won't be applied)
        # to restore database state before tested migration
        return self._migrate(targets, plan=plan) 
Example #15
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_rename_model_state_forwards(self):
        """
        RenameModel operations shouldn't trigger the caching of rendered apps
        on state without prior apps.
        """
        state = ProjectState()
        state.add_model(ModelState('migrations', 'Foo', []))
        operation = migrations.RenameModel('Foo', 'Bar')
        operation.state_forwards('migrations', state)
        self.assertNotIn('apps', state.__dict__)
        self.assertNotIn(('migrations', 'foo'), state.models)
        self.assertIn(('migrations', 'bar'), state.models)
        # Now with apps cached.
        apps = state.apps
        operation = migrations.RenameModel('Bar', 'Foo')
        operation.state_forwards('migrations', state)
        self.assertIs(state.apps, apps)
        self.assertNotIn(('migrations', 'bar'), state.models)
        self.assertIn(('migrations', 'foo'), state.models) 
Example #16
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_rename_field_reloads_state_on_fk_target_changes(self):
        """
        If RenameField doesn't reload state appropriately, the AlterField
        crashes on MySQL due to not dropping the PonyRider.pony foreign key
        constraint before modifying the column.
        """
        app_label = 'alter_rename_field_reloads_state_on_fk_target_changes'
        project_state = self.apply_operations(app_label, ProjectState(), operations=[
            migrations.CreateModel('Rider', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
            ]),
            migrations.CreateModel('Pony', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
                ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE)),
            ]),
            migrations.CreateModel('PonyRider', fields=[
                ('id', models.AutoField(primary_key=True)),
                ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE)),
            ]),
        ])
        project_state = self.apply_operations(app_label, project_state, operations=[
            migrations.RenameField('Rider', 'id', 'id2'),
            migrations.AlterField('Pony', 'id', models.CharField(primary_key=True, max_length=99)),
        ], atomic=connection.features.supports_atomic_references_rename) 
Example #17
Source File: graph.py    From bioforum with MIT License 6 votes vote down vote up
def make_state(self, nodes=None, at_end=True, real_apps=None):
        """
        Given a migration node or nodes, return a complete ProjectState for it.
        If at_end is False, return the state before the migration has run.
        If nodes is not provided, return the overall most current project state.
        """
        if nodes is None:
            nodes = list(self.leaf_nodes())
        if len(nodes) == 0:
            return ProjectState()
        if not isinstance(nodes[0], tuple):
            nodes = [nodes]
        plan = []
        for node in nodes:
            for migration in self.forwards_plan(node):
                if migration not in plan:
                    if not at_end and migration in nodes:
                        continue
                    plan.append(migration)
        project_state = ProjectState(real_apps=real_apps)
        for node in plan:
            project_state = self.nodes[node].mutate_state(project_state, preserve=False)
        return project_state 
Example #18
Source File: graph.py    From python with Apache License 2.0 6 votes vote down vote up
def make_state(self, nodes=None, at_end=True, real_apps=None):
        """
        Given a migration node or nodes, returns a complete ProjectState for it.
        If at_end is False, returns the state before the migration has run.
        If nodes is not provided, returns the overall most current project state.
        """
        if nodes is None:
            nodes = list(self.leaf_nodes())
        if len(nodes) == 0:
            return ProjectState()
        if not isinstance(nodes[0], tuple):
            nodes = [nodes]
        plan = []
        for node in nodes:
            for migration in self.forwards_plan(node):
                if migration not in plan:
                    if not at_end and migration in nodes:
                        continue
                    plan.append(migration)
        project_state = ProjectState(real_apps=real_apps)
        for node in plan:
            project_state = self.nodes[node].mutate_state(project_state, preserve=False)
        return project_state 
Example #19
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rename_missing_field(self):
        state = ProjectState()
        state.add_model(ModelState('app', 'model', []))
        with self.assertRaisesMessage(FieldDoesNotExist, "app.model has no field named 'field'"):
            migrations.RenameField('model', 'field', 'new_field').state_forwards('app', state) 
Example #20
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_alter_field_reloads_state_on_fk_with_to_field_target_changes(self):
        """
        If AlterField doesn't reload state appropriately, the second AlterField
        crashes on MySQL due to not dropping the PonyRider.pony foreign key
        constraint before modifying the column.
        """
        app_label = 'alter_alter_field_reloads_state_on_fk_with_to_field_target_changes'
        project_state = self.apply_operations(app_label, ProjectState(), operations=[
            migrations.CreateModel('Rider', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
                ('slug', models.CharField(unique=True, max_length=100)),
            ]),
            migrations.CreateModel('Pony', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
                ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE, to_field='slug')),
                ('slug', models.CharField(unique=True, max_length=100)),
            ]),
            migrations.CreateModel('PonyRider', fields=[
                ('id', models.AutoField(primary_key=True)),
                ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE, to_field='slug')),
            ]),
        ])
        project_state = self.apply_operations(app_label, project_state, operations=[
            migrations.AlterField('Rider', 'slug', models.CharField(unique=True, max_length=99)),
            migrations.AlterField('Pony', 'slug', models.CharField(unique=True, max_length=99)),
        ]) 
Example #21
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rename_referenced_field_state_forward(self):
        state = ProjectState()
        state.add_model(ModelState('app', 'Model', [
            ('id', models.AutoField(primary_key=True)),
            ('field', models.IntegerField(unique=True)),
        ]))
        state.add_model(ModelState('app', 'OtherModel', [
            ('id', models.AutoField(primary_key=True)),
            ('fk', models.ForeignKey('Model', models.CASCADE, to_field='field')),
            ('fo', models.ForeignObject('Model', models.CASCADE, from_fields=('fk',), to_fields=('field',))),
        ]))
        operation = migrations.RenameField('Model', 'field', 'renamed')
        new_state = state.clone()
        operation.state_forwards('app', new_state)
        self.assertEqual(new_state.models['app', 'othermodel'].fields[1][1].remote_field.field_name, 'renamed')
        self.assertEqual(new_state.models['app', 'othermodel'].fields[1][1].from_fields, ['self'])
        self.assertEqual(new_state.models['app', 'othermodel'].fields[1][1].to_fields, ('renamed',))
        self.assertEqual(new_state.models['app', 'othermodel'].fields[2][1].from_fields, ('fk',))
        self.assertEqual(new_state.models['app', 'othermodel'].fields[2][1].to_fields, ('renamed',))
        operation = migrations.RenameField('OtherModel', 'fk', 'renamed_fk')
        new_state = state.clone()
        operation.state_forwards('app', new_state)
        self.assertEqual(new_state.models['app', 'othermodel'].fields[1][1].remote_field.field_name, 'renamed')
        self.assertEqual(new_state.models['app', 'othermodel'].fields[1][1].from_fields, ('self',))
        self.assertEqual(new_state.models['app', 'othermodel'].fields[1][1].to_fields, ('renamed',))
        self.assertEqual(new_state.models['app', 'othermodel'].fields[2][1].from_fields, ('renamed_fk',))
        self.assertEqual(new_state.models['app', 'othermodel'].fields[2][1].to_fields, ('renamed',)) 
Example #22
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_run_python_noop(self):
        """
        #24098 - Tests no-op RunPython operations.
        """
        project_state = ProjectState()
        new_state = project_state.clone()
        operation = migrations.RunPython(migrations.RunPython.noop, migrations.RunPython.noop)
        with connection.schema_editor() as editor:
            operation.database_forwards("test_runpython", editor, project_state, new_state)
            operation.database_backwards("test_runpython", editor, new_state, project_state) 
Example #23
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def make_project_state(self, model_states):
        "Shortcut to make ProjectStates from lists of predefined models"
        project_state = ProjectState()
        for model_state in model_states:
            project_state.add_model(model_state.clone())
        return project_state 
Example #24
Source File: test_hstore_autodetect.py    From django-postgres-extra with MIT License 5 votes vote down vote up
def _make_project_state(model_states):
    """Shortcut to make :see:ProjectState from a list of predefined models."""

    project_state = ProjectState()
    for model_state in model_states:
        project_state.add_model(model_state.clone())
    return project_state 
Example #25
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def set_up_test_model(self, force_raster_creation=False):
        test_fields = [
            ('id', models.AutoField(primary_key=True)),
            ('name', models.CharField(max_length=100, unique=True)),
            ('geom', fields.MultiPolygonField(srid=4326))
        ]
        if connection.features.supports_raster or force_raster_creation:
            test_fields += [('rast', fields.RasterField(srid=4326, null=True))]
        operations = [migrations.CreateModel('Neighborhood', test_fields)]
        self.current_state = self.apply_operations('gis', ProjectState(), operations) 
Example #26
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rename_m2m_model_after_rename_field(self):
        """RenameModel renames a many-to-many column after a RenameField."""
        app_label = 'test_rename_multiple'
        project_state = self.apply_operations(app_label, ProjectState(), operations=[
            migrations.CreateModel('Pony', fields=[
                ('id', models.AutoField(primary_key=True)),
                ('name', models.CharField(max_length=20)),
            ]),
            migrations.CreateModel('Rider', fields=[
                ('id', models.AutoField(primary_key=True)),
                ('pony', models.ForeignKey('test_rename_multiple.Pony', models.CASCADE)),
            ]),
            migrations.CreateModel('PonyRider', fields=[
                ('id', models.AutoField(primary_key=True)),
                ('riders', models.ManyToManyField('Rider')),
            ]),
            migrations.RenameField(model_name='pony', old_name='name', new_name='fancy_name'),
            migrations.RenameModel(old_name='Rider', new_name='Jockey'),
        ], atomic=connection.features.supports_atomic_references_rename)
        Pony = project_state.apps.get_model(app_label, 'Pony')
        Jockey = project_state.apps.get_model(app_label, 'Jockey')
        PonyRider = project_state.apps.get_model(app_label, 'PonyRider')
        # No "no such column" error means the column was renamed correctly.
        pony = Pony.objects.create(fancy_name='a good name')
        jockey = Jockey.objects.create(pony=pony)
        ponyrider = PonyRider.objects.create()
        ponyrider.riders.add(jockey) 
Example #27
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_create_ignore_swapped(self):
        """
        The CreateTable operation ignores swapped models.
        """
        operation = migrations.CreateModel(
            "Pony",
            [
                ("id", models.AutoField(primary_key=True)),
                ("pink", models.IntegerField(default=1)),
            ],
            options={
                "swappable": "TEST_SWAP_MODEL",
            },
        )
        # Test the state alteration (it should still be there!)
        project_state = ProjectState()
        new_state = project_state.clone()
        operation.state_forwards("test_crigsw", new_state)
        self.assertEqual(new_state.models["test_crigsw", "pony"].name, "Pony")
        self.assertEqual(len(new_state.models["test_crigsw", "pony"].fields), 2)
        # Test the database alteration
        self.assertTableNotExists("test_crigsw_pony")
        with connection.schema_editor() as editor:
            operation.database_forwards("test_crigsw", editor, project_state, new_state)
        self.assertTableNotExists("test_crigsw_pony")
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_crigsw", editor, new_state, project_state)
        self.assertTableNotExists("test_crigsw_pony") 
Example #28
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rename_missing_field(self):
        state = ProjectState()
        state.add_model(ModelState('app', 'model', []))
        with self.assertRaisesMessage(FieldDoesNotExist, "app.model has no field named 'field'"):
            migrations.RenameField('model', 'field', 'new_field').state_forwards('app', state) 
Example #29
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_run_python_noop(self):
        """
        #24098 - Tests no-op RunPython operations.
        """
        project_state = ProjectState()
        new_state = project_state.clone()
        operation = migrations.RunPython(migrations.RunPython.noop, migrations.RunPython.noop)
        with connection.schema_editor() as editor:
            operation.database_forwards("test_runpython", editor, project_state, new_state)
            operation.database_backwards("test_runpython", editor, new_state, project_state) 
Example #30
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_alter_field_reloads_state_on_fk_with_to_field_target_changes(self):
        """
        If AlterField doesn't reload state appropriately, the second AlterField
        crashes on MySQL due to not dropping the PonyRider.pony foreign key
        constraint before modifying the column.
        """
        app_label = 'alter_alter_field_reloads_state_on_fk_with_to_field_target_changes'
        project_state = self.apply_operations(app_label, ProjectState(), operations=[
            migrations.CreateModel('Rider', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
                ('slug', models.CharField(unique=True, max_length=100)),
            ]),
            migrations.CreateModel('Pony', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
                ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE, to_field='slug')),
                ('slug', models.CharField(unique=True, max_length=100)),
            ]),
            migrations.CreateModel('PonyRider', fields=[
                ('id', models.AutoField(primary_key=True)),
                ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE, to_field='slug')),
            ]),
        ])
        project_state = self.apply_operations(app_label, project_state, operations=[
            migrations.AlterField('Rider', 'slug', models.CharField(unique=True, max_length=99)),
            migrations.AlterField('Pony', 'slug', models.CharField(unique=True, max_length=99)),
        ])