Pytest - 保留文件 b/w 测试的新副本,从磁盘读取一次

Pytest - preserve a fresh copy of a file b/w tests, read from disk once

我想从文件中读取一个大 pandas 数据帧,然后将其作为夹具发送到我 运行 的每个测试。我想要从内存中获取原始 df 的新版本,而不是从磁盘读取。

像这样:

import pytest

# <something here>
...
df = pd.read_csv("data.csv)
...

def test_1(df_fixture):
  assert len(df_fixture) == 1_000_000

def test_2(df_fixture):
  # Want a fresh df, without reading from disk again 
  assert sum(df_fixture["col1]) == 10_000_000


您可以将主 df 放在 scope=session 的 fixture 中,并将副本放在另一个 scope=function 的 fixture 中。在测试中调用 copy

的 fixture
import pandas as pd
import pytest


@pytest.fixture(scope="session")
def get_main_df():
    yield pd.read_csv("data.csv")


@pytest.fixture
def get_df_copy(get_main_df):
    yield get_main_df.copy(deep=True)


def test_1(get_df_copy):
  assert len(get_df_copy) == 1_000_000

def test_2(get_df_copy):
  assert sum(get_df_copy["col1"]) == 10_000_000