コード例 #1
0
ファイル: tests.py プロジェクト: africa-contest-dev/django
 def delete_tables(self):
     "Deletes all model tables for our models for a clean test environment"
     cursor = connection.cursor()
     connection.disable_constraint_checking()
     for model in self.models:
         # Remove any M2M tables first
         for field in model._meta.local_many_to_many:
             with atomic():
                 try:
                     cursor.execute(connection.schema_editor().sql_delete_table % {
                         "table": connection.ops.quote_name(field.rel.through._meta.db_table),
                     })
                 except DatabaseError as e:
                     if any([s in str(e).lower() for s in self.no_table_strings]):
                         pass
                     else:
                         raise
         # Then remove the main tables
         with atomic():
             try:
                 cursor.execute(connection.schema_editor().sql_delete_table % {
                     "table": connection.ops.quote_name(model._meta.db_table),
                 })
             except DatabaseError as e:
                 if any([s in str(e).lower() for s in self.no_table_strings]):
                     pass
                 else:
                     raise
     connection.enable_constraint_checking()
コード例 #2
0
ファイル: tests.py プロジェクト: devunt/django
 def test_disable_constraint_checks_manually(self):
     """
     When constraint checks are disabled, should be able to write bad data without IntegrityErrors.
     """
     with transaction.atomic():
         # Create an Article.
         models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r)
         # Retrieve it from the DB
         a = models.Article.objects.get(headline="Test article")
         a.reporter_id = 30
         try:
             connection.disable_constraint_checking()
             a.save()
             connection.enable_constraint_checking()
         except IntegrityError:
             self.fail("IntegrityError should not have occurred.")
         transaction.set_rollback(True)
コード例 #3
0
 def test_disable_constraint_checks_manually(self):
     """
     When constraint checks are disabled, should be able to write bad data without IntegrityErrors.
     """
     with transaction.atomic():
         # Create an Article.
         models.Article.objects.create(headline="Test article",
                                       pub_date=datetime.datetime(
                                           2010, 9, 4),
                                       reporter=self.r)
         # Retrieve it from the DB
         a = models.Article.objects.get(headline="Test article")
         a.reporter_id = 30
         try:
             connection.disable_constraint_checking()
             a.save()
             connection.enable_constraint_checking()
         except IntegrityError:
             self.fail("IntegrityError should not have occurred.")
         transaction.set_rollback(True)
コード例 #4
0
    def delete_tables(self):
        "Deletes all model tables for our models for a clean test environment"
        with connection.cursor() as cursor:
            connection.disable_constraint_checking()
            table_names = connection.introspection.table_names(cursor)
            for model in self.models:
                # Remove any M2M tables first
                for field in model._meta.local_many_to_many:
                    with atomic():
                        tbl = field.rel.through._meta.db_table
                        if tbl in table_names:
                            cursor.execute(connection.schema_editor().sql_delete_table % {
                                "table": connection.ops.quote_name(tbl),
                            })

                            try:
                                sql = connection.ops.drop_sequence_sql(tbl)
                                cursor.execute(sql)
                            except Exception as e:
                                print("Can not delete sequence for %s" % tbl)

                            table_names.remove(tbl)

                # Then remove the main tables
                with atomic():
                    tbl = model._meta.db_table
                    if tbl in table_names:
                        cursor.execute(connection.schema_editor().sql_delete_table % {
                            "table": connection.ops.quote_name(tbl),
                        })

                        try:
                            sql = connection.ops.drop_sequence_sql(tbl)
                            cursor.execute(sql)
                        except Exception as e:
                            print("Can not delete sequence for %s" % tbl)

                        table_names.remove(tbl)

        connection.enable_constraint_checking()
コード例 #5
0
ファイル: tests.py プロジェクト: Hestros/django
 def delete_tables(self):
     "Deletes all model tables for our models for a clean test environment"
     cursor = connection.cursor()
     connection.disable_constraint_checking()
     table_names = connection.introspection.table_names(cursor)
     for model in self.models:
         # Remove any M2M tables first
         for field in model._meta.local_many_to_many:
             with atomic():
                 tbl = field.rel.through._meta.db_table
                 if tbl in table_names:
                     cursor.execute(connection.schema_editor().sql_delete_table % {
                         "table": connection.ops.quote_name(tbl),
                     })
                     table_names.remove(tbl)
         # Then remove the main tables
         with atomic():
             tbl = model._meta.db_table
             if tbl in table_names:
                 cursor.execute(connection.schema_editor().sql_delete_table % {
                     "table": connection.ops.quote_name(tbl),
                 })
                 table_names.remove(tbl)
     connection.enable_constraint_checking()
コード例 #6
0
ファイル: tests.py プロジェクト: vhermecz/django
 def delete_tables(self):
     "Deletes all model tables for our models for a clean test environment"
     cursor = connection.cursor()
     connection.disable_constraint_checking()
     table_names = connection.introspection.table_names(cursor)
     for model in self.models:
         # Remove any M2M tables first
         for field in model._meta.local_many_to_many:
             with atomic():
                 tbl = field.rel.through._meta.db_table
                 if tbl in table_names:
                     cursor.execute(connection.schema_editor().sql_delete_table % {
                         "table": connection.ops.quote_name(tbl),
                     })
                     table_names.remove(tbl)
         # Then remove the main tables
         with atomic():
             tbl = model._meta.db_table
             if tbl in table_names:
                 cursor.execute(connection.schema_editor().sql_delete_table % {
                     "table": connection.ops.quote_name(tbl),
                 })
                 table_names.remove(tbl)
     connection.enable_constraint_checking()
コード例 #7
0
    def set_up_test_model(self,
                          app_label,
                          second_model=False,
                          third_model=False,
                          related_model=False,
                          mti_model=False,
                          proxy_model=False,
                          unique_together=False,
                          options=False,
                          db_table=None,
                          index_together=False):
        """
        Creates a test model state and database table.
        """
        # Delete the tables if they already exist
        table_names = [
            # Start with ManyToMany tables
            '_pony_stables',
            '_pony_vans',
            # Then standard model tables
            '_pony',
            '_stable',
            '_van',
        ]
        tables = [(app_label + table_name) for table_name in table_names]
        with connection.cursor() as cursor:
            table_names = connection.introspection.table_names(cursor)
            connection.disable_constraint_checking()
            sql_delete_table = connection.schema_editor().sql_delete_table
            with transaction.atomic():
                for table in tables:
                    if table in table_names:
                        cursor.execute(
                            sql_delete_table %
                            {"table": connection.ops.quote_name(table)})
            connection.enable_constraint_checking()

        # Make the "current" state
        model_options = {
            "swappable": "TEST_SWAP_MODEL",
            "index_together": [["weight", "pink"]] if index_together else [],
            "unique_together": [["pink", "weight"]] if unique_together else [],
        }
        if options:
            model_options["permissions"] = [("can_groom", "Can groom")]
        if db_table:
            model_options["db_table"] = db_table
        operations = [
            migrations.CreateModel(
                "Pony",
                [
                    ("id", models.AutoField(primary_key=True)),
                    ("pink", models.IntegerField(default=3)),
                    ("weight", models.FloatField()),
                ],
                options=model_options,
            )
        ]
        if second_model:
            operations.append(
                migrations.CreateModel(
                    "Stable",
                    [
                        ("id", models.AutoField(primary_key=True)),
                    ],
                ))
        if third_model:
            operations.append(
                migrations.CreateModel(
                    "Van",
                    [
                        ("id", models.AutoField(primary_key=True)),
                    ],
                ))
        if related_model:
            operations.append(
                migrations.CreateModel(
                    "Rider",
                    [
                        ("id", models.AutoField(primary_key=True)),
                        ("pony", models.ForeignKey("Pony")),
                        ("friend", models.ForeignKey("self")),
                    ],
                ))
        if mti_model:
            operations.append(
                migrations.CreateModel(
                    "ShetlandPony",
                    fields=[
                        ('pony_ptr',
                         models.OneToOneField(
                             auto_created=True,
                             primary_key=True,
                             to_field='id',
                             serialize=False,
                             to='Pony',
                         )),
                        ("cuteness", models.IntegerField(default=1)),
                    ],
                    bases=['%s.Pony' % app_label],
                ))
        if proxy_model:
            operations.append(
                migrations.CreateModel(
                    "ProxyPony",
                    fields=[],
                    options={"proxy": True},
                    bases=['%s.Pony' % app_label],
                ))

        return self.apply_operations(app_label, ProjectState(), operations)
コード例 #8
0
 def tearDownClass(cls):
     super().tearDownClass()
     connection.enable_constraint_checking()
コード例 #9
0
    def set_up_test_model(
            self, app_label, second_model=False, third_model=False,
            related_model=False, mti_model=False, proxy_model=False,
            unique_together=False, options=False, db_table=None,
            index_together=False):
        """
        Creates a test model state and database table.
        """
        # Delete the tables if they already exist
        table_names = [
            # Start with ManyToMany tables
            '_pony_stables', '_pony_vans',
            # Then standard model tables
            '_pony', '_stable', '_van',
        ]
        tables = [(app_label + table_name) for table_name in table_names]
        with connection.cursor() as cursor:
            table_names = connection.introspection.table_names(cursor)
            connection.disable_constraint_checking()
            sql_delete_table = connection.schema_editor().sql_delete_table
            with transaction.atomic():
                for table in tables:
                    if table in table_names:
                        cursor.execute(sql_delete_table % {
                            "table": connection.ops.quote_name(table),
                        })
            connection.enable_constraint_checking()

        # Make the "current" state
        model_options = {
            "swappable": "TEST_SWAP_MODEL",
            "index_together": [["weight", "pink"]] if index_together else [],
            "unique_together": [["pink", "weight"]] if unique_together else [],
        }
        if options:
            model_options["permissions"] = [("can_groom", "Can groom")]
        if db_table:
            model_options["db_table"] = db_table
        operations = [migrations.CreateModel(
            "Pony",
            [
                ("id", models.AutoField(primary_key=True)),
                ("pink", models.IntegerField(default=3)),
                ("weight", models.FloatField()),
            ],
            options=model_options,
        )]
        if second_model:
            operations.append(migrations.CreateModel(
                "Stable",
                [
                    ("id", models.AutoField(primary_key=True)),
                ]
            ))
        if third_model:
            operations.append(migrations.CreateModel(
                "Van",
                [
                    ("id", models.AutoField(primary_key=True)),
                ]
            ))
        if related_model:
            operations.append(migrations.CreateModel(
                "Rider",
                [
                    ("id", models.AutoField(primary_key=True)),
                    ("pony", models.ForeignKey("Pony")),
                    ("friend", models.ForeignKey("self"))
                ],
            ))
        if mti_model:
            operations.append(migrations.CreateModel(
                "ShetlandPony",
                fields=[
                    ('pony_ptr', models.OneToOneField(
                        auto_created=True,
                        primary_key=True,
                        to_field='id',
                        serialize=False,
                        to='Pony',
                    )),
                    ("cuteness", models.IntegerField(default=1)),
                ],
                bases=['%s.Pony' % app_label],
            ))
        if proxy_model:
            operations.append(migrations.CreateModel(
                "ProxyPony",
                fields=[],
                options={"proxy": True},
                bases=['%s.Pony' % app_label],
            ))

        return self.apply_operations(app_label, ProjectState(), operations)
コード例 #10
0
 def tearDownClass(cls):
     super(TestMgmtCommands, cls).tearDownClass()
     connection.enable_constraint_checking()