...

/

Fixtures in pytest

Fixtures in pytest

Learn about fixtures and how to use them in your tests.

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]
Re-use data in multiple tests

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 ...

Access this course and 1400+ top-rated courses and projects.