first commit

This commit is contained in:
2018-07-24 15:40:59 +02:00
commit d0d03faed9
1884 changed files with 366061 additions and 0 deletions

View File

@@ -0,0 +1,118 @@
from __future__ import division, absolute_import, print_function
import sys
import numpy as np
from numpy.ctypeslib import ndpointer, load_library
from numpy.distutils.misc_util import get_shared_lib_extension
from numpy.testing import run_module_suite, assert_, assert_raises, dec
try:
cdll = None
if hasattr(sys, 'gettotalrefcount'):
try:
cdll = load_library('multiarray_d', np.core.multiarray.__file__)
except OSError:
pass
if cdll is None:
cdll = load_library('multiarray', np.core.multiarray.__file__)
_HAS_CTYPE = True
except ImportError:
_HAS_CTYPE = False
class TestLoadLibrary(object):
@dec.skipif(not _HAS_CTYPE,
"ctypes not available on this python installation")
@dec.knownfailureif(sys.platform ==
'cygwin', "This test is known to fail on cygwin")
def test_basic(self):
try:
# Should succeed
load_library('multiarray', np.core.multiarray.__file__)
except ImportError as e:
msg = ("ctypes is not available on this python: skipping the test"
" (import error was: %s)" % str(e))
print(msg)
@dec.skipif(not _HAS_CTYPE,
"ctypes not available on this python installation")
@dec.knownfailureif(sys.platform ==
'cygwin', "This test is known to fail on cygwin")
def test_basic2(self):
# Regression for #801: load_library with a full library name
# (including extension) does not work.
try:
try:
so = get_shared_lib_extension(is_python_ext=True)
# Should succeed
load_library('multiarray%s' % so, np.core.multiarray.__file__)
except ImportError:
print("No distutils available, skipping test.")
except ImportError as e:
msg = ("ctypes is not available on this python: skipping the test"
" (import error was: %s)" % str(e))
print(msg)
class TestNdpointer(object):
def test_dtype(self):
dt = np.intc
p = ndpointer(dtype=dt)
assert_(p.from_param(np.array([1], dt)))
dt = '<i4'
p = ndpointer(dtype=dt)
assert_(p.from_param(np.array([1], dt)))
dt = np.dtype('>i4')
p = ndpointer(dtype=dt)
p.from_param(np.array([1], dt))
assert_raises(TypeError, p.from_param,
np.array([1], dt.newbyteorder('swap')))
dtnames = ['x', 'y']
dtformats = [np.intc, np.float64]
dtdescr = {'names': dtnames, 'formats': dtformats}
dt = np.dtype(dtdescr)
p = ndpointer(dtype=dt)
assert_(p.from_param(np.zeros((10,), dt)))
samedt = np.dtype(dtdescr)
p = ndpointer(dtype=samedt)
assert_(p.from_param(np.zeros((10,), dt)))
dt2 = np.dtype(dtdescr, align=True)
if dt.itemsize != dt2.itemsize:
assert_raises(TypeError, p.from_param, np.zeros((10,), dt2))
else:
assert_(p.from_param(np.zeros((10,), dt2)))
def test_ndim(self):
p = ndpointer(ndim=0)
assert_(p.from_param(np.array(1)))
assert_raises(TypeError, p.from_param, np.array([1]))
p = ndpointer(ndim=1)
assert_raises(TypeError, p.from_param, np.array(1))
assert_(p.from_param(np.array([1])))
p = ndpointer(ndim=2)
assert_(p.from_param(np.array([[1]])))
def test_shape(self):
p = ndpointer(shape=(1, 2))
assert_(p.from_param(np.array([[1, 2]])))
assert_raises(TypeError, p.from_param, np.array([[1], [2]]))
p = ndpointer(shape=())
assert_(p.from_param(np.array(1)))
def test_flags(self):
x = np.array([[1, 2], [3, 4]], order='F')
p = ndpointer(flags='FORTRAN')
assert_(p.from_param(x))
p = ndpointer(flags='CONTIGUOUS')
assert_raises(TypeError, p.from_param, x)
p = ndpointer(flags=x.flags.num)
assert_(p.from_param(x))
assert_raises(TypeError, p.from_param, np.array([[1, 2], [3, 4]]))
def test_cache(self):
a1 = ndpointer(dtype=np.float64)
a2 = ndpointer(dtype=np.float64)
assert_(a1 == a2)
if __name__ == "__main__":
run_module_suite()

View File

@@ -0,0 +1,64 @@
from __future__ import division, absolute_import, print_function
import numpy as np
import numpy.matlib
from numpy.testing import assert_array_equal, assert_, run_module_suite
def test_empty():
x = numpy.matlib.empty((2,))
assert_(isinstance(x, np.matrix))
assert_(x.shape, (1, 2))
def test_ones():
assert_array_equal(numpy.matlib.ones((2, 3)),
np.matrix([[ 1., 1., 1.],
[ 1., 1., 1.]]))
assert_array_equal(numpy.matlib.ones(2), np.matrix([[ 1., 1.]]))
def test_zeros():
assert_array_equal(numpy.matlib.zeros((2, 3)),
np.matrix([[ 0., 0., 0.],
[ 0., 0., 0.]]))
assert_array_equal(numpy.matlib.zeros(2), np.matrix([[ 0., 0.]]))
def test_identity():
x = numpy.matlib.identity(2, dtype=int)
assert_array_equal(x, np.matrix([[1, 0], [0, 1]]))
def test_eye():
xc = numpy.matlib.eye(3, k=1, dtype=int)
assert_array_equal(xc, np.matrix([[ 0, 1, 0],
[ 0, 0, 1],
[ 0, 0, 0]]))
assert xc.flags.c_contiguous
assert not xc.flags.f_contiguous
xf = numpy.matlib.eye(3, 4, dtype=int, order='F')
assert_array_equal(xf, np.matrix([[ 1, 0, 0, 0],
[ 0, 1, 0, 0],
[ 0, 0, 1, 0]]))
assert not xf.flags.c_contiguous
assert xf.flags.f_contiguous
def test_rand():
x = numpy.matlib.rand(3)
# check matrix type, array would have shape (3,)
assert_(x.ndim == 2)
def test_randn():
x = np.matlib.randn(3)
# check matrix type, array would have shape (3,)
assert_(x.ndim == 2)
def test_repmat():
a1 = np.arange(4)
x = numpy.matlib.repmat(a1, 2, 2)
y = np.array([[0, 1, 2, 3, 0, 1, 2, 3],
[0, 1, 2, 3, 0, 1, 2, 3]])
assert_array_equal(x, y)
if __name__ == "__main__":
run_module_suite()

View File

@@ -0,0 +1,23 @@
from __future__ import division, absolute_import, print_function
import re
import numpy as np
from numpy.testing import assert_, run_module_suite
def test_valid_numpy_version():
# Verify that the numpy version is a valid one (no .post suffix or other
# nonsense). See gh-6431 for an issue caused by an invalid version.
version_pattern = r"^[0-9]+\.[0-9]+\.[0-9]+(|a[0-9]|b[0-9]|rc[0-9])"
dev_suffix = r"(\.dev0\+([0-9a-f]{7}|Unknown))"
if np.version.release:
res = re.match(version_pattern, np.__version__)
else:
res = re.match(version_pattern + dev_suffix, np.__version__)
assert_(res is not None, np.__version__)
if __name__ == "__main__":
run_module_suite()

View File

@@ -0,0 +1,34 @@
from __future__ import division, absolute_import, print_function
import sys
from numpy.testing import assert_raises, assert_, run_module_suite
if sys.version_info[:2] >= (3, 4):
from importlib import reload
else:
from imp import reload
def test_numpy_reloading():
# gh-7844. Also check that relevant globals retain their identity.
import numpy as np
import numpy._globals
_NoValue = np._NoValue
VisibleDeprecationWarning = np.VisibleDeprecationWarning
ModuleDeprecationWarning = np.ModuleDeprecationWarning
reload(np)
assert_(_NoValue is np._NoValue)
assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning)
assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning)
assert_raises(RuntimeError, reload, numpy._globals)
reload(np)
assert_(_NoValue is np._NoValue)
assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning)
assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning)
if __name__ == "__main__":
run_module_suite()

View File

@@ -0,0 +1,92 @@
""" Test scripts
Test that we can run executable scripts that have been installed with numpy.
"""
from __future__ import division, print_function, absolute_import
import os
from os.path import join as pathjoin, isfile, dirname, basename
import sys
from subprocess import Popen, PIPE
import numpy as np
from numpy.compat.py3k import basestring
from nose.tools import assert_equal
from numpy.testing import assert_, dec
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
Parameters
----------
cmd : str or sequence
string with command name or sequence of strings defining command
check_code : {True, False}, optional
If True, raise error for non-zero return code
Returns
-------
returncode : int
return code from execution of `cmd`
stdout : bytes (python 3) or str (python 2)
stdout from `cmd`
stderr : bytes (python 3) or str (python 2)
stderr from `cmd`
Raises
------
RuntimeError
If `check_code` is True, and return code !=0
"""
cmd = [cmd] if isinstance(cmd, basestring) else list(cmd)
if os.name == 'nt':
# Quote any arguments with spaces. The quotes delimit the arguments
# on Windows, and the arguments might be file paths with spaces.
# On Unix the list elements are each separate arguments.
cmd = ['"{0}"'.format(c) if ' ' in c else c for c in cmd]
proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = proc.communicate()
if proc.poll() is None:
proc.terminate()
if check_code and proc.returncode != 0:
raise RuntimeError('\n'.join(
['Command "{0}" failed with',
'stdout', '------', '{1}', '',
'stderr', '------', '{2}']).format(cmd, stdout, stderr))
return proc.returncode, stdout, stderr
@dec.skipif(is_inplace)
def test_f2py():
# test that we can run f2py script
if sys.platform == 'win32':
exe_dir = dirname(sys.executable)
if exe_dir.endswith('Scripts'): # virtualenv
f2py_cmd = r"%s\f2py.py" % exe_dir
else:
f2py_cmd = r"%s\Scripts\f2py.py" % exe_dir
code, stdout, stderr = run_command([sys.executable, f2py_cmd, '-v'])
success = stdout.strip() == b'2'
assert_(success, "Warning: f2py not found in path")
else:
version = sys.version_info
major = str(version.major)
minor = str(version.minor)
f2py_cmds = ('f2py', 'f2py' + major, 'f2py' + major + '.' + minor)
success = False
for f2py_cmd in f2py_cmds:
try:
code, stdout, stderr = run_command([f2py_cmd, '-v'])
assert_equal(stdout.strip(), b'2')
success = True
break
except Exception:
pass
msg = "Warning: neither %s nor %s nor %s found in path" % f2py_cmds
assert_(success, msg)

View File

@@ -0,0 +1,84 @@
"""
Tests which scan for certain occurrences in the code, they may not find
all of these occurrences but should catch almost all.
"""
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info >= (3, 4):
from pathlib import Path
import ast
import tokenize
import numpy
from numpy.testing import run_module_suite, dec
class ParseCall(ast.NodeVisitor):
def __init__(self):
self.ls = []
def visit_Attribute(self, node):
ast.NodeVisitor.generic_visit(self, node)
self.ls.append(node.attr)
def visit_Name(self, node):
self.ls.append(node.id)
class FindFuncs(ast.NodeVisitor):
def __init__(self, filename):
super().__init__()
self.__filename = filename
def visit_Call(self, node):
p = ParseCall()
p.visit(node.func)
ast.NodeVisitor.generic_visit(self, node)
if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings':
if node.args[0].s == "ignore":
raise AssertionError(
"ignore filter should not be used; found in "
"{} on line {}".format(self.__filename, node.lineno))
if p.ls[-1] == 'warn' and (
len(p.ls) == 1 or p.ls[-2] == 'warnings'):
if "testing/tests/test_warnings.py" is self.__filename:
# This file
return
# See if stacklevel exists:
if len(node.args) == 3:
return
args = {kw.arg for kw in node.keywords}
if "stacklevel" in args:
return
raise AssertionError(
"warnings should have an appropriate stacklevel; found in "
"{} on line {}".format(self.__filename, node.lineno))
@dec.slow
def test_warning_calls():
# combined "ignore" and stacklevel error
base = Path(numpy.__file__).parent
for path in base.rglob("*.py"):
if base / "testing" in path.parents:
continue
if path == base / "__init__.py":
continue
if path == base / "random" / "__init__.py":
continue
# use tokenize to auto-detect encoding on systems where no
# default encoding is defined (e.g. LANG='C')
with tokenize.open(str(path)) as file:
tree = ast.parse(file.read())
FindFuncs(path).visit(tree)
if __name__ == "__main__":
run_module_suite()