简体   繁体   中英

How to Dynamically Change pytest's tmpdir Base Directory

As per the pytest documentation , it possible to override the default temporary directory setting as follows:

py.test --basetemp=/base_dir

When the tmpdir fixture is then used in a test ...

def test_new_base_dir(tmpdir):
    print str(tmpdir)
    assert False

... something like the following would then be printed to the screen:

/base_dir/test_new_base_dir_0

This works as intended and for certain use cases can be very useful.

However, I would like to be able to change this setting on a per-test (or perhaps I should say a "per-fixture") basis. Is such a thing possible?

I'm close to just rolling my own tmpdir based on the code for the original , but would rather not do this -- I want to build on top of existing functionality where I can, not duplicate it.


As an aside, my particular use case is that I am writing a Python module that will act on different kinds of file systems (NFS4, etc), and it would be nice to be able to yield the functionality of tmpdir to be able to create the following fixtures:

def test_nfs3_stuff(nfs3_tmpdir):
    ... test NFS3 functionality

def test_nfs4_stuff(nfs4_tmpdir):
    ... test NFS4 functionality

There didn't appear to be a nice solution to the problem as posed in the question so I settled on making two calls to py.test :

  • Passing in a different --basetemp for each.
  • Marking (using @pytest.mark.my_mark ) which tests needed the special treatment of using a non-standard basetemp.
  • Passing -k my_mark or -k-my_mark into each call.

In the sources of TempdirFactory the .config.option.basetemp is used as the attribute to store the basetemp . So you can directly set it before the usage:

import pytest
import time
import os

def mktemp_db(tmpdir_factory, db):
    basetemp = None
    if 'PYTEST_TMPDIR' in os.environ:
        basetemp = os.environ['PYTEST_TMPDIR']
    if basetemp:
        tmpdir_factory.config.option.basetemp = basetemp
    if db == "db1.db":
        tmpdb = tmpdir_factory.mktemp('data1_').join(db)
    elif db == "db2.db":
        tmpdb = tmpdir_factory.mktemp('data2_').join(db)
    return tmpdb

@pytest.fixture(scope='session')
def empty_db(tmpdir_factory):
    tmpdb = mktemp_db(tmpdir_factory, 'db1.db')
    print("* " + str(tmpdb))
    time.sleep(5)
    return tmpdb

@pytest.fixture(scope='session')
def empty_db2(tmpdir_factory):
    tmpdb = mktemp_db(tmpdir_factory, 'db2.db')
    print("* " + str(tmpdb))
    time.sleep(5)
    return tmpdb

def test_empty_db(empty_db):
    pass

def test_empty_db2(empty_db2):
    pass

-

>set PYTEST_TMPDIR=./tmp
>python.exe -m pytest -q -s test_my_db.py
* c:\tests\tmp\data1_0\db1.db
.* c:\tests\tmp\data2_0\db2.db
.
2 passed in 10.03 seconds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM