4

我正在尝试将 json 固定装置加载到 Python 2.6/Django 1.4 单元测试中。我可以在测试级别使用 Django 的 TestCase,但加载需要 8-10 秒(2M 的 json,不会变得更小)。因此,运行十几个测试真的很慢,我想只加载一次测试数据库。看起来它可能在 Python 2.6 中添加unittest2,但我还没有让它工作。

# Works, but takes eight seconds per test.
class BaseStuff(django.test.testcases.TestCase):
    fixtures = ['test_data']

    def setUp(self):
        # stuff
    def test_one(self):
        # stuff

# Doesn't work - but runs *really* fast.
class BaseStuff(unittest2.TestCase):
    @classmethod
    def setUpClass(cls):  # Added in unittest2
        fixtures = ['test_data']
        print "in setupClass()"  # Does print, so function is called.

尝试setupModule()也没有用。setup 函数肯定会被调用,但似乎并不支持fixture。

所以Django的TestCase会读取fixture,而unittest2的TestCase会在类/模块级别做事。有没有办法结合这个操作,并在类/模块级别读取固定装置?我尝试了多重继承,但无法让它加载数据。

更新:根据@robjohncox 的建议,此代码在模块级别:

from django.core import management
management.call_command('loaddata', 'test_data.json', verbosity=1, noinput=True)

似乎确实创建了一个数据库。但随后 Django 似乎为每个测试创建了另一个数据库(它是空的)。不知道如何告诉 TestCase 使用第一个 db(我尝试了 Django 和 unittest2 TestCase)。

4

2 回答 2

1

您可以通过自己在setUpClass方法中手动加载夹具数据来解决此问题 - 有一个 django 管理命令 ( loaddata ) 可以为您执行此操作,可以从代码中调用。正如您在示例中正确指出的那样,这需要是unittest2.TestCase.

于 2014-01-18T08:04:56.850 回答
0

As Django doc suggests, you can use the name of the DB in the name of the fixture, to load the data in a db:

So combining your suggestion and mine:

In your settings.py, you have this databases:

DATABASES = {'default': ..., 'legacy_db': ...}

Then you can load fixture to a db like this:

from django.core import management
management.call_command('loaddata', 'test_data.legacy_db.json', verbosity=1, noinput=True)

Reference: https://docs.djangoproject.com/en/dev/ref/django-admin/#database-specific-fixtures

于 2021-06-14T17:21:41.857 回答