1+ import importlib
12import os
23import shutil
3- from tempfile import mkdtemp
4+ import tempfile
45import pytest
56import numpy as np
67import py .path as pp
78
89NIPYPE_DATADIR = os .path .realpath (
910 os .path .join (os .path .dirname (__file__ ), "testing/data" )
1011)
11- temp_folder = mkdtemp ()
12- data_dir = os .path .join (temp_folder , "data" )
13- shutil .copytree (NIPYPE_DATADIR , data_dir )
12+ NIPYPE_TMPDIR = tempfile .mkdtemp ()
13+ TMP_DATADIR = os .path .join (NIPYPE_TMPDIR , "data" )
14+
15+
16+ def pytest_configure (config ):
17+ shutil .copytree (NIPYPE_DATADIR , TMP_DATADIR )
18+
19+ # Pytest uses gettempdir() to construct its tmp_paths, but the logic to get
20+ # `pytest-of-<user>/pytest-<n>` directories is contingent on not directly
21+ # configuring the `config.option.base_temp` value.
22+ # Instead of replicating that logic, inject a new directory into gettempdir()
23+ #
24+ # Use the discovered temp dir as a base, to respect user/system settings.
25+ if ' ' not in (base_temp := tempfile .gettempdir ()):
26+ new_base = os .path .join (base_temp , "nipype tmp" )
27+ os .makedirs (new_base , exist_ok = True )
28+ os .environ ['TMPDIR' ] = os .path .join (base_temp , "nipype tmp" )
29+ importlib .reload (tempfile )
30+ assert tempfile .gettempdir () == os .path .join (base_temp , "nipype tmp" )
31+
32+
33+ def pytest_unconfigure (config ):
34+ shutil .rmtree (NIPYPE_TMPDIR )
1435
1536
1637@pytest .fixture (autouse = True )
1738def add_np (doctest_namespace ):
1839 doctest_namespace ["np" ] = np
1940 doctest_namespace ["os" ] = os
2041 doctest_namespace ["pytest" ] = pytest
21- doctest_namespace ["datadir" ] = data_dir
42+ doctest_namespace ["datadir" ] = TMP_DATADIR
2243
2344
2445@pytest .fixture (scope = 'session' , autouse = True )
@@ -33,7 +54,7 @@ def _docdir(request):
3354 doctest_plugin = request .config .pluginmanager .getplugin ("doctest" )
3455 if isinstance (request .node , doctest_plugin .DoctestItem ):
3556 # Get the fixture dynamically by its name.
36- tmpdir = pp .local (data_dir )
57+ tmpdir = pp .local (TMP_DATADIR )
3758
3859 # Chdir only for the duration of the test.
3960 with tmpdir .as_cwd ():
@@ -42,8 +63,3 @@ def _docdir(request):
4263 else :
4364 # For normal tests, we have to yield, since this is a yield-fixture.
4465 yield
45-
46-
47- def pytest_unconfigure (config ):
48- # Delete temp folder after session is finished
49- shutil .rmtree (temp_folder )
0 commit comments