Каков наилучший способ избежать побочных эффектов для объектов, возвращаемых из осветительных приборов области действия?
Мой рецепт заключается в том, чтобы обернуть осветитель с сессионной областью в прибор с функциональной сферой, который возвращает копию исходного объекта. Есть ли что-нибудь встроенное в PyTest для этого? Может, какой-нибудь декоратор?
import pytest
from pandas import read_csv
@pytest.fixture(scope='session')
def _input_df():
"""Computationally expensive fixture, so runs once per test session.
As an example we read in a CSV file 5000 rows, 26 columns into a pandas.DataFrame
"""
df = read_csv('large-file.csv')
return df
@pytest.fixture(scope='function')
def input_df(_input_df):
""""This is a function-scoped fixture, which wraps around the session-scoped one
to make a copy of its result."""
return _input_df.copy()
def test_df_1(input_df):
"""Inadvertently, this test mutates the object from the input_df fixture"""
# adding a new column
input_df['newcol'] = 0
# we now have 27 columns
assert input_df.shape == (5000, 27)
def test_df_2(input_df):
"""But since we are getting a copy or the original this test still passes"""
assert input_df.shape == (5000, 26)