python - 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"""
有人可以帮忙吗?谢谢
解决方案
tmpdir_factory
夹具方法返回一个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
back to创建的路径str
通常是使用此夹具的方法。
推荐阅读
- python - IndexError:Python 升级后布尔数组不再匹配
- javascript - 将画布图像从js提取到烧瓶,但图像的背景变成白色透明
- php - CodeIgniter 中的 SQL Server 2005 连接
- amazon-web-services - 使用无服务器脚本而不是 UI 将 API 网关作为触发器添加到 Lambda 函数
- jasper-reports - 表格 columnFooter 中的文本打印在每一页
- json - 在 Go 中解组类似表的 JSON
- java - 如何在游戏中实现图形而不是使用像素点?
- c++ - 如何输出到子目录中的文件?
- python - 使用 bs4 更改属性值后更新网站
- sql - 检查列是否具有重复自身的单个值