django测试:如何启动可以访问测试数据库的后台进程?

时间:2015-08-18 19:57:12

标签: 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'),
    }
}

1 个答案:

答案 0 :(得分:1)

由于子进程未运行测试命令,因此可以预期不使用测试数据库的子进程。解决方案是创建一个新的设置文件,并使用--settings参数将其作为参数传递给您的子进程。当然,这个新的设置文件应该指向测试数据库。