首页 > 解决方案 > Pytest tmpdir_factory 抛出错误“预期的二进制或 unicode 字符串,获取本地”

问题描述

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"""

有人可以帮忙吗?谢谢

标签: pythonmachine-learningdata-sciencepytestfixtures

解决方案


tmpdir_factory夹具方法返回一个py.path.local对象,该对象封装了一个路径(有点类似于pathlib.Path)。因此,这些方法调用可以链接起来以操纵路径,就像在使用mktemp().join(). 要从结果中取回str路径,您必须显式地将其转换py.path.localstr

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

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


推荐阅读