pytest - 如何从 tmpdir_factory 读取文件

标签 pytest

给定一个固定装置,在临时目录中创建一个文件,如下所示:

conftest.py

@pytest.fixture(scope="session")
def manifest(tmpdir_factory):
    db_dir = tmpdir_factory.mktemp("artifact")
    db_fn = db_dir.join("xxx.db")
    db = os.path.join(db_fn.dirname, db_fn.basename)

是否可以在测试文件中打开并只读有问题的文件?

以下不起作用:

test_iface.py

def targets_to_try(tmpdir_factory):
    tmpdir_factory.getbasetemp().join("artifact/xxx.db")

因为 pytest 将临时目录重命名为 artifact0,所以 0 表示测试运行。

能否请您提供解决方案的建议?

最佳答案

如果你想在初始化后使用tempdir,从fixture返回路径:

#conftest.py

@pytest.fixture(scope="session")
def manifest(tmpdir_factory):
    db_dir = tmpdir_factory.mktemp("artifact")
    db_fn = db_dir.join("xxx.db")
    db = os.path.join(db_fn.dirname, db_fn.basename)
    return db

#test_iface.py

def targets_to_try(manifest):
    assert manifest.basename() == "xxx.db"

tmpdir 基本目录将随着每次测试运行而更改名称。如果要避免更改目录名称,则不应使用 tmpdir。使用常规目录。

关于pytest - 如何从 tmpdir_factory 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52414211/

相关文章:

python - 启动 py.test 后从请求的数据流中读取后无法访问正文

python-3.x - vscode pytest 测试发现因缺少环境变量而失败

python - 使用pytest的parametrize,如果一个测试用例失败,我如何跳过剩余的测试?

python-3.x - PyTest - 将模拟应用于所有测试

python - pytest 应该用于集成测试嵌入式系统吗?

python - 从 PYCHARM 运行时使 PYTEST 更安静

python - 使用 Flask 进行 pytest 无法找到模块

python - 如何参数化 Pytest fixture

python - 如何让 pytest 运行 doctests 以及正常的测试目录?

python - 如何自动重命名 Testrail 中的测试运行