'Best way to reuse test data in several pytest tests?

I need to run a number of tests using pytest. Several tests rely on data which must be read from a database, and which takes a while to retrieve. For this reason, I would like to construct a testing dataset once, then reuse it in several tests.

I would do something like the below to accomplish this. Is this a reasonable way to reuse testing data, or should I do something else?

from copy import deepcopy


def read_test_data():
    # Takes a while to run
    return test_data


reusable_test_data = read_test_data()


def get_test_data():
    # Using this helper method to make sure no test accidentally modifies the test data
    return deepcopy(reusable_test_data)


def test_foo():
    data = get_test_data()
    # Test something

def test_bar():
    data = get_test_data()
    # Test something else


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source