tayfun
tayfun

Reputation: 3135

How to share test run data between pytests?

I would like to share the data and expected failure as well between different pytest test files. Let me give an example. I'm testing a class A in test_a.py and class B in test_b.py. Interestingly these two classes need to be compatible with each other so I want to test them on the same data and also mark some of the data as xfail. How can I do this?

example data:

my_test_data = [
     ('test_data', 'expected_output'),
     pytest.mark.xfail(('another_test', 'failing_output')),
]

I can put this in a conftest.py and import it from the tests but an explicit import does not feel right.

Upvotes: 2

Views: 1935

Answers (1)

tayfun
tayfun

Reputation: 3135

I've fixed this by using params on a fixture which returns the testing data. If you put this into conftest.py file, you can use the fixture in the test files automatically. Here's an example:

# in conftest.py file
@pytest.fixture(params=my_test_data)
def my_test(request):
  return request.params

Having parameterized-data-returning fixture in conftest.py means you can use that data inside tests without importing it:

# in test files themselves
def test_whatever(my_test):
  # Do whatever you like with the test data
  print my_test[0]

Upvotes: 5

Related Questions