如何避免在PyTest中从会话作用域fixture中改变对象?

2024-04-20 01:49:39 发布

您现在位置:Python中文网/ 问答频道 /正文

避免从会话范围的装置返回的对象产生副作用的最佳方法是什么?你知道吗

我的方法是用函数范围的fixture包装会话范围的fixture,该fixture返回原始对象的副本。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)

Tags: csvthe对象方法testimportdfread
1条回答
网友
1楼 · 发布于 2024-04-20 01:49:39

您应该从input返回copy function对象,而不实例化它:

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 test失败。你知道吗

相关问题 更多 >