问题描述
在单元测试中,我需要加载灯具,如下所示:
In unit tests I need to load fixtures, as below:
class TestQuestionBankViews(TestCase):
# Load fixtures
fixtures = ['qbank']
def setUp(self):
login = self.client.login(email="[email protected]",password="welcome")
def test_starting_an_exam_view(self):
candidate = Candidate.objects.get(email="[email protected]")
.......etc
def test_review_view(self):
self.assertTrue(True)
.........
def test_review_view2(self):
self.assertTrue(True)
.........
问题:
Problem:
固定装置正在为每个测试加载,即在 test_review_view , test_review_view2 之前等等,作为Dj每次测试后,ango会刷新数据库。
These fixtures are loading for every test, i.e. before test_review_view, test_review_view2, etc., as Django flushes the database after every test.
此行为导致测试需要很长时间才能完成。
This behaviour is causing tests to take a long time to complete.
如何防止这个冗余的夹具装载?
How can I prevent this redundant fixture loading?
有没有办法在 setUp
中加载灯具,并将其冲洗当测试类完成时,而不是在每个测试之间冲洗?
Is there a way to load fixtures in setUp
and flush them when the test class is finished, instead of flushing between every test?
推荐答案
使用和一些代码,你可以做你所要求的。使用django-nose,您可以拥有每个包,每个模块和每个类的设置和拆卸功能。这样可以将您的灯具加载到较高的设置功能中,并禁用django.test.TestCase在测试之间重置灯具。
Using django-nose and a bit of code, you can do exactly what you asked for. With django-nose, you can have per-package, per-module and per-class setup and teardown functions. That allows you to load your fixtures in one of the higher-up setup functions and disable the django.test.TestCase's resetting of the fixtures between tests.
这是一个例子测试文件:
Here is an example test file:
from django.test import TestCase
from django.core import management
def setup():
management.call_command('loaddata', 'MyFixture.json', verbosity=0)
def teardown():
management.call_command('flush', verbosity=0, interactive=False)
class MyTestCase(TestCase):
def _fixture_setup(self):
pass
def test_something(self):
self.assertEqual(1, 1)
通知该设置和拆卸在课外。该设置将在此文件中的所有测试类之前运行,拆分将在所有测试类之后运行。
Notice that setup and teardown are outside of the class. The setup will be run before all the test classes in this file, and the teardown will be run after all test classes.
在课堂内,您会注意到 def _fixture_setup(self)方法。这将覆盖在每次测试之间复位数据库的功能。
Inside the class, you will notice the def _fixture_setup(self) method. This overrides the function that resets the database in between each test.
请记住,如果您的测试写入数据库,这可能会使您的测试无效。所以需要为每个测试重新加载固件的任何其他测试应该放在不同的测试文件中。
Keep in mind that if your tests write anything to the database, this could invalidate your tests. So any other tests that need fixtures reloaded for each test should be put in a different test file.
这篇关于如何在django单元测试中仅加载一次固定装置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!