【问题标题】:Django tests with schema - schema not foundDjango 使用模式测试 - 找不到模式
【发布时间】:2017-02-23 23:23:09
【问题描述】:

我在 django-cookiecutter 的项目设置中使用 Django 1.10.5。我有一个看起来像这样的非托管模型:

# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings


class MyModel(models.Model):
    """Base account model."""
    account_nm = models.CharField(max_length=255, blank=True, null=True,
                                  db_column='customer_nm')

    class Meta:
        app_label = 'mylabel'
        db_table = '"stage"."mytable"'
        managed = False if not settings.TESTING else True

托管设置旨在在我测试时创建我的表,但在其他情况下不会。我正在使用 django-pytest 运行我的测试,就像py.test --reuse-db 一样。我的后端是 django-redshift-backend 这个非托管模型的 Redshift。

如果我只使用db_table = 'mytable' 运行测试,我的表将成功地在我的测试数据库的public 模式中创建。如果我使用db_table 运行测试,如上图所示,我会收到一个错误。

E               django.db.utils.ProgrammingError: schema "myschema" does not exist
E               LINE 1: CREATE TABLE "myschema"."mytable" (....

在正常情况下,我可以在具有特定模式的应用程序中成功使用此模型。为什么我在测试时无法在我的架构中创建表?

【问题讨论】:

    标签: python django amazon-redshift


    【解决方案1】:

    我认为这是因为您尚未在 test_** 数据库中创建 stage 架构,而 stage 架构存在于您的“开发/生产”环境中。

    我按照以下步骤运行,终于成功运行单元测试 (假设数据库名称是app):

    1. 将数据库app 转储并复制到test_app
    2. 确保stage 架构是在test_app 下创建的,mytable 是在架构stage 下创建的。 (我已经临时打开managed选项并运行python migrate,这样我就可以让django为我创建mytable)
    3. 使用 django 单元测试命令运行:

      python manage.py test --keepdb  # --keepdb is available from django 1.8 and later.
      

    test.py

    from django.test import TestCase
    from app.models import MyModel
    
    
    class TestMyModel(TestCase):
    
        def testRetrieve(self):
            self.assertRaises(MyModel.objects.get(pk=1))
    

    pytest我没试过,但我觉得差不多。

    【讨论】:

    • 感谢您的回复。看起来我已经在我的测试数据库中创建了阶段模式。我在我的 DATABASES 设置中指定使用名为 test 的数据库进行测试。
    • @duffn 测试后数据库有可能掉线吗?
    • 我不这么认为。 --reuse-db 可以防止这种情况。
    • @duffn 你也可以显示你的测试的日志消息吗?
    • 测试的错误是E django.db.utils.ProgrammingError: schema "myschema" does not exist E LINE 1: CREATE TABLE "myschema"."mytable" (....
    猜你喜欢
    • 2011-10-20
    • 2015-12-04
    • 2014-04-10
    • 2015-09-29
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    相关资源
    最近更新 更多