Data Driven Test in pytest – fixture
Fixture is definitely a shining point of pytest. It uses annotation @pytest.fixture to put in front of a method. In Python function can be used as parameter of another function. Thus when a function with @pytest.fixture is used as parameter for a test method, the return value of that function will be transferred to the test method. This is independent injection.
Take following as example:
@pytest.fixture
def get_test_data():
try:
test_data = pd.read_csv("test_data.csv", usecols=["firstName", "middleName", "lastName"])
logging.info(test_data)
tuples = [tuple(x) for x in test_data.values]
logging.info(tuples)
return tuples
except FileNotFoundError as e:
errno, errstr = e.args
logging.error("FileNotFoundError {}: {}".format(errno, errstr))
logging.error(e)
except:
logging.error("Unexpected error:", sys.exc_info()[0])
raise
finally:
logging.info("this section will always be executed...")
def test_datadriven(get_test_data):
test_data = get_test_data
print(test_data)
Of course, in real project, we should avoid write these two methods in a single file — each file should ONLY do one thing. We normally put that get_test_data() function in a seperate file named conftest.py. Of course we may define various test data getting methods in this file which can be reused by multiple test methods.
For fixtures can also be defined its usage scope, like some fixtures can be used for a specific module only.
Back To Homepage
Data Driven Test in pytest – parametization