Python 在每次测试之前创建初始数据条目并刷新
我是Django中使用莴苣进行BDD开发的新手,但是,我需要帮助弄清楚如何为模型加载初始测试数据,以及如何在每次测试之前刷新它们 我认为最简单的出发点是看。对于“刷新”数据,我使用带有如下代码的Python 在每次测试之前创建初始数据条目并刷新,python,django,lettuce,Python,Django,Lettuce,我是Django中使用莴苣进行BDD开发的新手,但是,我需要帮助弄清楚如何为模型加载初始测试数据,以及如何在每次测试之前刷新它们 我认为最简单的出发点是看。对于“刷新”数据,我使用带有如下代码的terrain.py: from django.db import transaction @before.each_feature def begin_transaction(feature): #shouldn't strictly be needed, but I've gotten
terrain.py
:
from django.db import transaction
@before.each_feature
def begin_transaction(feature):
#shouldn't strictly be needed, but I've gotten
#inconsistent results without it
transaction.rollback()
transaction.set_autocommit(False)
@after.each_feature
def end_transaction(feature):
transaction.rollback()
@before.each_scenario
def load_scenario_fixture(scenario):
call_command('loaddata', 'lettuce_global', interactive=False, verbosity=0)
fixture_path = os.path.join(scenario.feature.name.lower().replace(' ', '_'), scenario.name.lower().replace(' ', '_'))
logger.info("Loading fixture:")
logger.info(" " + fixture_path)
call_command('loaddata', fixture_path, interactive=False, verbosity=0)
@after.each_scenario
def flush_database(scenario):
logger.info("Flushing the test database ...")
call_command('flush', interactive=False, verbosity=0)
在每个场景之前使用可能更合适。使用适合你的工具。我有以下几点:
from django.db import transaction
@before.each_feature
def begin_transaction(feature):
#shouldn't strictly be needed, but I've gotten
#inconsistent results without it
transaction.rollback()
transaction.set_autocommit(False)
@after.each_feature
def end_transaction(feature):
transaction.rollback()
@before.each_scenario
def load_scenario_fixture(scenario):
call_command('loaddata', 'lettuce_global', interactive=False, verbosity=0)
fixture_path = os.path.join(scenario.feature.name.lower().replace(' ', '_'), scenario.name.lower().replace(' ', '_'))
logger.info("Loading fixture:")
logger.info(" " + fixture_path)
call_command('loaddata', fixture_path, interactive=False, verbosity=0)
@after.each_scenario
def flush_database(scenario):
logger.info("Flushing the test database ...")
call_command('flush', interactive=False, verbosity=0)
这将在每个场景之前加载一个全局测试夹具,也将加载该场景的一个特定夹具。夹具文件路径的格式为{app}/fixtures/{feature name}/{fixture name}
场景完成后,我只需使用Django flush命令进行重置。transaction.set\u autocommit在Django 1.5上不可用。