Как избежать мутирования объектов из фиксированных областей видимости в PyTest? - PullRequest
0 голосов
/ 07 ноября 2018

Каков наилучший способ избежать побочных эффектов для объектов, возвращаемых из осветительных приборов области действия?

Мой рецепт заключается в том, чтобы обернуть осветитель с сессионной областью в прибор с функциональной сферой, который возвращает копию исходного объекта. Есть ли что-нибудь встроенное в 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)

1 Ответ

0 голосов
/ 08 ноября 2018

Вы должны вернуть объект функции копирования из фиксации input_df, не создавая его экземпляра:

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)

Этот пример кода работает на моей машине. test_df_2 тест не проходит в этом случае.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...