Ryan
Ryan

Reputation: 21

Pass variable(s) to dependent tests in pytest

I am currently using the pytest-dependency plugin for pytest to define test dependencies.

I am having trouble understanding how to pass values to a dependent tests. Below is an example of what I'd like to do. I'd like to use the job produced in test_one in the test_two function.

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

Upvotes: 2

Views: 871

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16815

Generally, it is not a good idea to have tests depend on each other, so if you can refactor your tests to avoid this, that would be the best solution.

That being said, dependent tests are often used due to performance issues, so if create_job takes a lot of time, it makes sense to run it only once. This can best be done by using a module- or session-scoped fixture:

@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

This way, the tests are still dependent (the second test doesn't make sense if the first one failed), but create_job is called only once and you don't have direct test dependencies.

Upvotes: 2

Related Questions