Django单元测试失败了多个Postgres模式

Wal*_*r B 2 python django postgresql

我的Postgres DB有3个模式:default,cedirData和webData.

对于那些指向不同于默认模式的模型,我将其指定如下:

class Person(models.Model):
    first_name = models.CharField(max_length=200, null=False, blank=False)
    last_name = models.CharField(max_length=200, null=False, blank=False)

    class Meta:
        db_table = 'cedirData\".\"persons'
Run Code Online (Sandbox Code Playgroud)

该应用程序工作正常,但当我尝试运行测试时:

$ ./manage.py test
Run Code Online (Sandbox Code Playgroud)

我得到以下内容:

  File "/home/wbrunetti/.virtualenvs/cedir/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 160, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/home/wbrunetti/.virtualenvs/cedir/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 63, in migrate
    self.apply_migration(migration, fake=fake)
  File "/home/wbrunetti/.virtualenvs/cedir/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 97, in apply_migration
    migration.apply(project_state, schema_editor)
  File "/home/wbrunetti/.virtualenvs/cedir/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 107, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "/home/wbrunetti/.virtualenvs/cedir/local/lib/python2.7/site-packages/django/db/migrations/operations/models.py", line 36, in database_forwards
    schema_editor.create_model(model)
  File "/home/wbrunetti/.virtualenvs/cedir/local/lib/python2.7/site-packages/django/db/backends/schema.py", line 270, in create_model
    self.execute(sql, params)
  File "/home/wbrunetti/.virtualenvs/cedir/local/lib/python2.7/site-packages/django/db/backends/schema.py", line 98, in execute
    cursor.execute(sql, params)
  File "/home/wbrunetti/.virtualenvs/cedir/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/wbrunetti/.virtualenvs/cedir/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/wbrunetti/.virtualenvs/cedir/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: schema "cedirData" does not exist
Run Code Online (Sandbox Code Playgroud)

看起来它可能与迁移有关.由于数据库表已经存在,我刚刚创建了初始迁移并运行了--fake:

$ python manage.py makemigrations
$ ./manage.py migrate --fake
Run Code Online (Sandbox Code Playgroud)

仅使用默认架构创建测试DB.

我正在使用Django 1.7和Python 2.7.6.

任何想法或想法都会有所帮助.

谢谢!

Pre*_*ton 5

许多其他数据库引擎都没有使用模式.通过在模型中指定模式,您在postgres的代码中引入了依赖项.

您可以采取两种方式来解决问题;

首先,您可以为postgres用户添加默认搜索路径.这种方法的缺点是模式不能再用于命名空间,但优点是如果您的数据库更改为不同的引擎,您的代码将正常运行.命名表空间可以通过选择一些标准的表命名方式来实现,类似于Django默认的方式(例如appName_className)

有两种方法可以实现这一目标.以这种方式执行的postgres命令是:

ALTER USER (your user) SET search_path = "$user",(schema1),(schema2),(schema3),(...)
Run Code Online (Sandbox Code Playgroud)

django唯一的方法是:

# Warning! This is untested, I just glanced at the docs and it looks right.
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        # some configuration here
        'OPTIONS': {
            'options': '-c search_path=schema1,schema2,schema3'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你还想改变:

db_table = 'cedirData\".\"persons'
Run Code Online (Sandbox Code Playgroud)

至:

db_table = 'persons'
Run Code Online (Sandbox Code Playgroud)

作为奖励,您现在可以使用:

manage.py inspectdb > models.py
Run Code Online (Sandbox Code Playgroud)

这是一个很好的功能,这样您就不必手动复制现有数据库.

但是,如果架构命名空间在您的数据库上被大量使用而其他应用程序依赖于它,则此解决方案将无法帮助您.另一种方法是编写自定义testrunner以在测试数据库中创建这些模式.这比上述方法更复杂,并且可能有点混乱.我不建议这样做,但如果你感兴趣我可以尝试帮助.

一个不那么混乱,但更"笨拙"的方法是在运行测试时简单地覆盖元.这也是一个测试者.

from django.test.simple import DjangoTestSuiteRunner
from django.db.models.loading import get_models

class SchemaModelTestRunner(DjangoTestSuiteRunner):
    """Docstring"""
    def setup_test_environment(self, *args, **kwargs):
        self.original_db_tables = {}
        self.schema_models = [m for m in get_models()
                                 if '"."' in m._meta.db_table]
        for m in self.schema_models:
            schema, table = m._meta.db_table.split('"."')
            self.original_db_tables[m] = m._meta.db_table
            m._meta.db_table = 'schema_'+schema+'_table_'+table

        super(SchemaModelTestRunner, self).setup_test_environment(*args,
                                                                   **kwargs)
    def teardown_test_environment(self, *args, **kwargs):
        super(SchemaModelTestRunner, self).teardown_test_environment(*args,
                                                                      **kwargs)
        # reset models
        for m in self.schema_models:
            m._meta.db_table = self.original_db_tables[m]
Run Code Online (Sandbox Code Playgroud)

您还需要在settings.py文件中将其定义为testrunner.