测试只读表(Django)时表不存在

2024-09-30 08:19:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Django项目。这个项目中有两个数据库,我编写了一个Router来创建其中一个readonly。我已经编写了一些使用这个readonly数据库的单元测试,但是当我运行python manage.py test时,它说

ProgrammingError: (1146, "Table 'test_arzesh-db.company' doesn't exist")

以下是数据库的设置:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'broker-website',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'OPTIONS': {
            "init_command": "SET foreign_key_checks = 0;",
        },
    },
    'arzesh-db': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'arzesh-db',
        'USER': 'root',
        'PASSWORD': '',
        'TEST_DATABASE': 'default',
    },
    'TEST': {
        'CHARSET': 'utf8',
        'COALATION': 'utf8-unicode-ci',
    }
}

这是我的路由器的代码:

^{pr2}$

以下是只读数据库中的模型:

class Company(models.Model):
    def __unicode__(self):
        return self.tick

    id = models.AutoField(primary_key=True)
    tick = models.CharField(unique=True, max_length=32)
    name = models.CharField(max_length=128, unique=True)

    class Meta:
        managed = False
        db_table = 'company'

下面是在unittest中得到错误的一行:

company.objects.create(id=1, tick='a', name='a')

Tags: 项目djangotest数据库truedefaultdbmodels
1条回答
网友
1楼 · 发布于 2024-09-30 08:19:00

首先说这是不准确的

I've written some unit tests that use this readonly database

那是因为

Tests that require a database (namely, model tests) will not use your “real” (production) database. Separate, blank databases are created for the tests. ... The default test database names are created by prepending test_ to the value of each NAME in DATABASES

参考号:https://docs.djangoproject.com/en/1.9/topics/testing/overview/#the-test-database

错误是

ProgrammingError: (1146, "Table 'test_arzesh-db.company' doesn't exist")

对,那么测试数据库是如何创建的呢?基于您迁移的内容。但你有

    class Meta:
        managed = False
        db_table = 'company'

这里的managed = False表示不会创建迁移,因此该表将不存在于测试数据库中。因此出现了错误。在

解决方案。 使用创建此表的RunSQL手动添加迁移。为此,请使用SHOW CREATE TABLE company中的SQL。先这么做

^{pr2}$

编辑新创建的迁移文件,将RunPython或RunSQL代码添加到其中。传递给RunSQL的SQL是由mysql控制台中的SHOW CREATE TBABLE company生成的SQL。请参考RunSQL文档以获取更多信息和示例。在

相关问题 更多 >

    热门问题