how to read a file from a tmpdir_factory

Viewed 1086

Given a fixture, that creates a file in a temp directory, like this:

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)

Is it possible to open and read-only the file in question inside a test file?

The following does not work:

test_iface.py

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

Because pytest renames the temp directory as artifact0, the 0 signifies the test run.

Could you please advise on the solution?

1 Answers

If you want to use the tempdir after initialization, return the path from 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 base directory will change name with each test run. If you want to avoid changing directory name, you should not use tmpdir. Use regular directory.

Related