Fixtures in pytest
Explore how pytest fixtures enable reusable test setup in machine learning projects. Learn to create consistent environments that improve test reliability and follow best practices for managing input data in ML testing.
We'll cover the following...
Overview
Fixtures are fixed environment items (usually function inputs and outputs) used in tests. Without fixtures, we do not separate test-case preparation logic from the test itself. Moreover, we’re probably creating almost the same test cases for different tests.
Let’s look at the code below where we add some images to our repository and use the crop_image function to crop an image.
from typing import Tuple
import numpy as np
def crop_image(img: np.ndarray, coords: Tuple[int, int, int, int]) -> np.ndarray:
x, y = coords[0], coords[1]
w, h = coords[2], coords[3]
return img[x:x+w, y:y+h]Another way to use fixtures is by passing them through the test’s arguments (which can only be either the fixture or the test’s parameter), while creating or loading fixtures separately by using the @pytest.fixture decorator.
Let’s demonstrate this on the same ...