1
1
""" support for providing temporary directories to test functions. """
2
2
import pytest , py
3
+ from _pytest .monkeypatch import monkeypatch
3
4
4
- def pytest_configure (config ):
5
- def ensuretemp (string , dir = 1 ):
5
+ class TempdirHandler :
6
+ def __init__ (self , config ):
7
+ self .config = config
8
+ self .trace = config .trace .get ("tmpdir" )
9
+
10
+ def ensuretemp (self , string , dir = 1 ):
6
11
""" (deprecated) return temporary directory path with
7
12
the given string as the trailing part. It is usually
8
- better to use the 'tmpdir' function argument which will
9
- take care to provide empty unique directories for each
10
- test call even if the test is called multiple times .
13
+ better to use the 'tmpdir' function argument which
14
+ provides an empty unique-per-test-invocation directory
15
+ and is guaranteed to be empty .
11
16
"""
12
17
#py.log._apiwarn(">1.1", "use tmpdir function argument")
13
- return config .ensuretemp (string , dir = dir )
14
- pytest .ensuretemp = ensuretemp
18
+ return self .getbasetemp ().ensure (string , dir = dir )
19
+
20
+ def mktemp (self , basename , numbered = True ):
21
+ basetemp = self .getbasetemp ()
22
+ if not numbered :
23
+ p = basetemp .mkdir (basename )
24
+ else :
25
+ p = py .path .local .make_numbered_dir (prefix = basename ,
26
+ keep = 0 , rootdir = basetemp , lock_timeout = None )
27
+ self .trace ("mktemp" , p )
28
+ return p
29
+
30
+ def getbasetemp (self ):
31
+ """ return base temporary directory. """
32
+ try :
33
+ return self ._basetemp
34
+ except AttributeError :
35
+ basetemp = self .config .option .basetemp
36
+ if basetemp :
37
+ basetemp = py .path .local (basetemp )
38
+ if basetemp .check ():
39
+ basetemp .remove ()
40
+ basetemp .mkdir ()
41
+ else :
42
+ basetemp = py .path .local .make_numbered_dir (prefix = 'pytest-' )
43
+ self ._basetemp = t = basetemp
44
+ self .trace ("new basetemp" , t )
45
+ return t
46
+
47
+ def finish (self ):
48
+ self .trace ("finish" )
49
+
50
+ def pytest_configure (config ):
51
+ config ._mp = mp = monkeypatch ()
52
+ t = TempdirHandler (config )
53
+ mp .setattr (config , '_tmpdirhandler' , t , raising = False )
54
+ mp .setattr (pytest , 'ensuretemp' , t .ensuretemp , raising = False )
55
+
56
+ def pytest_unconfigure (config ):
57
+ config ._tmpdirhandler .finish ()
58
+ config ._mp .undo ()
15
59
16
60
def pytest_funcarg__tmpdir (request ):
17
61
"""return a temporary directory path object
@@ -22,5 +66,6 @@ def pytest_funcarg__tmpdir(request):
22
66
"""
23
67
name = request ._pyfuncitem .name
24
68
name = py .std .re .sub ("[\W]" , "_" , name )
25
- x = request .config .mktemp (name , numbered = True )
69
+ x = request .config ._tmpdirhandler . mktemp (name , numbered = True )
26
70
return x .realpath ()
71
+
0 commit comments