自定义场景运行程序期间在第一次测试中刷新pytest固定装置

时间:2020-04-28 07:58:12

标签: python pytest

我为基于pytest的测试实现了scenario support,并且效果很好。

但是,我的固定装置之一使用干净的表初始化数据库,第二种方案使用脏的数据库运行测试。在后续场景中如何重新初始化或刷新数据库设备?

为清楚起见,我想看看这个:

  • 场景1
    • test_demo1得到一个新的数据库,测试将写入该数据库
    • test_demo2不会重新初始化数据库,但是会看到test_demo1所做的更改
  • 场景2
    • test_demo1再次获得一个新的数据库,测试将写入该数据库
    • test_demo2不会重新初始化数据库,而是仅在场景2中看到test_demo1所做的更改。
def pytest_runtest_setup(item):
    if hasattr(item.cls, "scenarios") and "first" in item.keywords:
        # what to do here?

@pytest.mark.usefixtures("db")
class TestSampleWithScenarios:
    scenarios = [scenario1, scenario2]

    @pytest.mark.first
    def test_demo1(self, db):
        # db is dirty here in scenario2
        pass

    def test_demo2(self, db):
        pass

我目前正在研究pytest的来源以找到答案,一旦有发现,我将在这里发布。

1 个答案:

答案 0 :(得分:1)

我找到了一种解决方法。进行一个常规测试,该测试使用DB夹具parametrize和场景,并直接在类中调用测试:

@pytest.mark.parametrize(["scenario"], scenarios)
def test_sample_with_scenarios(db, scenario):
    TestSampleWithScenarios().test_demo1(db, scenario)
    TestSampleWithScenarios().test_demo2(db, scenario)