Using fixtures for setup and teardown

The fixture functions can also provide a teardown capability as well as a setup capability. This relies on the lazy way generator functions work. Some example code for a fixture that does setup and teardown is as follows:

@fixture
def damaged_file_path():
file_path = Path.cwd() / "data" / "ch17_sample.csv"
with file_path.open("w", newline="") as target:
print("not_player,bet,rounds,final", file=target)
print("data,1,1,1", file=target)
yield file_path
file_path.unlink()

The damaged_file_path() function creates a file with a relative path of data/ch17_sample.csv. A few lines of data are written to the file.

The yield statement provides an initial result value. This is used by a test function. When the test completes, then a second value is retrieved from the fixture. When this second result is requested, the fixture function can do any teardown work that is required. In this example, the teardown work deletes the test file that was created.

The fixture function will be called implicitly when the test is run. Here is an example test that uses this fixture:

def test_damaged(damaged_file_path):
with raises(AssertionError):
stats = rounds_final(Path.cwd()/"data"/"ch17_sample.csv")

This test confirms that the rounds_final() function, when given the example file, will raise AssertionError. Because the damaged_file_path fixture uses yield, it can tear down the test context, removing the file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset