将变量传递给 pytest 中的依赖测试

时间:2021-06-10 15:03:15

标签: python pytest

我目前正在使用 pytest-dependency 插件为 pytest 定义测试依赖项。

我无法理解如何将值传递给相关测试。下面是我想做的一个例子。我想在 test_two 函数中使用 test_one 中生成的作业。

def test_one(fake_fixture):
    job = create_job()
    assert job.status == "COMPLETE"
    
@pytest.mark.dependeny(depends=["test_one"])
def test_two(fake_fixture):
    response = download_report(job)
    assert file.status_code == 200

1 个答案:

答案 0 :(得分:2)

一般来说,让测试相互依赖并不是一个好主意,所以如果你能重构你的测试以避免这种情况,那将是最好的解决方案。

话虽如此,由于性能问题,经常使用依赖测试,所以如果 create_job 需要很多时间,那么只运行一次是有意义的。这可以通过使用模块或会话范围的装置来最好地完成:

@pytest.fixture(scope="module")
def job():
    yield create_job()

def test_one(fake_fixture, job):
    assert job.status == "COMPLETE"
    
@pytest.mark.dependeny(depends=["test_one"])
def test_two(fake_fixture, job):
    response = download_report(job)
    assert file.status_code == 200

这样,测试仍然是依赖的(如果第一个测试失败,则第二个测试没有意义),但是 create_job 只被调用一次,并且您没有直接的测试依赖项。