如何从tmpdir_factory读取文件

时间:2018-09-19 21:05:02

标签: pytest

给出一个夹具,该夹具在temp目录中创建一个文件,如下所示:

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表示测试运行。

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

1 个答案:

答案 0 :(得分:1)

如果要在初始化后使用临时目录,请返回夹具的路径:

#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。使用常规目录。

相关问题