python - Django 测试 : How to start a background process that can access the test database?

标签 python django python-unittest

我正在尝试使用 django 测试框架编写测试,该测试生成了一个可以访问测试数据库的新后台进程。测试看起来像这样,

temp_project/temp_app/tests.py

import subprocess
from django.test import TestCase                                                                                                                    
from temp_app.models import TempModel

# Create your tests here.                                                                                                                             

class TempTest(TestCase):

    def setUp(self):
        TempModel.objects.create()

    def test_main(self):

        self.assertEqual(str(TempModel.objects.all()) + '\n',
                     subprocess.check_output(['python', 'manage.py', 'temp_command']))

子进程只是打印出数据库的内容,temp_project/temp_app/management/commands/temp_command.py

from temp_app.models import TempModel
from django.core.management.base import BaseCommand

class Command(BaseCommand):

    def handle(self, *args, **kwargs):
        print TempModel.objects.all()

模型是一个空的占位符,temp_project/temp_app/models.py

from django.db import models

# Create your models here.                                                                                                                            
class TempModel(models.Model):
    pass

但是测试的输出看起来像,

> python manage.py test
Creating test database for alias 'default'...
F
======================================================================
FAIL: test_main (temp_app.tests.TempTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/dvoong/projects/opentrv/ors/source/temp/temp_project/temp_app/tests.py", line 15, in test_main
    subprocess.check_output(['python', 'manage.py', 'temp_command']))
AssertionError: '[<TempModel: TempModel object>]\n' != '[]\n'

----------------------------------------------------------------------
Ran 1 test in 0.285s

FAILED (failures=1)
Destroying test database for alias 'default'...

所以看起来子进程正在访问生产数据库而不是测试数据库。有任何想法吗?数据库设置是,默认值,

DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

最佳答案

不使用测试数据库的子进程是预料之中的,因为您的子进程无论如何都没有运行测试命令。解决方案是创建一个新的设置文件,并使用 --settings 参数将其作为参数传递给您的子进程。当然,这个新的设置文件应该指向测试数据库。

关于python - Django 测试 : How to start a background process that can access the test database?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32081544/

相关文章:

python - 单元测试 __main__.py

python - 替代合并排序的效率?

python - 使用 python3.7 修剪列表中的链接

python - 在 win32 中读取符号链接(symbolic link)/连接点的目标(通过 Python)

python - Django查询ORM根据主键进行查询,然后从外键链接的联结表中获取信息

Django CSRF 错误 : Only on local runserver

django-object-permissions 与 django-guardian 与 django-authority

python unittest "X tests run"数字从哪里来?

python - 如何在 python 中修补模拟来自操作系统的多个调用?

django - 在 Django 中自定义单选按钮