Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read a file from a tmpdir_factory

Tags:

pytest

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?

like image 293
nskalis Avatar asked Nov 20 '25 08:11

nskalis


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.

like image 102
SilentGuy Avatar answered Nov 22 '25 02:11

SilentGuy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!