【问题标题】:creating initial data entries and flushing before each test lettuce django在每个测试生菜 django 之前创建初始数据条目和刷新
【发布时间】:2014-02-23 09:02:50
【问题描述】:

我是在 Django 中使用生菜进行 BDD 开发的新手,但是,我需要帮助来弄清楚如何为我的模型加载初始测试数据,以及如何在每次测试之前刷新它们。

【问题讨论】:

    标签: python django lettuce


    【解决方案1】:

    我认为最简单的起点是查看http://lettuce.it/tutorial/tables.html。对于“刷新”数据,我使用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 可能更合适。使用适合您的。

    【讨论】:

    • transaction.set_autocommit 在 Django 1.5 上不可用。
    【解决方案2】:

    我有以下几点:

    @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 命令进行重置。

    【讨论】:

      猜你喜欢
      • 2014-03-17
      • 2013-05-25
      • 1970-01-01
      • 2020-08-30
      • 2022-10-25
      • 1970-01-01
      • 2011-06-14
      • 2011-02-15
      • 2016-11-10
      相关资源
      最近更新 更多