summaryrefslogtreecommitdiff
path: root/numpy
diff options
context:
space:
mode:
Diffstat (limited to 'numpy')
-rw-r--r--numpy/distutils/tests/test_npy_pkg_config.py54
-rw-r--r--numpy/f2py/tests/util.py32
-rw-r--r--numpy/lib/tests/test_io.py86
-rw-r--r--numpy/ma/tests/test_mrecords.py16
-rw-r--r--numpy/tests/test_scripts.py7
5 files changed, 74 insertions, 121 deletions
diff --git a/numpy/distutils/tests/test_npy_pkg_config.py b/numpy/distutils/tests/test_npy_pkg_config.py
index 9a7284270..bdef47167 100644
--- a/numpy/distutils/tests/test_npy_pkg_config.py
+++ b/numpy/distutils/tests/test_npy_pkg_config.py
@@ -1,10 +1,9 @@
from __future__ import division, absolute_import, print_function
import os
-from tempfile import mkstemp
from numpy.distutils.npy_pkg_config import read_config, parse_flags
-from numpy.testing import TestCase, run_module_suite
+from numpy.testing import TestCase, run_module_suite, temppath
simple = """\
[meta]
@@ -39,41 +38,30 @@ simple_variable_d = {'cflags': '-I/foo/bar/include', 'libflags': '-L/foo/bar/lib
class TestLibraryInfo(TestCase):
def test_simple(self):
- fd, filename = mkstemp('foo.ini')
- try:
- pkg = os.path.splitext(filename)[0]
- try:
- os.write(fd, simple.encode('ascii'))
- finally:
- os.close(fd)
-
+ with temppath('foo.ini') as path:
+ with open(path, 'w') as f:
+ f.write(simple)
+ pkg = os.path.splitext(path)[0]
out = read_config(pkg)
- self.assertTrue(out.cflags() == simple_d['cflags'])
- self.assertTrue(out.libs() == simple_d['libflags'])
- self.assertTrue(out.name == simple_d['name'])
- self.assertTrue(out.version == simple_d['version'])
- finally:
- os.remove(filename)
- def test_simple_variable(self):
- fd, filename = mkstemp('foo.ini')
- try:
- pkg = os.path.splitext(filename)[0]
- try:
- os.write(fd, simple_variable.encode('ascii'))
- finally:
- os.close(fd)
+ self.assertTrue(out.cflags() == simple_d['cflags'])
+ self.assertTrue(out.libs() == simple_d['libflags'])
+ self.assertTrue(out.name == simple_d['name'])
+ self.assertTrue(out.version == simple_d['version'])
+ def test_simple_variable(self):
+ with temppath('foo.ini') as path:
+ with open(path, 'w') as f:
+ f.write(simple_variable)
+ pkg = os.path.splitext(path)[0]
out = read_config(pkg)
- self.assertTrue(out.cflags() == simple_variable_d['cflags'])
- self.assertTrue(out.libs() == simple_variable_d['libflags'])
- self.assertTrue(out.name == simple_variable_d['name'])
- self.assertTrue(out.version == simple_variable_d['version'])
-
- out.vars['prefix'] = '/Users/david'
- self.assertTrue(out.cflags() == '-I/Users/david/include')
- finally:
- os.remove(filename)
+
+ self.assertTrue(out.cflags() == simple_variable_d['cflags'])
+ self.assertTrue(out.libs() == simple_variable_d['libflags'])
+ self.assertTrue(out.name == simple_variable_d['name'])
+ self.assertTrue(out.version == simple_variable_d['version'])
+ out.vars['prefix'] = '/Users/david'
+ self.assertTrue(out.cflags() == '-I/Users/david/include')
class TestParseFlags(TestCase):
def test_simple_cflags(self):
diff --git a/numpy/f2py/tests/util.py b/numpy/f2py/tests/util.py
index 8d06d9680..0c9e91568 100644
--- a/numpy/f2py/tests/util.py
+++ b/numpy/f2py/tests/util.py
@@ -19,7 +19,7 @@ import random
from numpy.compat import asbytes, asstr
import numpy.f2py
-from numpy.testing import SkipTest
+from numpy.testing import SkipTest, temppath
try:
from hashlib import md5
@@ -159,16 +159,11 @@ def build_code(source_code, options=[], skip=[], only=[], suffix=None,
"""
if suffix is None:
suffix = '.f'
-
- fd, tmp_fn = tempfile.mkstemp(suffix=suffix)
- os.write(fd, asbytes(source_code))
- os.close(fd)
-
- try:
- return build_module([tmp_fn], options=options, skip=skip, only=only,
+ with temppath(suffix=suffix) as path:
+ with open(path, 'w') as f:
+ f.write(source_code)
+ return build_module([path], options=options, skip=skip, only=only,
module_name=module_name)
- finally:
- os.unlink(tmp_fn)
#
# Check if compilers are available at all...
@@ -209,22 +204,19 @@ sys.exit(99)
"""
code = code % dict(syspath=repr(sys.path))
- fd, script = tempfile.mkstemp(suffix='.py')
- os.write(fd, asbytes(code))
- os.close(fd)
+ with temppath(suffix='.py') as script:
+ with open(script, 'w') as f:
+ f.write(code)
- try:
cmd = [sys.executable, script, 'config']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
out, err = p.communicate()
- m = re.search(asbytes(r'COMPILERS:(\d+),(\d+),(\d+)'), out)
- if m:
- _compiler_status = (bool(int(m.group(1))), bool(int(m.group(2))),
- bool(int(m.group(3))))
- finally:
- os.unlink(script)
+ m = re.search(asbytes(r'COMPILERS:(\d+),(\d+),(\d+)'), out)
+ if m:
+ _compiler_status = (bool(int(m.group(1))), bool(int(m.group(2))),
+ bool(int(m.group(3))))
# Finished
return _compiler_status
diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py
index 45ee0a477..32e0c32de 100644
--- a/numpy/lib/tests/test_io.py
+++ b/numpy/lib/tests/test_io.py
@@ -4,7 +4,7 @@ import sys
import gzip
import os
import threading
-from tempfile import mkstemp, NamedTemporaryFile
+from tempfile import NamedTemporaryFile
import time
import warnings
import gc
@@ -194,8 +194,7 @@ class TestSavezLoad(RoundtripTest, TestCase):
def test_big_arrays(self):
L = (1 << 31) + 100000
a = np.empty(L, dtype=np.uint8)
- with tempdir(prefix="numpy_test_big_arrays_") as tmpdir:
- tmp = os.path.join(tmpdir, "file.npz")
+ with temppath(prefix="numpy_test_big_arrays_") as tmp:
np.savez(tmp, a=a)
del a
npfile = np.load(tmp)
@@ -234,16 +233,12 @@ class TestSavezLoad(RoundtripTest, TestCase):
# and savez functions in multithreaded environment
def writer(error_list):
- fd, tmp = mkstemp(suffix='.npz')
- os.close(fd)
- try:
+ with temppath(suffix='.npz') as tmp:
arr = np.random.randn(500, 500)
try:
np.savez(tmp, arr=arr)
except OSError as err:
error_list.append(err)
- finally:
- os.remove(tmp)
errors = []
threads = [threading.Thread(target=writer, args=(errors,))
@@ -277,13 +272,8 @@ class TestSavezLoad(RoundtripTest, TestCase):
# e.g. Debian sid of 2012 Jul 05 but was reported to
# trigger the failure on Ubuntu 10.04:
# http://projects.scipy.org/numpy/ticket/1517#comment:2
- fd, tmp = mkstemp(suffix='.npz')
- os.close(fd)
-
- try:
- fp = open(tmp, 'wb')
- np.savez(fp, data='LOVELY LOAD')
- fp.close()
+ with temppath(suffix='.npz') as tmp:
+ np.savez(tmp, data='LOVELY LOAD')
# We need to check if the garbage collector can properly close
# numpy npz file returned by np.load when their reference count
# goes to zero. Python 3 running in debug mode raises a
@@ -299,16 +289,14 @@ class TestSavezLoad(RoundtripTest, TestCase):
except Exception as e:
msg = "Failed to load data from a file: %s" % e
raise AssertionError(msg)
- finally:
- os.remove(tmp)
def test_closing_zipfile_after_load(self):
- # Check that zipfile owns file and can close it.
- # This needs to pass a file name to load for the
- # test.
- with tempdir(prefix="numpy_test_closing_zipfile_after_load_") as tmpdir:
- fd, tmp = mkstemp(suffix='.npz', dir=tmpdir)
- os.close(fd)
+ # Check that zipfile owns file and can close it. This needs to
+ # pass a file name to load for the test. On windows failure will
+ # cause a second error will be raised when the attempt to remove
+ # the open file is made.
+ prefix = 'numpy_test_closing_zipfile_after_load_'
+ with temppath(suffix='.npz', prefix=prefix) as tmp:
np.savez(tmp, lab='place holder')
data = np.load(tmp)
fp = data.zip.fp
@@ -416,15 +404,11 @@ class TestSaveTxt(TestCase):
asbytes('1 2\n3 4\n' + commentstr + test_header_footer + '\n'))
def test_file_roundtrip(self):
- f, name = mkstemp()
- os.close(f)
- try:
+ with temppath() as name:
a = np.array([(1, 2), (3, 4)])
np.savetxt(name, a)
b = np.loadtxt(name)
assert_array_equal(a, b)
- finally:
- os.unlink(name)
def test_complex_arrays(self):
ncols = 2
@@ -739,15 +723,11 @@ class TestLoadTxt(TestCase):
assert_equal(res, tgt)
def test_universal_newline(self):
- f, name = mkstemp()
- os.write(f, b'1 21\r3 42\r')
- os.close(f)
-
- try:
+ with temppath() as name:
+ with open(name, 'w') as f:
+ f.write('1 21\r3 42\r')
data = np.loadtxt(name)
- assert_array_equal(data, [[1, 21], [3, 42]])
- finally:
- os.unlink(name)
+ assert_array_equal(data, [[1, 21], [3, 42]])
def test_empty_field_after_tab(self):
c = TextIO()
@@ -1760,8 +1740,9 @@ M 33 21.99
assert_equal(test, control)
def test_gft_using_filename(self):
- # Test that we can load data from a filename as well as a file object
- wanted = np.arange(6).reshape((2, 3))
+ # Test that we can load data from a filename as well as a file
+ # object
+ tgt = np.arange(6).reshape((2, 3))
if sys.version_info[0] >= 3:
# python 3k is known to fail for '\r'
linesep = ('\n', '\r\n')
@@ -1770,15 +1751,11 @@ M 33 21.99
for sep in linesep:
data = '0 1 2' + sep + '3 4 5'
- f, name = mkstemp()
- # We can't use NamedTemporaryFile on windows, because we cannot
- # reopen the file.
- try:
- os.write(f, asbytes(data))
- assert_array_equal(np.genfromtxt(name), wanted)
- finally:
- os.close(f)
- os.unlink(name)
+ with temppath() as name:
+ with open(name, 'w') as f:
+ f.write(data)
+ res = np.genfromtxt(name)
+ assert_array_equal(res, tgt)
def test_gft_using_generator(self):
# gft doesn't work with unicode.
@@ -1838,16 +1815,15 @@ def test_gzip_loadtxt():
g = gzip.GzipFile(fileobj=s, mode='w')
g.write(b'1 2 3\n')
g.close()
+
s.seek(0)
+ with temppath(suffix='.gz') as name:
+ with open(name, 'wb') as f:
+ f.write(s.read())
+ res = np.loadtxt(name)
+ s.close()
- f, name = mkstemp(suffix='.gz')
- try:
- os.write(f, s.read())
- s.close()
- assert_array_equal(np.loadtxt(name), [1, 2, 3])
- finally:
- os.close(f)
- os.unlink(name)
+ assert_array_equal(res, [1, 2, 3])
def test_gzip_loadtxt_from_string():
diff --git a/numpy/ma/tests/test_mrecords.py b/numpy/ma/tests/test_mrecords.py
index 84b68ba0f..574c65271 100644
--- a/numpy/ma/tests/test_mrecords.py
+++ b/numpy/ma/tests/test_mrecords.py
@@ -15,7 +15,7 @@ import numpy.ma as ma
from numpy import recarray
from numpy.compat import asbytes, asbytes_nested
from numpy.ma import masked, nomask
-from numpy.testing import TestCase, run_module_suite
+from numpy.testing import TestCase, run_module_suite, temppath
from numpy.core.records import (
fromrecords as recfromrecords, fromarrays as recfromarrays
)
@@ -476,7 +476,7 @@ class TestMRecordsImport(TestCase):
def test_fromtextfile(self):
# Tests reading from a text file.
- fcontent = asbytes(
+ fcontent = (
"""#
'One (S)','Two (I)','Three (F)','Four (M)','Five (-)','Six (C)'
'strings',1,1.0,'mixed column',,1
@@ -484,14 +484,10 @@ class TestMRecordsImport(TestCase):
'strings',3,3.0E5,3,,1
'strings',4,-1e-10,,,1
""")
- import os
- import tempfile
- (tmp_fd, tmp_fl) = tempfile.mkstemp()
- os.write(tmp_fd, fcontent)
- os.close(tmp_fd)
- mrectxt = fromtextfile(tmp_fl, delimitor=',', varnames='ABCDEFG')
- os.remove(tmp_fl)
-
+ with temppath() as path:
+ with open(path, 'w') as f:
+ f.write(fcontent)
+ mrectxt = fromtextfile(path, delimitor=',', varnames='ABCDEFG')
self.assertTrue(isinstance(mrectxt, MaskedRecords))
assert_equal(mrectxt.F, [1, 1, 1, 1])
assert_equal(mrectxt.E._mask, [1, 1, 1, 1])
diff --git a/numpy/tests/test_scripts.py b/numpy/tests/test_scripts.py
index 434f17a4a..94587e807 100644
--- a/numpy/tests/test_scripts.py
+++ b/numpy/tests/test_scripts.py
@@ -14,7 +14,7 @@ from nose.tools import assert_equal
from numpy.testing.decorators import skipif
from numpy.testing import assert_
-skipif_inplace = skipif(isfile(pathjoin(dirname(np.__file__), '..', 'setup.py')))
+is_inplace = isfile(pathjoin(dirname(np.__file__), '..', 'setup.py'))
def run_command(cmd, check_code=True):
""" Run command sequence `cmd` returning exit code, stdout, stderr
@@ -58,7 +58,7 @@ def run_command(cmd, check_code=True):
return proc.returncode, stdout, stderr
-@skipif_inplace
+@skipif(is_inplace)
def test_f2py():
# test that we can run f2py script
if sys.platform == 'win32':
@@ -79,4 +79,5 @@ def test_f2py():
break
except:
pass
- assert_(success, "Warning: neither %s nor %s found in path" % f2py_cmds)
+ msg = "Warning: neither %s nor %s found in path" % f2py_cmds
+ assert_(success, msg)