1
""" support for providing temporary directories to test functions. """
6
from _pytest.monkeypatch import MonkeyPatch
10
"""Factory for temporary directories under the common base temp directory.
12
The base directory can be configured using the ``--basetemp`` option.
15
def __init__(self, config):
17
self.trace = config.trace.get("tmpdir")
19
def ensuretemp(self, string, dir=1):
20
""" (deprecated) return temporary directory path with
21
the given string as the trailing part. It is usually
22
better to use the 'tmpdir' function argument which
23
provides an empty unique-per-test-invocation directory
24
and is guaranteed to be empty.
26
#py.log._apiwarn(">1.1", "use tmpdir function argument")
27
return self.getbasetemp().ensure(string, dir=dir)
29
def mktemp(self, basename, numbered=True):
30
"""Create a subdirectory of the base temporary directory and return it.
31
If ``numbered``, ensure the directory is unique by adding a number
32
prefix greater than any existing one.
34
basetemp = self.getbasetemp()
36
p = basetemp.mkdir(basename)
38
p = py.path.local.make_numbered_dir(prefix=basename,
39
keep=0, rootdir=basetemp, lock_timeout=None)
40
self.trace("mktemp", p)
43
def getbasetemp(self):
44
""" return base temporary directory. """
47
except AttributeError:
48
basetemp = self.config.option.basetemp
50
basetemp = py.path.local(basetemp)
55
temproot = py.path.local.get_temproot()
58
# use a sub-directory in the temproot to speed-up
59
# make_numbered_dir() call
60
rootdir = temproot.join('pytest-of-%s' % user)
64
basetemp = py.path.local.make_numbered_dir(prefix='pytest-',
66
self._basetemp = t = basetemp.realpath()
67
self.trace("new basetemp", t)
75
"""Return the current user name, or None if getuser() does not work
76
in the current environment (see #1010).
80
return getpass.getuser()
81
except (ImportError, KeyError):
85
# backward compatibility
86
TempdirHandler = TempdirFactory
89
def pytest_configure(config):
90
"""Create a TempdirFactory and attach it to the config object.
92
This is to comply with existing plugins which expect the handler to be
93
available at pytest_configure time, but ideally should be moved entirely
94
to the tmpdir_factory session fixture.
97
t = TempdirFactory(config)
98
config._cleanup.extend([mp.undo, t.finish])
99
mp.setattr(config, '_tmpdirhandler', t, raising=False)
100
mp.setattr(pytest, 'ensuretemp', t.ensuretemp, raising=False)
103
@pytest.fixture(scope='session')
104
def tmpdir_factory(request):
105
"""Return a TempdirFactory instance for the test session.
107
return request.config._tmpdirhandler
111
def tmpdir(request, tmpdir_factory):
112
"""Return a temporary directory path object
113
which is unique to each test function invocation,
114
created as a sub directory of the base temporary
115
directory. The returned object is a `py.path.local`_
118
name = request.node.name
119
name = re.sub("[\W]", "_", name)
121
if len(name) > MAXVAL:
123
x = tmpdir_factory.mktemp(name, numbered=True)