Repository: joblib/joblib
Pull request #463 (2016-12-15 10:04:05)

[MRG] Replace manual setup / teardown of temp directory with 'tmpdir' fixture.
#### Fourth Phase PR on #411 (Succeeding PR #461 )

Several modules declare a setup and teardown where a temporary directory was created and its path was set as a global variable. Creation and deletion of this directory was handled manually while setup and teardown. This has been replaced by pytest's `tmpdir` fixture.

It is a `py.path.local` object, and has to be specified as a parameter in tests requiring a temporary directory.

karandesai-96: @lesteve please have a round of reviews as per convenience. Github says it has added "Request to Review" feature on PRs but I can't find anything here on this interface. :confused: 

Patch:
diff --git a/joblib/format_stack.py b/joblib/format_stack.py
index 3f3d106..4be93c1 100644
--- a/joblib/format_stack.py
+++ b/joblib/format_stack.py
@@ -135,15 +135,10 @@ def _fixed_getframes(etb, context=1, tb_offset=0):
     aux = traceback.extract_tb(etb)
     assert len(records) == len(aux)
     for i, (file, lnum, _, _) in enumerate(aux):
-        maybeStart = lnum - 1 - context // 2
-        start = max(maybeStart, 0)
+        maybe_start = lnum - 1 - context // 2
+        start = max(maybe_start, 0)
         end = start + context
         lines = linecache.getlines(file)[start:end]
-        # pad with empty lines if necessary
-        if maybeStart < 0:
-            lines = (['\n'] * -maybeStart) + lines
-        if len(lines) < context:
-            lines += ['\n'] * (context - len(lines))
         buf = list(records[i])
         buf[LNUM_POS] = lnum
         buf[INDEX_POS] = lnum - 1 - start
@@ -400,15 +395,10 @@ def format_outer_frames(context=5, stack_start=None, stack_end=None,
             if (os.path.basename(filename) in ('iplib.py', 'py3compat.py')
                         and func_name in ('execfile', 'safe_execfile', 'runcode')):
                 break
-        maybeStart = line_no - 1 - context // 2
-        start = max(maybeStart, 0)
+        maybe_start = line_no - 1 - context // 2
+        start = max(maybe_start, 0)
         end = start + context
         lines = linecache.getlines(filename)[start:end]
-        # pad with empty lines if necessary
-        if maybeStart < 0:
-            lines = (['\n'] * -maybeStart) + lines
-        if len(lines) < context:
-            lines += ['\n'] * (context - len(lines))
         buf = list(records[i])
         buf[LNUM_POS] = line_no
         buf[INDEX_POS] = line_no - 1 - start


Test patch:
diff --git a/joblib/test/test_format_stack.py b/joblib/test/test_format_stack.py
index 32fc8f5..baa8076 100644
--- a/joblib/test/test_format_stack.py
+++ b/joblib/test/test_format_stack.py
@@ -6,6 +6,8 @@ Unit tests for the stack formatting utilities
 # Copyright (c) 2010 Gael Varoquaux
 # License: BSD Style, 3 clauses.
 
+import imp
+import os
 import re
 import sys
 
@@ -75,6 +77,38 @@ def test_format_records():
                          re.MULTILINE)
 
 
+def test_format_records_file_with_less_lines_than_context(tmpdir):
+    # See https://github.com/joblib/joblib/issues/420
+    filename = os.path.join(tmpdir.strpath, 'small_file.py')
+    code_lines = ['def func():', '    1/0']
+    code = '\n'.join(code_lines)
+    open(filename, 'w').write(code)
+
+    small_file = imp.load_source('small_file', filename)
+    try:
+        small_file.func()
+    except ZeroDivisionError:
+        etb = sys.exc_info()[2]
+
+        records = _fixed_getframes(etb, context=10)
+        # Check that if context is bigger than the number of lines in
+        # the file you do not get padding
+        frame, tb_filename, line, func_name, context, _ = records[-1]
+        assert [l.rstrip() for l in context] == code_lines
+
+        formatted_records = format_records(records)
+        # 2 lines for header in the traceback: lines of ...... +
+        # filename with function
+        len_header = 2
+        nb_lines_formatted_records = len(formatted_records[1].splitlines())
+        assert (nb_lines_formatted_records == len_header + len(code_lines))
+        # Check exception stack
+        arrow_regex = r'^-+>\s+\d+\s+'
+        assert re.search(arrow_regex + r'1/0',
+                         formatted_records[1],
+                         re.MULTILINE)
+
+
 @with_numpy
 def test_format_exc_with_compiled_code():
     # Trying to tokenize compiled C code raise SyntaxError.
diff --git a/joblib/test/test_memory.py b/joblib/test/test_memory.py
index e7e8037..582b3e8 100644
--- a/joblib/test/test_memory.py
+++ b/joblib/test/test_memory.py
@@ -9,7 +9,6 @@ Test the memory module.
 import shutil
 import os
 import os.path
-from tempfile import mkdtemp
 import pickle
 import warnings
 import sys
@@ -33,51 +32,16 @@ def f(x, y=1):
     return x ** 2 + y
 
 
-###############################################################################
-# Test fixtures
-env = dict()
-
-
-def setup_module():
-    """ Test setup.
-    """
-    cachedir = mkdtemp()
-    env['dir'] = cachedir
-    if os.path.exists(cachedir):
-        shutil.rmtree(cachedir)
-    # Don't make the cachedir, Memory should be able to do that on the fly
-    print(80 * '_')
-    print('test_memory setup (%s)' % env['dir'])
-    print(80 * '_')
-
-
-def _rmtree_onerror(func, path, excinfo):
-    print('!' * 79)
-    print('os function failed: %r' % func)
-    print('file to be removed: %s' % path)
-    print('exception was: %r' % excinfo[1])
-    print('!' * 79)
-
-
-def teardown_module():
-    """ Test teardown.
-    """
-    shutil.rmtree(env['dir'], False, _rmtree_onerror)
-    print(80 * '_')
-    print('test_memory teardown (%s)' % env['dir'])
-    print(80 * '_')
-
-
 ###############################################################################
 # Helper function for the tests
-def check_identity_lazy(func, accumulator):
+def check_identity_lazy(func, accumulator, cachedir):
     """ Given a function and an accumulator (a list that grows every
         time the function is called), check that the function can be
         decorated by memory to be a lazy identity.
     """
     # Call each function with several arguments, and check that it is
     # evaluated only once per argument.
-    memory = Memory(cachedir=env['dir'], verbose=0)
+    memory = Memory(cachedir=cachedir, verbose=0)
     memory.clear(warn=False)
     func = memory.cache(func)
     for i in range(3):
@@ -88,7 +52,7 @@ def check_identity_lazy(func, accumulator):
 
 ###############################################################################
 # Tests
-def test_memory_integration():
+def test_memory_integration(tmpdir):
     """ Simple test of memory lazy evaluation.
     """
     accumulator = list()
@@ -100,19 +64,19 @@ def test_memory_integration():
         accumulator.append(1)
         return l
 
-    check_identity_lazy(f, accumulator)
+    check_identity_lazy(f, accumulator, tmpdir.strpath)
 
     # Now test clearing
     for compress in (False, True):
         for mmap_mode in ('r', None):
-            memory = Memory(cachedir=env['dir'], verbose=10,
+            memory = Memory(cachedir=tmpdir.strpath, verbose=10,
                             mmap_mode=mmap_mode, compress=compress)
             # First clear the cache directory, to check that our code can
             # handle that
             # NOTE: this line would raise an exception, as the database file is
             # still open; we ignore the error since we want to test what
             # happens if the directory disappears
-            shutil.rmtree(env['dir'], ignore_errors=True)
+            shutil.rmtree(tmpdir.strpath, ignore_errors=True)
             g = memory.cache(f)
             g(1)
             g.clear(warn=False)
@@ -127,7 +91,7 @@ def test_memory_integration():
     # Now do a smoke test with a function defined in __main__, as the name
     # mangling rules are more complex
     f.__module__ = '__main__'
-    memory = Memory(cachedir=env['dir'], verbose=0)
+    memory = Memory(cachedir=tmpdir.strpath, verbose=0)
     memory.cache(f)(1)
 
 
@@ -147,7 +111,7 @@ def test_no_memory():
         assert len(accumulator) == current_accumulator + 1
 
 
-def test_memory_kwarg():
+def test_memory_kwarg(tmpdir):
     " Test memory with a function with keyword arguments."
     accumulator = list()
 
@@ -155,15 +119,15 @@ def test_memory_kwarg():
         accumulator.append(1)
         return l
 
-    check_identity_lazy(g, accumulator)
+    check_identity_lazy(g, accumulator, tmpdir.strpath)
 
-    memory = Memory(cachedir=env['dir'], verbose=0)
+    memory = Memory(cachedir=tmpdir.strpath, verbose=0)
     g = memory.cache(g)
     # Smoke test with an explicit keyword argument:
     assert g(l=30, m=2) == 30
 
 
-def test_memory_lambda():
+def test_memory_lambda(tmpdir):
     " Test memory with a function with a lambda."
     accumulator = list()
 
@@ -175,12 +139,12 @@ def test_memory_lambda():
 
     l = lambda x: helper(x)
 
-    check_identity_lazy(l, accumulator)
+    check_identity_lazy(l, accumulator, tmpdir.strpath)
 
 
-def test_memory_name_collision():
+def test_memory_name_collision(tmpdir):
     " Check that name collisions with functions will raise warnings"
-    memory = Memory(cachedir=env['dir'], verbose=0)
+    memory = Memory(cachedir=tmpdir.strpath, verbose=0)
 
     @memory.cache
     def name_collision(x):
@@ -212,9 +176,9 @@ def test_memory_name_collision():
         assert "collision" in str(w[-1].message)
 
 
-def test_memory_warning_lambda_collisions():
+def test_memory_warning_lambda_collisions(tmpdir):
     # Check that multiple use of lambda will raise collisions
-    memory = Memory(cachedir=env['dir'], verbose=0)
+    memory = Memory(cachedir=tmpdir.strpath, verbose=0)
     # For isolation with other tests
     memory.clear()
     a = lambda x: x
@@ -238,10 +202,10 @@ def test_memory_warning_lambda_collisions():
     assert len(w) == 4
 
 
-def test_memory_warning_collision_detection():
+def test_memory_warning_collision_detection(tmpdir):
     # Check that collisions impossible to detect will raise appropriate
     # warnings.
-    memory = Memory(cachedir=env['dir'], verbose=0)
+    memory = Memory(cachedir=tmpdir.strpath, verbose=0)
     # For isolation with other tests
     memory.clear()
     a1 = eval('lambda x: x')
@@ -264,7 +228,7 @@ def test_memory_warning_collision_detection():
         assert "cannot detect" in str(w[-1].message).lower()
 
 
-def test_memory_partial():
+def test_memory_partial(tmpdir):
     " Test memory with functools.partial."
     accumulator = list()
 
@@ -277,12 +241,12 @@ def test_memory_partial():
     import functools
     function = functools.partial(func, 1)
 
-    check_identity_lazy(function, accumulator)
+    check_identity_lazy(function, accumulator, tmpdir.strpath)
 
 
-def test_memory_eval():
+def test_memory_eval(tmpdir):
     " Smoke test memory with a function with a function defined in an eval."
-    memory = Memory(cachedir=env['dir'], verbose=0)
+    memory = Memory(cachedir=tmpdir.strpath, verbose=0)
 
     m = eval('lambda x: x')
     mm = memory.cache(m)
@@ -300,11 +264,11 @@ def count_and_append(x=[]):
     return len_x
 
 
-def test_argument_change():
+def test_argument_change(tmpdir):
     """ Check that if a function has a side effect in its arguments, it
         should use the hash of changing arguments.
     """
-    mem = Memory(cachedir=env['dir'], verbose=0)
+    mem = Memory(cachedir=tmpdir.strpath, verbose=0)
     func = mem.cache(count_and_append)
     # call the function for the first time, is should cache it with
     # argument x=[]
@@ -315,7 +279,7 @@ def test_argument_change():
 
 
 @with_numpy
-def test_memory_numpy():
+def test_memory_numpy(tmpdir):
     " Test memory with a function with numpy arrays."
     # Check with memmapping and without.
     for mmap_mode in (None, 'r'):
@@ -325,7 +289,7 @@ def test_memory_numpy():
             accumulator.append(1)
             return l
 
-        memory = Memory(cachedir=env['dir'], mmap_mode=mmap_mode,
+        memory = Memory(cachedir=tmpdir.strpath, mmap_mode=mmap_mode,
                             verbose=0)
         memory.clear(warn=False)
         cached_n = memory.cache(n)
@@ -339,10 +303,10 @@ def test_memory_numpy():
 
 
 @with_numpy
-def test_memory_numpy_check_mmap_mode():
+def test_memory_numpy_check_mmap_mode(tmpdir):
     """Check that mmap_mode is respected even at the first call"""
 
-    memory = Memory(cachedir=env['dir'], mmap_mode='r', verbose=0)
+    memory = Memory(cachedir=tmpdir.strpath, mmap_mode='r', verbose=0)
     memory.clear(warn=False)
 
     @memory.cache()
@@ -361,10 +325,10 @@ def test_memory_numpy_check_mmap_mode():
     assert b.mode == 'r'
 
 
-def test_memory_exception():
+def test_memory_exception(tmpdir):
     """ Smoketest the exception handling of Memory.
     """
-    memory = Memory(cachedir=env['dir'], verbose=0)
+    memory = Memory(cachedir=tmpdir.strpath, verbose=0)
 
     class MyException(Exception):
         pass
@@ -382,9 +346,9 @@ def test_memory_exception():
         assert_raises(MyException, h, 1)
 
 
-def test_memory_ignore():
+def test_memory_ignore(tmpdir):
     " Test the ignore feature of memory "
-    memory = Memory(cachedir=env['dir'], verbose=0)
+    memory = Memory(cachedir=tmpdir.strpath, verbose=0)
     accumulator = list()
 
     @memory.cache(ignore=['y'])
@@ -401,9 +365,9 @@ def test_memory_ignore():
     assert len(accumulator) == 1
 
 
-def test_partial_decoration():
+def test_partial_decoration(tmpdir):
     "Check cache may be called with kwargs before decorating"
-    memory = Memory(cachedir=env['dir'], verbose=0)
+    memory = Memory(cachedir=tmpdir.strpath, verbose=0)
 
     test_values = [
         (['x'], 100, 'r'),
@@ -419,13 +383,13 @@ def test_partial_decoration():
         assert z.mmap_mode == mmap_mode
 
 
-def test_func_dir():
+def test_func_dir(tmpdir):
     # Test the creation of the memory cache directory for the function.
-    memory = Memory(cachedir=env['dir'], verbose=0)
+    memory = Memory(cachedir=tmpdir.strpath, verbose=0)
     memory.clear()
     path = __name__.split('.')
     path.append('f')
-    path = os.path.join(env['dir'], 'joblib', *path)
+    path = tmpdir.join('joblib', *path).strpath
 
     g = memory.cache(f)
     # Test that the function directory is created on demand
@@ -448,9 +412,9 @@ def test_func_dir():
     assert a == g(1)
 
 
-def test_persistence():
+def test_persistence(tmpdir):
     # Test the memorized functions can be pickled and restored.
-    memory = Memory(cachedir=env['dir'], verbose=0)
+    memory = Memory(cachedir=tmpdir.strpath, verbose=0)
     g = memory.cache(f)
     output = g(1)
 
@@ -470,13 +434,13 @@ def test_persistence():
     gp(1)
 
 
-def test_call_and_shelve():
+def test_call_and_shelve(tmpdir):
     """Test MemorizedFunc outputting a reference to cache.
     """
 
-    for func, Result in zip((MemorizedFunc(f, env['dir']),
+    for func, Result in zip((MemorizedFunc(f, tmpdir.strpath),
                              NotMemorizedFunc(f),
-                             Memory(cachedir=env['dir']).cache(f),
+                             Memory(cachedir=tmpdir.strpath).cache(f),
                              Memory(cachedir=None).cache(f),
                              ),
                             (MemorizedResult, NotMemorizedResult,
@@ -491,9 +455,9 @@ def test_call_and_shelve():
         result.clear()  # Do nothing if there is no cache.
 
 
-def test_memorized_pickling():
-    for func in (MemorizedFunc(f, env['dir']), NotMemorizedFunc(f)):
-        filename = os.path.join(env['dir'], 'pickling_test.dat')
+def test_memorized_pickling(tmpdir):
+    for func in (MemorizedFunc(f, tmpdir.strpath), NotMemorizedFunc(f)):
+        filename = tmpdir.join('pickling_test.dat').strpath
         result = func.call_and_shelve(2)
         with open(filename, 'wb') as fp:
             pickle.dump(result, fp)
@@ -503,11 +467,11 @@ def test_memorized_pickling():
         os.remove(filename)
 
 
-def test_memorized_repr():
-    func = MemorizedFunc(f, env['dir'])
+def test_memorized_repr(tmpdir):
+    func = MemorizedFunc(f, tmpdir.strpath)
     result = func.call_and_shelve(2)
 
-    func2 = MemorizedFunc(f, env['dir'])
+    func2 = MemorizedFunc(f, tmpdir.strpath)
     result2 = func2.call_and_shelve(2)
     assert result.get() == result2.get()
     assert repr(func) == repr(func2)
@@ -518,29 +482,27 @@ def test_memorized_repr():
     repr(func.call_and_shelve(2))
 
     # Smoke test for message output (increase code coverage)
-    func = MemorizedFunc(f, env['dir'], verbose=11, timestamp=time.time())
+    func = MemorizedFunc(f, tmpdir.strpath, verbose=11, timestamp=time.time())
     result = func.call_and_shelve(11)
     result.get()
 
-    func = MemorizedFunc(f, env['dir'], verbose=11)
+    func = MemorizedFunc(f, tmpdir.strpath, verbose=11)
     result = func.call_and_shelve(11)
     result.get()
 
-    func = MemorizedFunc(f, env['dir'], verbose=5, timestamp=time.time())
+    func = MemorizedFunc(f, tmpdir.strpath, verbose=5, timestamp=time.time())
     result = func.call_and_shelve(11)
     result.get()
 
-    func = MemorizedFunc(f, env['dir'], verbose=5)
+    func = MemorizedFunc(f, tmpdir.strpath, verbose=5)
     result = func.call_and_shelve(11)
     result.get()
 
 
-def test_memory_file_modification(capsys):
+def test_memory_file_modification(capsys, tmpdir):
     # Test that modifying a Python file after loading it does not lead to
     # Recomputation
-    dir_name = os.path.join(env['dir'], 'tmp_import')
-    if not os.path.exists(dir_name):
-        os.mkdir(dir_name)
+    dir_name = tmpdir.mkdir('tmp_import').strpath
     filename = os.path.join(dir_name, 'tmp_joblib_.py')
     content = 'def f(x):\n    print(x)\n    return x\n'
     with open(filename, 'w') as module_file:
@@ -550,7 +512,7 @@ def test_memory_file_modification(capsys):
     sys.path.append(dir_name)
     import tmp_joblib_ as tmp
 
-    mem = Memory(cachedir=env['dir'], verbose=0)
+    mem = Memory(cachedir=tmpdir.strpath, verbose=0)
     f = mem.cache(tmp.f)
     # First call f a few times
     f(1)
@@ -606,10 +568,10 @@ def _product(a, b):
     return a * b
 
 
-def test_memory_in_memory_function_code_change():
+def test_memory_in_memory_function_code_change(tmpdir):
     _function_to_cache.__code__ = _sum.__code__
 
-    mem = Memory(cachedir=env['dir'], verbose=0)
+    mem = Memory(cachedir=tmpdir.strpath, verbose=0)
     f = mem.cache(_function_to_cache)
 
     assert f(1, 2) == 3
@@ -639,8 +601,8 @@ def func_with_signature(a: int, b: float) -> float:
     return a + b
 """)
 
-    def test_memory_func_with_kwonly_args():
-        mem = Memory(cachedir=env['dir'], verbose=0)
+    def test_memory_func_with_kwonly_args(tmpdir):
+        mem = Memory(cachedir=tmpdir.strpath, verbose=0)
         func_cached = mem.cache(func_with_kwonly_args)
 
         assert func_cached(1, 2, kw1=3) == (1, 2, 3, 'kw2')
@@ -668,18 +630,17 @@ def func_with_signature(a: int, b: float) -> float:
         assert func_cached(1, 2, kw1=3, kw2=4) == (1, 2, 3, 4)
         assert func_cached(1, 2, kw1=3, kw2='ignored') == (1, 2, 3, 4)
 
-
-    def test_memory_func_with_signature():
-        mem = Memory(cachedir=env['dir'], verbose=0)
+    def test_memory_func_with_signature(tmpdir):
+        mem = Memory(cachedir=tmpdir.strpath, verbose=0)
         func_cached = mem.cache(func_with_signature)
 
         assert func_cached(1, 2.) == 3.
 
 
-def _setup_temporary_cache_folder(num_inputs=10):
+def _setup_temporary_cache_folder(tmpdir, num_inputs=10):
     # Use separate cache dir to avoid side-effects from other tests
     # that do not use _setup_temporary_cache_folder
-    mem = Memory(cachedir=os.path.join(env['dir'], 'separate_cache'),
+    mem = Memory(cachedir=tmpdir.mkdir('separate_cache').strpath,
                  verbose=0)
 
     @mem.cache()
@@ -697,8 +658,8 @@ def _setup_temporary_cache_folder(num_inputs=10):
     return mem, full_hashdirs, get_1000_bytes
 
 
-def test__get_cache_items():
-    mem, expected_hash_cachedirs, _ = _setup_temporary_cache_folder()
+def test__get_cache_items(tmpdir):
+    mem, expected_hash_cachedirs, _ = _setup_temporary_cache_folder(tmpdir)
     cachedir = mem.cachedir
     cache_items = _get_cache_items(cachedir)
     hash_cachedirs = [ci.path for ci in cache_items]
@@ -724,8 +685,8 @@ def test__get_cache_items():
     assert last_accesses == expected_last_accesses
 
 
-def test__get_cache_items_to_delete():
-    mem, expected_hash_cachedirs, _ = _setup_temporary_cache_folder()
+def test__get_cache_items_to_delete(tmpdir):
+    mem, expected_hash_cachedirs, _ = _setup_temporary_cache_folder(tmpdir)
     cachedir = mem.cachedir
     cache_items = _get_cache_items(cachedir)
     # bytes_limit set to keep only one cache item (each hash cache
@@ -759,8 +720,8 @@ def test__get_cache_items_to_delete():
             min(ci.last_access for ci in surviving_cache_items))
 
 
-def test_memory_reduce_size():
-    mem, _, _ = _setup_temporary_cache_folder()
+def test_memory_reduce_size(tmpdir):
+    mem, _, _ = _setup_temporary_cache_folder(tmpdir)
     cachedir = mem.cachedir
     ref_cache_items = _get_cache_items(cachedir)
 
diff --git a/joblib/test/test_numpy_pickle.py b/joblib/test/test_numpy_pickle.py
index 1cf10fa..20cd9a0 100644
--- a/joblib/test/test_numpy_pickle.py
+++ b/joblib/test/test_numpy_pickle.py
@@ -1,13 +1,10 @@
 """Test the numpy pickler as a replacement of the standard pickler."""
 
-from tempfile import mkdtemp
 import copy
-import shutil
 import os
 import random
 import sys
 import re
-import tempfile
 import io
 import warnings
 import gzip
@@ -108,45 +105,16 @@ _object = _newclass()
 typelist.append(_object)  # <type 'class'>
 
 
-###############################################################################
-# Test fixtures
-
-env = dict()
-
-
-def setup_module():
-    """ Test setup.
-    """
-    env['dir'] = mkdtemp()
-    env['filename'] = os.path.join(env['dir'], 'test.pkl')
-    print(80 * '_')
-    print('setup numpy_pickle')
-    print(80 * '_')
-
-
-def teardown_module():
-    """ Test teardown.
-    """
-    shutil.rmtree(env['dir'])
-    # del env['dir']
-    # del env['filename']
-    print(80 * '_')
-    print('teardown numpy_pickle')
-    print(80 * '_')
-
-
 ###############################################################################
 # Tests
 
-def test_standard_types():
+def test_standard_types(tmpdir):
     # Test pickling and saving with standard types.
-    filename = env['filename']
+    filename = tmpdir.join('test.pkl').strpath
     for compress in [0, 1]:
         for member in typelist:
-            # Change the file name to avoid side effects between tests
-            this_filename = filename + str(random.randint(0, 1000))
-            numpy_pickle.dump(member, this_filename, compress=compress)
-            _member = numpy_pickle.load(this_filename)
+            numpy_pickle.dump(member, filename, compress=compress)
+            _member = numpy_pickle.load(filename)
             # We compare the pickled instance to the reloaded one only if it
             # can be compared to a copied one
             if member == copy.deepcopy(member):
@@ -169,28 +137,24 @@ def test_compress_level_error():
 
 
 @with_numpy
-def test_numpy_persistence():
-    filename = env['filename']
+def test_numpy_persistence(tmpdir):
+    filename = tmpdir.join('test.pkl').strpath
     rnd = np.random.RandomState(0)
     a = rnd.random_sample((10, 2))
     for compress in (False, True, 0, 3):
         # We use 'a.T' to have a non C-contiguous array.
         for index, obj in enumerate(((a,), (a.T,), (a, a), [a, a, a])):
-            # Change the file name to avoid side effects between tests
-            this_filename = filename + str(random.randint(0, 1000))
-
-            filenames = numpy_pickle.dump(obj, this_filename,
-                                          compress=compress)
+            filenames = numpy_pickle.dump(obj, filename, compress=compress)
 
             # All is cached in one file
             assert len(filenames) == 1
             # Check that only one file was created
-            assert filenames[0] == this_filename
+            assert filenames[0] == filename
             # Check that this file does exist
-            assert os.path.exists(os.path.join(env['dir'], filenames[0]))
+            assert os.path.exists(filenames[0])
 
             # Unpickle the object
-            obj_ = numpy_pickle.load(this_filename)
+            obj_ = numpy_pickle.load(filename)
             # Check that the items are indeed arrays
             for item in obj_:
                 assert isinstance(item, np.ndarray)
@@ -199,15 +163,13 @@ def test_numpy_persistence():
 
         # Now test with array subclasses
         for obj in (np.matrix(np.zeros(10)),
-                    np.memmap(filename + str(random.randint(0, 1000)) + 'mmap',
+                    np.memmap(filename + 'mmap',
                               mode='w+', shape=4, dtype=np.float)):
-            this_filename = filename + str(random.randint(0, 1000))
-            filenames = numpy_pickle.dump(obj, this_filename,
-                                          compress=compress)
+            filenames = numpy_pickle.dump(obj, filename, compress=compress)
             # All is cached in one file
             assert len(filenames) == 1
 
-            obj_ = numpy_pickle.load(this_filename)
+            obj_ = numpy_pickle.load(filename)
             if (type(obj) is not np.memmap and
                     hasattr(obj, '__array_prepare__')):
                 # We don't reconstruct memmaps
@@ -217,12 +179,11 @@ def test_numpy_persistence():
 
         # Test with an object containing multiple numpy arrays
         obj = ComplexTestObject()
-        filenames = numpy_pickle.dump(obj, this_filename,
-                                      compress=compress)
+        filenames = numpy_pickle.dump(obj, filename, compress=compress)
         # All is cached in one file
         assert len(filenames) == 1
 
-        obj_loaded = numpy_pickle.load(this_filename)
+        obj_loaded = numpy_pickle.load(filename)
         assert isinstance(obj_loaded, type(obj))
         np.testing.assert_array_equal(obj_loaded.array_float, obj.array_float)
         np.testing.assert_array_equal(obj_loaded.array_int, obj.array_int)
@@ -230,9 +191,9 @@ def test_numpy_persistence():
 
 
 @with_numpy
-def test_numpy_persistence_bufferred_array_compression():
+def test_numpy_persistence_bufferred_array_compression(tmpdir):
     big_array = np.ones((_IO_BUFFER_SIZE + 100), dtype=np.uint8)
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test.pkl').strpath
     numpy_pickle.dump(big_array, filename, compress=True)
     arr_reloaded = numpy_pickle.load(filename)
 
@@ -240,17 +201,17 @@ def test_numpy_persistence_bufferred_array_compression():
 
 
 @with_numpy
-def test_memmap_persistence():
+def test_memmap_persistence(tmpdir):
     rnd = np.random.RandomState(0)
     a = rnd.random_sample(10)
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test1.pkl').strpath
     numpy_pickle.dump(a, filename)
     b = numpy_pickle.load(filename, mmap_mode='r')
 
     assert isinstance(b, np.memmap)
 
     # Test with an object containing multiple numpy arrays
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test2.pkl').strpath
     obj = ComplexTestObject()
     numpy_pickle.dump(obj, filename)
     obj_loaded = numpy_pickle.load(filename, mmap_mode='r')
@@ -290,14 +251,14 @@ def test_memmap_persistence():
 
 
 @with_numpy
-def test_memmap_persistence_mixed_dtypes():
+def test_memmap_persistence_mixed_dtypes(tmpdir):
     # loading datastructures that have sub-arrays with dtype=object
     # should not prevent memmaping on fixed size dtype sub-arrays.
     rnd = np.random.RandomState(0)
     a = rnd.random_sample(10)
     b = np.array([1, 'b'], dtype=object)
     construct = (a, b)
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test.pkl').strpath
     numpy_pickle.dump(construct, filename)
     a_clone, b_clone = numpy_pickle.load(filename, mmap_mode='r')
 
@@ -309,24 +270,24 @@ def test_memmap_persistence_mixed_dtypes():
 
 
 @with_numpy
-def test_masked_array_persistence():
+def test_masked_array_persistence(tmpdir):
     # The special-case picker fails, because saving masked_array
     # not implemented, but it just delegates to the standard pickler.
     rnd = np.random.RandomState(0)
     a = rnd.random_sample(10)
     a = np.ma.masked_greater(a, 0.5)
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test.pkl').strpath
     numpy_pickle.dump(a, filename)
     b = numpy_pickle.load(filename, mmap_mode='r')
     assert isinstance(b, np.ma.masked_array)
 
 
 @with_numpy
-def test_compress_mmap_mode_warning():
+def test_compress_mmap_mode_warning(tmpdir):
     # Test the warning in case of compress + mmap_mode
     rnd = np.random.RandomState(0)
     a = rnd.random_sample(10)
-    this_filename = env['filename'] + str(random.randint(0, 1000))
+    this_filename = tmpdir.join('test.pkl').strpath
     numpy_pickle.dump(a, this_filename, compress=1)
     with warnings.catch_warnings(record=True) as caught_warnings:
         warnings.simplefilter("always")
@@ -342,9 +303,9 @@ def test_compress_mmap_mode_warning():
 
 
 @with_numpy
-def test_cache_size_warning():
+def test_cache_size_warning(tmpdir):
     # Check deprecation warning raised when cache size is not None
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test.pkl').strpath
     rnd = np.random.RandomState(0)
     a = rnd.random_sample((10, 2))
 
@@ -364,9 +325,9 @@ def test_cache_size_warning():
 
 @with_numpy
 @with_memory_profiler
-def test_memory_usage():
+def test_memory_usage(tmpdir):
     # Verify memory stays within expected bounds.
-    filename = env['filename']
+    filename = tmpdir.join('test.pkl').strpath
     small_array = np.ones((10, 10))
     big_array = np.ones(shape=100 * int(1e6), dtype=np.uint8)
     small_matrix = np.matrix(small_array)
@@ -391,7 +352,7 @@ def test_memory_usage():
 
 
 @with_numpy
-def test_compressed_pickle_dump_and_load():
+def test_compressed_pickle_dump_and_load(tmpdir):
     expected_list = [np.arange(5, dtype=np.dtype('<i8')),
                      np.arange(5, dtype=np.dtype('>i8')),
                      np.arange(5, dtype=np.dtype('<f8')),
@@ -408,21 +369,17 @@ def test_compressed_pickle_dump_and_load():
                      np.matrix([0, 1, 2], dtype=np.dtype('>i8')),
                      u"C'est l'\xe9t\xe9 !"]
 
-    with tempfile.NamedTemporaryFile(suffix='.gz', dir=env['dir']) as f:
-        fname = f.name
+    fname = tmpdir.join('temp.pkl.gz').strpath
 
-    try:
-        dumped_filenames = numpy_pickle.dump(expected_list, fname, compress=1)
-        assert len(dumped_filenames) == 1
-        result_list = numpy_pickle.load(fname)
-        for result, expected in zip(result_list, expected_list):
-            if isinstance(expected, np.ndarray):
-                assert result.dtype == expected.dtype
-                np.testing.assert_equal(result, expected)
-            else:
-                assert result == expected
-    finally:
-        os.remove(fname)
+    dumped_filenames = numpy_pickle.dump(expected_list, fname, compress=1)
+    assert len(dumped_filenames) == 1
+    result_list = numpy_pickle.load(fname)
+    for result, expected in zip(result_list, expected_list):
+        if isinstance(expected, np.ndarray):
+            assert result.dtype == expected.dtype
+            np.testing.assert_equal(result, expected)
+        else:
+            assert result == expected
 
 
 def _check_pickle(filename, expected_list):
@@ -528,12 +485,12 @@ def test_joblib_pickle_across_python_versions():
         _check_pickle(fname, expected_list)
 
 
-def test_compress_tuple_argument():
+def test_compress_tuple_argument(tmpdir):
     compress_tuples = (('zlib', 3),
                        ('gzip', 3))
 
     # Verify the tuple is correctly taken into account.
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test.pkl').strpath
     for compress in compress_tuples:
         numpy_pickle.dump("dummy", filename,
                           compress=compress)
@@ -562,9 +519,9 @@ def test_compress_tuple_argument():
 
 
 @with_numpy
-def test_joblib_compression_formats():
+def test_joblib_compression_formats(tmpdir):
     compresslevels = (1, 3, 6)
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test.pkl').strpath
     objects = (np.ones(shape=(100, 100), dtype='f8'),
                range(10),
                {'a': 1, 2: 'b'}, [], (), {}, 0, 1.0)
@@ -592,7 +549,6 @@ def test_joblib_compression_formats():
                         np.testing.assert_array_equal(obj_reloaded, obj)
                     else:
                         assert obj_reloaded == obj
-                    os.remove(dump_filename)
 
 
 def _gzip_file_decompress(source_filename, target_filename):
@@ -613,10 +569,10 @@ def _zlib_file_decompress(source_filename, target_filename):
         fo.write(buf)
 
 
-def test_load_externally_decompressed_files():
+def test_load_externally_decompressed_files(tmpdir):
     # Test that BinaryZlibFile generates valid gzip and zlib compressed files.
     obj = "a string to persist"
-    filename_raw = env['filename'] + str(random.randint(0, 1000))
+    filename_raw = tmpdir.join('test.pkl').strpath
     compress_list = (('.z', _zlib_file_decompress),
                      ('.gz', _gzip_file_decompress))
 
@@ -633,13 +589,8 @@ def test_load_externally_decompressed_files():
         obj_reloaded = numpy_pickle.load(filename_raw)
         assert obj == obj_reloaded
 
-        # Do some cleanup
-        os.remove(filename_raw)
-        if os.path.exists(filename_compressed):
-            os.remove(filename_compressed)
-
 
-def test_compression_using_file_extension():
+def test_compression_using_file_extension(tmpdir):
     # test that compression method corresponds to the given filename extension.
     extensions_dict = {
         # valid compressor extentions
@@ -652,7 +603,7 @@ def test_compression_using_file_extension():
         '.pkl': 'not-compressed',
         '': 'not-compressed'
     }
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test.pkl').strpath
     obj = "object to dump"
 
     for ext, cmethod in extensions_dict.items():
@@ -671,11 +622,10 @@ def test_compression_using_file_extension():
             obj_reloaded = numpy_pickle.load(dump_fname)
             assert isinstance(obj_reloaded, type(obj))
             assert obj_reloaded == obj
-            os.remove(dump_fname)
 
 
 @with_numpy
-def test_file_handle_persistence():
+def test_file_handle_persistence(tmpdir):
     objs = [np.random.random((10, 10)),
             "some data",
             np.matrix([0, 1, 2])]
@@ -683,7 +633,7 @@ def test_file_handle_persistence():
     if PY3_OR_LATER:
         import lzma
         fobjs += [lzma.LZMAFile]
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test.pkl').strpath
 
     for obj in objs:
         for fobj in fobjs:
@@ -707,8 +657,6 @@ def test_file_handle_persistence():
                 assert obj_reloaded == obj
                 assert obj_reloaded_2 == obj
 
-            os.remove(filename)
-
 
 @with_numpy
 def test_in_memory_persistence():
@@ -726,9 +674,9 @@ def test_in_memory_persistence():
 
 
 @with_numpy
-def test_file_handle_persistence_mmap():
+def test_file_handle_persistence_mmap(tmpdir):
     obj = np.random.random((10, 10))
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test.pkl').strpath
 
     with open(filename, 'wb') as f:
         numpy_pickle.dump(obj, f)
@@ -740,9 +688,9 @@ def test_file_handle_persistence_mmap():
 
 
 @with_numpy
-def test_file_handle_persistence_compressed_mmap():
+def test_file_handle_persistence_compressed_mmap(tmpdir):
     obj = np.random.random((10, 10))
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test.pkl').strpath
 
     with open(filename, 'wb') as f:
         numpy_pickle.dump(obj, f, compress=('gzip', 3))
@@ -779,8 +727,8 @@ def test_file_handle_persistence_in_memory_mmap():
                     'option will be ignored.' % {'mmap_mode': 'r+'})
 
 
-def test_binary_zlibfile():
-    filename = env['filename'] + str(random.randint(0, 1000))
+def test_binary_zlibfile(tmpdir):
+    filename = tmpdir.join('test.pkl').strpath
 
     # Test bad compression levels
     for bad_value in (-1, 10, 15, 'a', (), {}):
@@ -829,8 +777,6 @@ def test_binary_zlibfile():
                         assert fz.tell() == 0
                 assert fz.closed
 
-            os.remove(filename)
-
             # Test with a filename as input
             with BinaryZlibFile(filename, 'wb',
                                 compresslevel=compress_level) as fz:
@@ -876,8 +822,8 @@ if np is not None:
 
 
 @with_numpy
-def test_numpy_subclass():
-    filename = env['filename']
+def test_numpy_subclass(tmpdir):
+    filename = tmpdir.join('test.pkl').strpath
     a = SubArray((10,))
     numpy_pickle.dump(a, filename)
     c = numpy_pickle.load(filename)
@@ -885,13 +831,13 @@ def test_numpy_subclass():
     np.testing.assert_array_equal(c, a)
 
 
-def test_pathlib():
+def test_pathlib(tmpdir):
     try:
         from pathlib import Path
     except ImportError:
         pass
     else:
-        filename = env['filename']
+        filename = tmpdir.join('test.pkl').strpath
         value = 123
         numpy_pickle.dump(value, Path(filename))
         assert numpy_pickle.load(filename) == value
@@ -900,8 +846,8 @@ def test_pathlib():
 
 
 @with_numpy
-def test_non_contiguous_array_pickling():
-    filename = env['filename'] + str(random.randint(0, 1000))
+def test_non_contiguous_array_pickling(tmpdir):
+    filename = tmpdir.join('test.pkl').strpath
 
     for array in [  # Array that triggers a contiguousness issue with nditer,
                     # see https://github.com/joblib/joblib/pull/352 and see
@@ -914,16 +860,15 @@ def test_non_contiguous_array_pickling():
         numpy_pickle.dump(array, filename)
         array_reloaded = numpy_pickle.load(filename)
         np.testing.assert_array_equal(array_reloaded, array)
-        os.remove(filename)
 
 
 @with_numpy
-def test_pickle_highest_protocol():
+def test_pickle_highest_protocol(tmpdir):
     # ensure persistence of a numpy array is valid even when using
     # the pickle HIGHEST_PROTOCOL.
     # see https://github.com/joblib/joblib/issues/362
 
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test.pkl').strpath
     test_array = np.zeros(10)
 
     numpy_pickle.dump(test_array, filename, protocol=pickle.HIGHEST_PROTOCOL)
diff --git a/joblib/test/test_numpy_pickle_compat.py b/joblib/test/test_numpy_pickle_compat.py
index 492bae6..5e83192 100644
--- a/joblib/test/test_numpy_pickle_compat.py
+++ b/joblib/test/test_numpy_pickle_compat.py
@@ -1,36 +1,15 @@
 """Test the old numpy pickler, compatibility version."""
 
-import shutil
-import os
 import random
 
-from tempfile import mkdtemp
-
 # numpy_pickle is not a drop-in replacement of pickle, as it takes
 # filenames instead of open files as arguments.
 from joblib import numpy_pickle_compat
 
 
-###############################################################################
-# Test fixtures
-
-env = dict()
-
-
-def setup_module():
-    """Test setup."""
-    env['dir'] = mkdtemp()
-    env['filename'] = os.path.join(env['dir'], 'test.pkl')
-
-
-def teardown_module():
-    """Test teardown."""
-    shutil.rmtree(env['dir'])
-
-
-def test_z_file():
+def test_z_file(tmpdir):
     # Test saving and loading data with Zfiles.
-    filename = env['filename'] + str(random.randint(0, 1000))
+    filename = tmpdir.join('test.pkl').strpath
     data = numpy_pickle_compat.asbytes('Foo, \n Bar, baz, \n\nfoobar')
     with open(filename, 'wb') as f:
         numpy_pickle_compat.write_zfile(f, data)
diff --git a/joblib/test/test_numpy_pickle_utils.py b/joblib/test/test_numpy_pickle_utils.py
index f45551b..c4e378d 100644
--- a/joblib/test/test_numpy_pickle_utils.py
+++ b/joblib/test/test_numpy_pickle_utils.py
@@ -1,36 +1,16 @@
-import shutil
-import os
-from tempfile import mkdtemp
-
 from joblib import numpy_pickle_utils
 
 
-###############################################################################
-# Test fixtures
-
-env = dict()
-
-
-def setup_module():
-    """Test setup."""
-    env['dir'] = mkdtemp()
-
-
-def teardown_module():
-    """Test teardown."""
-    shutil.rmtree(env['dir'])
-
-
-def test_binary_zlib_file():
+def test_binary_zlib_file(tmpdir):
     """Testing creation of files depending on the type of the filenames."""
     # Testing str filename.
     binary_file = numpy_pickle_utils.BinaryZlibFile(
-        os.path.join(env['dir'], 'test'),
+        tmpdir.join('test').strpath,
         mode='wb')
     binary_file.close()
 
     # Testing unicode filename.
     binary_file = numpy_pickle_utils.BinaryZlibFile(
-        os.path.join(env['dir'], u'test'),
+        tmpdir.join(u'test').strpath,
         mode='wb')
     binary_file.close()
diff --git a/joblib/test/test_pool.py b/joblib/test/test_pool.py
index 894de01..cfe4e8e 100644
--- a/joblib/test/test_pool.py
+++ b/joblib/test/test_pool.py
@@ -16,11 +16,6 @@ if mp is not None:
     from joblib.pool import reduce_memmap
 
 
-@fixture(scope='function')
-def tmpdir_path(tmpdir):
-    return tmpdir.strpath
-
-
 def setup_module():
     setup_autokill(__name__, timeout=300)
 
@@ -57,10 +52,10 @@ def inplace_double(args):
 
 @with_numpy
 @with_multiprocessing
-def test_memmap_based_array_reducing(tmpdir_path):
+def test_memmap_based_array_reducing(tmpdir):
     """Check that it is possible to reduce a memmap backed array"""
     assert_array_equal = np.testing.assert_array_equal
-    filename = os.path.join(tmpdir_path, 'test.mmap')
+    filename = tmpdir.join('test.mmap').strpath
 
     # Create a file larger than what will be used by a
     buffer = np.memmap(filename, dtype=np.float64, shape=500, mode='w+')
@@ -86,7 +81,7 @@ def test_memmap_based_array_reducing(tmpdir_path):
     d = c.T
 
     # Array reducer with auto dumping disabled
-    reducer = ArrayMemmapReducer(None, tmpdir_path, 'c')
+    reducer = ArrayMemmapReducer(None, tmpdir.strpath, 'c')
 
     def reconstruct_array(x):
         cons, args = reducer(x)
@@ -139,10 +134,10 @@ def test_memmap_based_array_reducing(tmpdir_path):
 
 @with_numpy
 @with_multiprocessing
-def test_high_dimension_memmap_array_reducing(tmpdir_path):
+def test_high_dimension_memmap_array_reducing(tmpdir):
     assert_array_equal = np.testing.assert_array_equal
 
-    filename = os.path.join(tmpdir_path, 'test.mmap')
+    filename = tmpdir.join('test.mmap').strpath
 
     # Create a high dimensional memmap
     a = np.memmap(filename, dtype=np.float64, shape=(100, 15, 15, 3),
@@ -184,16 +179,15 @@ def test_high_dimension_memmap_array_reducing(tmpdir_path):
 
 @with_numpy
 @with_multiprocessing
-def test_pool_with_memmap(tmpdir_path):
+def test_pool_with_memmap(tmpdir):
     """Check that subprocess can access and update shared memory memmap"""
     assert_array_equal = np.testing.assert_array_equal
 
     # Fork the subprocess before allocating the objects to be passed
-    pool_temp_folder = os.path.join(tmpdir_path, 'pool')
-    os.makedirs(pool_temp_folder)
+    pool_temp_folder = tmpdir.mkdir('pool').strpath
     p = MemmapingPool(10, max_nbytes=2, temp_folder=pool_temp_folder)
     try:
-        filename = os.path.join(tmpdir_path, 'test.mmap')
+        filename = tmpdir.join('test.mmap').strpath
         a = np.memmap(filename, dtype=np.float32, shape=(3, 5), mode='w+')
         a.fill(1.0)
 
@@ -237,17 +231,16 @@ def test_pool_with_memmap(tmpdir_path):
 
 @with_numpy
 @with_multiprocessing
-def test_pool_with_memmap_array_view(tmpdir_path):
+def test_pool_with_memmap_array_view(tmpdir):
     """Check that subprocess can access and update shared memory array"""
     assert_array_equal = np.testing.assert_array_equal
 
     # Fork the subprocess before allocating the objects to be passed
-    pool_temp_folder = os.path.join(tmpdir_path, 'pool')
-    os.makedirs(pool_temp_folder)
+    pool_temp_folder = tmpdir.mkdir('pool').strpath
     p = MemmapingPool(10, max_nbytes=2, temp_folder=pool_temp_folder)
     try:
 
-        filename = os.path.join(tmpdir_path, 'test.mmap')
+        filename = tmpdir.join('test.mmap').strpath
         a = np.memmap(filename, dtype=np.float32, shape=(3, 5), mode='w+')
         a.fill(1.0)
 
@@ -275,18 +268,18 @@ def test_pool_with_memmap_array_view(tmpdir_path):
 
 @with_numpy
 @with_multiprocessing
-def test_memmaping_pool_for_large_arrays(tmpdir_path):
+def test_memmaping_pool_for_large_arrays(tmpdir):
     """Check that large arrays are not copied in memory"""
 
     # Check that the tempfolder is empty
-    assert os.listdir(tmpdir_path) == []
+    assert os.listdir(tmpdir.strpath) == []
 
     # Build an array reducers that automaticaly dump large array content
     # to filesystem backed memmap instances to avoid memory explosion
-    p = MemmapingPool(3, max_nbytes=40, temp_folder=tmpdir_path)
+    p = MemmapingPool(3, max_nbytes=40, temp_folder=tmpdir.strpath)
     try:
         # The temporary folder for the pool is not provisioned in advance
-        assert os.listdir(tmpdir_path) == []
+        assert os.listdir(tmpdir.strpath) == []
         assert not os.path.exists(p._temp_folder)
 
         small = np.ones(5, dtype=np.float32)
@@ -294,7 +287,7 @@ def test_memmaping_pool_for_large_arrays(tmpdir_path):
         p.map(check_array, [(small, i, 1.0) for i in range(small.shape[0])])
 
         # Memory has been copied, the pool filesystem folder is unused
-        assert os.listdir(tmpdir_path) == []
+        assert os.listdir(tmpdir.strpath) == []
 
         # Try with a file larger than the memmap threshold of 40 bytes
         large = np.ones(100, dtype=np.float64)
@@ -322,14 +315,14 @@ def test_memmaping_pool_for_large_arrays(tmpdir_path):
 
 @with_numpy
 @with_multiprocessing
-def test_memmaping_pool_for_large_arrays_disabled(tmpdir_path):
+def test_memmaping_pool_for_large_arrays_disabled(tmpdir):
     """Check that large arrays memmaping can be disabled"""
     # Set max_nbytes to None to disable the auto memmaping feature
-    p = MemmapingPool(3, max_nbytes=None, temp_folder=tmpdir_path)
+    p = MemmapingPool(3, max_nbytes=None, temp_folder=tmpdir.strpath)
     try:
 
         # Check that the tempfolder is empty
-        assert os.listdir(tmpdir_path) == []
+        assert os.listdir(tmpdir.strpath) == []
 
         # Try with a file largish than the memmap threshold of 40 bytes
         large = np.ones(100, dtype=np.float64)
@@ -337,7 +330,7 @@ def test_memmaping_pool_for_large_arrays_disabled(tmpdir_path):
         p.map(check_array, [(large, i, 1.0) for i in range(large.shape[0])])
 
         # Check that the tempfolder is still empty
-        assert os.listdir(tmpdir_path) == []
+        assert os.listdir(tmpdir.strpath) == []
 
     finally:
         # Cleanup open file descriptors
@@ -387,7 +380,7 @@ def test_memmaping_on_dev_shm():
 
 @with_numpy
 @with_multiprocessing
-def test_memmaping_pool_for_large_arrays_in_return(tmpdir_path):
+def test_memmaping_pool_for_large_arrays_in_return(tmpdir):
     """Check that large arrays are not copied in memory in return"""
     assert_array_equal = np.testing.assert_array_equal
 
@@ -398,7 +391,7 @@ def test_memmaping_pool_for_large_arrays_in_return(tmpdir_path):
 
     # The MemmapingPool user can always return numpy.memmap object explicitly
     # to avoid memory copy
-    p = MemmapingPool(3, max_nbytes=10, temp_folder=tmpdir_path)
+    p = MemmapingPool(3, max_nbytes=10, temp_folder=tmpdir.strpath)
     try:
         res = p.apply_async(np.ones, args=(1000,))
         large = res.get()
@@ -417,7 +410,7 @@ def _worker_multiply(a, n_times):
 
 @with_numpy
 @with_multiprocessing
-def test_workaround_against_bad_memmap_with_copied_buffers(tmpdir_path):
+def test_workaround_against_bad_memmap_with_copied_buffers(tmpdir):
     """Check that memmaps with a bad buffer are returned as regular arrays
 
     Unary operations and ufuncs on memmap instances return a new memmap
@@ -425,7 +418,7 @@ def test_workaround_against_bad_memmap_with_copied_buffers(tmpdir_path):
     """
     assert_array_equal = np.testing.assert_array_equal
 
-    p = MemmapingPool(3, max_nbytes=10, temp_folder=tmpdir_path)
+    p = MemmapingPool(3, max_nbytes=10, temp_folder=tmpdir.strpath)
     try:
         # Send a complex, large-ish view on a array that will be converted to
         # a memmap in the worker process