Pytest tmpdir_factory 抛出错误 "Expected binary or unicode string, got local"

Pytest tmpdir_factory threw an error "Expected binary or unicode string, got local"

我正在使用 pytest 对将数据拆分为机器学习问题的训练、验证、测试集进行测试。我使用 tmpdir_factory 创建临时文件,但它给我带来了类似 TypeError: Expected binary or unicode string, got local('/tmp/pytest/pytest-4/test_folder0/train.tfrecord') 的错误。这是我的代码:

里面 conftest.py:

DATA_FOLDER = 'test_folder'

@pytest.fixture(scope="session")
def train_dataset(tmpdir_factory):
    return tmpdir_factory.mktemp(DATA_FOLDER).join('train.tfrecord')

@pytest.fixture(scope="session")
def val_dataset(tmpdir_factory):
    return tmpdir_factory.mktemp(DATA_FOLDER).join('val.tfrecord')

@pytest.fixture(scope="session")
def test_dataset(tmpdir_factory):
    return tmpdir_factory.mktemp(DATA_FOLDER).join('test.tfrecord')

测试文件内:

def test_split(train_dataset, val_dataset, test_dataset):
    # the arguments of split_function refer to the path where the splitting results is written
    split_function(train_dataset, val_dataset, test_dataset)
    """continue with assert functions"""

有人可以帮忙吗?谢谢

tmpdir_factory fixture 方法 return 一个 py.path.local 对象,它封装了一个路径(有点类似于 pathlib.Path)。因此,可以将这些方法调用链接起来以操纵路径,就像在您的灯具中使用 mktemp().join() 所做的那样。要从结果中取回 str 路径,您必须明确地将 py.path.local 转换为 str:

@pytest.fixture(scope="session")
def train_dataset(tmpdir_factory):
    return str(tmpdir_factory.mktemp(DATA_FOLDER).join('train.tfrecord'))

由于您的测试函数不知道 py.path.local,将 tmpdir_factory 创建的路径转换回 str 通常是使用此夹具的方法。