python - 如何避免在 PyTest 中从 session 范围固定装置中改变对象?

标签 python unit-testing pytest

避免对从 session 范围的固定装置返回的对象产生副作用的最佳方法是什么?

我的秘诀是用一个函数范围的 fixture 包装一个 session 范围的 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)

最佳答案

您应该从 input_df fixture 返回复制函数对象而不实例化它:

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 测试失败。

关于python - 如何避免在 PyTest 中从 session 范围固定装置中改变对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53193932/

相关文章:

python - 如何使用 tox 和 pytest 将单元测试限制在支持的平台上?

python - 无法使用 beautifulsoup 3 从 json 脚本中提取所有 URL

python - "Fatal Python error: (pygame parachute) Segmentation Fault"改变窗口时

c# - 如何等待元素加载到 selenium webdriver 中?

javascript - 在 QUnit 测试中获取 $httpBackend

python - 如何通过命令行将 firefox/chrome headless 模式传递给 pytest

Python pandas 从 csv 文件中读取列表数据类型的列表

Python - 如果我不知道扩展名,如何在文件夹中查找文件?

swift - 使用 SingleValueDecodingContainer 对 Decodable 的一致性进行单元测试

python - 如果一个测试失败,pytest 会跳过所有内容