diff options
author | Rohit Goswami <rog32@hi.is> | 2021-12-02 21:21:34 +0000 |
---|---|---|
committer | Rohit Goswami <rog32@hi.is> | 2021-12-05 22:23:55 +0000 |
commit | e4ca1fbcc96f956708f2deacb6ae1806cd132fe5 (patch) | |
tree | 6001fb86ee2e1982d712977fad8a5c7dc7a6bc89 /numpy/f2py | |
parent | cd24ca1ef578924bad8c5c31f8939e64e353c256 (diff) | |
download | numpy-e4ca1fbcc96f956708f2deacb6ae1806cd132fe5.tar.gz |
MAINT: Rework whitespace to pass PR checks
Co-authored-by: Charles Harris <charlesr.harris@gmail.com>
Diffstat (limited to 'numpy/f2py')
24 files changed, 880 insertions, 737 deletions
diff --git a/numpy/f2py/tests/test_abstract_interface.py b/numpy/f2py/tests/test_abstract_interface.py index 41b7d21c4..7aecf57fc 100644 --- a/numpy/f2py/tests/test_abstract_interface.py +++ b/numpy/f2py/tests/test_abstract_interface.py @@ -5,9 +5,9 @@ from numpy.f2py import crackfortran class TestAbstractInterface(util.F2PyTest): - suffix = '.f90' + suffix = ".f90" - skip = ['add1', 'add2'] + skip = ["add1", "add2"] code = textwrap.dedent(""" module ops_module @@ -52,7 +52,8 @@ class TestAbstractInterface(util.F2PyTest): def test_parse_abstract_interface(self, tmp_path): # Test gh18403 f_path = Path(tmp_path / "gh18403_mod.f90") - f_path.write_text(textwrap.dedent("""\ + f_path.write_text( + textwrap.dedent("""\ module test abstract interface subroutine foo() @@ -62,5 +63,5 @@ class TestAbstractInterface(util.F2PyTest): """)) mod = crackfortran.crackfortran([str(f_path)]) assert len(mod) == 1 - assert len(mod[0]['body']) == 1 - assert mod[0]['body'][0]['block'] == 'abstract interface' + assert len(mod[0]["body"]) == 1 + assert mod[0]["body"][0]["block"] == "abstract interface" diff --git a/numpy/f2py/tests/test_array_from_pyobj.py b/numpy/f2py/tests/test_array_from_pyobj.py index 0407ff515..26060561a 100644 --- a/numpy/f2py/tests/test_array_from_pyobj.py +++ b/numpy/f2py/tests/test_array_from_pyobj.py @@ -12,6 +12,7 @@ from . import util wrap = None + def setup_module(): """ Build the required testing extension module @@ -30,11 +31,13 @@ def setup_module(): define_macros=[]) """ d = os.path.dirname(__file__) - src = [util.getpath('tests', 'src', 'array_from_pyobj', 'wrapmodule.c'), - util.getpath('src', 'fortranobject.c'), - util.getpath('src', 'fortranobject.h')] + src = [ + util.getpath("tests", "src", "array_from_pyobj", "wrapmodule.c"), + util.getpath("src", "fortranobject.c"), + util.getpath("src", "fortranobject.h"), + ] wrap = util.build_module_distutils(src, config_code, - 'test_array_from_pyobj_ext') + "test_array_from_pyobj_ext") def flags_info(arr): @@ -44,39 +47,49 @@ def flags_info(arr): def flags2names(flags): info = [] - for flagname in ['CONTIGUOUS', 'FORTRAN', 'OWNDATA', 'ENSURECOPY', - 'ENSUREARRAY', 'ALIGNED', 'NOTSWAPPED', 'WRITEABLE', - 'WRITEBACKIFCOPY', 'UPDATEIFCOPY', 'BEHAVED', 'BEHAVED_RO', - 'CARRAY', 'FARRAY' - ]: + for flagname in [ + "CONTIGUOUS", + "FORTRAN", + "OWNDATA", + "ENSURECOPY", + "ENSUREARRAY", + "ALIGNED", + "NOTSWAPPED", + "WRITEABLE", + "WRITEBACKIFCOPY", + "UPDATEIFCOPY", + "BEHAVED", + "BEHAVED_RO", + "CARRAY", + "FARRAY", + ]: if abs(flags) & getattr(wrap, flagname, 0): info.append(flagname) return info class Intent: - def __init__(self, intent_list=[]): self.intent_list = intent_list[:] flags = 0 for i in intent_list: - if i == 'optional': + if i == "optional": flags |= wrap.F2PY_OPTIONAL else: - flags |= getattr(wrap, 'F2PY_INTENT_' + i.upper()) + flags |= getattr(wrap, "F2PY_INTENT_" + i.upper()) self.flags = flags def __getattr__(self, name): name = name.lower() - if name == 'in_': - name = 'in' + if name == "in_": + name = "in" return self.__class__(self.intent_list + [name]) def __str__(self): - return 'intent(%s)' % (','.join(self.intent_list)) + return "intent(%s)" % (",".join(self.intent_list)) def __repr__(self): - return 'Intent(%r)' % (self.intent_list) + return "Intent(%r)" % (self.intent_list) def is_intent(self, *names): for name in names: @@ -87,32 +100,46 @@ class Intent: def is_intent_exact(self, *names): return len(self.intent_list) == len(names) and self.is_intent(*names) -intent = Intent() - -_type_names = ['BOOL', 'BYTE', 'UBYTE', 'SHORT', 'USHORT', 'INT', 'UINT', - 'LONG', 'ULONG', 'LONGLONG', 'ULONGLONG', - 'FLOAT', 'DOUBLE', 'CFLOAT'] - -_cast_dict = {'BOOL': ['BOOL']} -_cast_dict['BYTE'] = _cast_dict['BOOL'] + ['BYTE'] -_cast_dict['UBYTE'] = _cast_dict['BOOL'] + ['UBYTE'] -_cast_dict['BYTE'] = ['BYTE'] -_cast_dict['UBYTE'] = ['UBYTE'] -_cast_dict['SHORT'] = _cast_dict['BYTE'] + ['UBYTE', 'SHORT'] -_cast_dict['USHORT'] = _cast_dict['UBYTE'] + ['BYTE', 'USHORT'] -_cast_dict['INT'] = _cast_dict['SHORT'] + ['USHORT', 'INT'] -_cast_dict['UINT'] = _cast_dict['USHORT'] + ['SHORT', 'UINT'] - -_cast_dict['LONG'] = _cast_dict['INT'] + ['LONG'] -_cast_dict['ULONG'] = _cast_dict['UINT'] + ['ULONG'] - -_cast_dict['LONGLONG'] = _cast_dict['LONG'] + ['LONGLONG'] -_cast_dict['ULONGLONG'] = _cast_dict['ULONG'] + ['ULONGLONG'] -_cast_dict['FLOAT'] = _cast_dict['SHORT'] + ['USHORT', 'FLOAT'] -_cast_dict['DOUBLE'] = _cast_dict['INT'] + ['UINT', 'FLOAT', 'DOUBLE'] +intent = Intent() -_cast_dict['CFLOAT'] = _cast_dict['FLOAT'] + ['CFLOAT'] +_type_names = [ + "BOOL", + "BYTE", + "UBYTE", + "SHORT", + "USHORT", + "INT", + "UINT", + "LONG", + "ULONG", + "LONGLONG", + "ULONGLONG", + "FLOAT", + "DOUBLE", + "CFLOAT", +] + +_cast_dict = {"BOOL": ["BOOL"]} +_cast_dict["BYTE"] = _cast_dict["BOOL"] + ["BYTE"] +_cast_dict["UBYTE"] = _cast_dict["BOOL"] + ["UBYTE"] +_cast_dict["BYTE"] = ["BYTE"] +_cast_dict["UBYTE"] = ["UBYTE"] +_cast_dict["SHORT"] = _cast_dict["BYTE"] + ["UBYTE", "SHORT"] +_cast_dict["USHORT"] = _cast_dict["UBYTE"] + ["BYTE", "USHORT"] +_cast_dict["INT"] = _cast_dict["SHORT"] + ["USHORT", "INT"] +_cast_dict["UINT"] = _cast_dict["USHORT"] + ["SHORT", "UINT"] + +_cast_dict["LONG"] = _cast_dict["INT"] + ["LONG"] +_cast_dict["ULONG"] = _cast_dict["UINT"] + ["ULONG"] + +_cast_dict["LONGLONG"] = _cast_dict["LONG"] + ["LONGLONG"] +_cast_dict["ULONGLONG"] = _cast_dict["ULONG"] + ["ULONGLONG"] + +_cast_dict["FLOAT"] = _cast_dict["SHORT"] + ["USHORT", "FLOAT"] +_cast_dict["DOUBLE"] = _cast_dict["INT"] + ["UINT", "FLOAT", "DOUBLE"] + +_cast_dict["CFLOAT"] = _cast_dict["FLOAT"] + ["CFLOAT"] # 32 bit system malloc typically does not provide the alignment required by # 16 byte long double types this means the inout intent cannot be satisfied @@ -120,15 +147,22 @@ _cast_dict['CFLOAT'] = _cast_dict['FLOAT'] + ['CFLOAT'] # when numpy gains an aligned allocator the tests could be enabled again # # Furthermore, on macOS ARM64, LONGDOUBLE is an alias for DOUBLE. -if ((np.intp().dtype.itemsize != 4 or np.clongdouble().dtype.alignment <= 8) and - sys.platform != 'win32' and - (platform.system(), platform.processor()) != ('Darwin', 'arm')): - _type_names.extend(['LONGDOUBLE', 'CDOUBLE', 'CLONGDOUBLE']) - _cast_dict['LONGDOUBLE'] = _cast_dict['LONG'] + \ - ['ULONG', 'FLOAT', 'DOUBLE', 'LONGDOUBLE'] - _cast_dict['CLONGDOUBLE'] = _cast_dict['LONGDOUBLE'] + \ - ['CFLOAT', 'CDOUBLE', 'CLONGDOUBLE'] - _cast_dict['CDOUBLE'] = _cast_dict['DOUBLE'] + ['CFLOAT', 'CDOUBLE'] +if ((np.intp().dtype.itemsize != 4 or np.clongdouble().dtype.alignment <= 8) + and sys.platform != "win32" + and (platform.system(), platform.processor()) != ("Darwin", "arm")): + _type_names.extend(["LONGDOUBLE", "CDOUBLE", "CLONGDOUBLE"]) + _cast_dict["LONGDOUBLE"] = _cast_dict["LONG"] + [ + "ULONG", + "FLOAT", + "DOUBLE", + "LONGDOUBLE", + ] + _cast_dict["CLONGDOUBLE"] = _cast_dict["LONGDOUBLE"] + [ + "CFLOAT", + "CDOUBLE", + "CLONGDOUBLE", + ] + _cast_dict["CDOUBLE"] = _cast_dict["DOUBLE"] + ["CFLOAT", "CDOUBLE"] class Type: @@ -153,7 +187,7 @@ class Type: def _init(self, name): self.NAME = name.upper() info = typeinfo[self.NAME] - self.type_num = getattr(wrap, 'NPY_' + self.NAME) + self.type_num = getattr(wrap, "NPY_" + self.NAME) assert_equal(self.type_num, info.num) self.dtype = np.dtype(info.type) self.type = info.type @@ -194,7 +228,6 @@ class Type: class Array: - def __init__(self, typ, dims, intent, obj): self.type = typ self.dims = dims @@ -210,16 +243,18 @@ class Array: self.arr_attr = wrap.array_attrs(self.arr) if len(dims) > 1: - if self.intent.is_intent('c'): + if self.intent.is_intent("c"): assert_(intent.flags & wrap.F2PY_INTENT_C) - assert_(not self.arr.flags['FORTRAN'], - repr((self.arr.flags, getattr(obj, 'flags', None)))) - assert_(self.arr.flags['CONTIGUOUS']) + assert_( + not self.arr.flags["FORTRAN"], + repr((self.arr.flags, getattr(obj, "flags", None))), + ) + assert_(self.arr.flags["CONTIGUOUS"]) assert_(not self.arr_attr[6] & wrap.FORTRAN) else: assert_(not intent.flags & wrap.F2PY_INTENT_C) - assert_(self.arr.flags['FORTRAN']) - assert_(not self.arr.flags['CONTIGUOUS']) + assert_(self.arr.flags["FORTRAN"]) + assert_(not self.arr.flags["CONTIGUOUS"]) assert_(self.arr_attr[6] & wrap.FORTRAN) if obj is None: @@ -227,53 +262,71 @@ class Array: self.pyarr_attr = None return - if intent.is_intent('cache'): + if intent.is_intent("cache"): assert_(isinstance(obj, np.ndarray), repr(type(obj))) self.pyarr = np.array(obj).reshape(*dims).copy() else: self.pyarr = np.array( - np.array(obj, dtype=typ.dtypechar).reshape(*dims), - order=self.intent.is_intent('c') and 'C' or 'F') - assert_(self.pyarr.dtype == typ, - repr((self.pyarr.dtype, typ))) - self.pyarr.setflags(write=self.arr.flags['WRITEABLE']) - assert_(self.pyarr.flags['OWNDATA'], (obj, intent)) + np.array(obj, dtype=typ.dtypechar).reshape(*dims), + order=self.intent.is_intent("c") and "C" or "F", + ) + assert_(self.pyarr.dtype == typ, repr((self.pyarr.dtype, typ))) + self.pyarr.setflags(write=self.arr.flags["WRITEABLE"]) + assert_(self.pyarr.flags["OWNDATA"], (obj, intent)) self.pyarr_attr = wrap.array_attrs(self.pyarr) if len(dims) > 1: - if self.intent.is_intent('c'): - assert_(not self.pyarr.flags['FORTRAN']) - assert_(self.pyarr.flags['CONTIGUOUS']) + if self.intent.is_intent("c"): + assert_(not self.pyarr.flags["FORTRAN"]) + assert_(self.pyarr.flags["CONTIGUOUS"]) assert_(not self.pyarr_attr[6] & wrap.FORTRAN) else: - assert_(self.pyarr.flags['FORTRAN']) - assert_(not self.pyarr.flags['CONTIGUOUS']) + assert_(self.pyarr.flags["FORTRAN"]) + assert_(not self.pyarr.flags["CONTIGUOUS"]) assert_(self.pyarr_attr[6] & wrap.FORTRAN) assert_(self.arr_attr[1] == self.pyarr_attr[1]) # nd assert_(self.arr_attr[2] == self.pyarr_attr[2]) # dimensions if self.arr_attr[1] <= 1: - assert_(self.arr_attr[3] == self.pyarr_attr[3], - repr((self.arr_attr[3], self.pyarr_attr[3], - self.arr.tobytes(), self.pyarr.tobytes()))) # strides - assert_(self.arr_attr[5][-2:] == self.pyarr_attr[5][-2:], - repr((self.arr_attr[5], self.pyarr_attr[5]))) # descr - assert_(self.arr_attr[6] == self.pyarr_attr[6], - repr((self.arr_attr[6], self.pyarr_attr[6], - flags2names(0 * self.arr_attr[6] - self.pyarr_attr[6]), - flags2names(self.arr_attr[6]), intent))) # flags - - if intent.is_intent('cache'): - assert_(self.arr_attr[5][3] >= self.type.elsize, - repr((self.arr_attr[5][3], self.type.elsize))) + assert_( + self.arr_attr[3] == self.pyarr_attr[3], + repr(( + self.arr_attr[3], + self.pyarr_attr[3], + self.arr.tobytes(), + self.pyarr.tobytes(), + )), + ) # strides + assert_( + self.arr_attr[5][-2:] == self.pyarr_attr[5][-2:], + repr((self.arr_attr[5], self.pyarr_attr[5])), + ) # descr + assert_( + self.arr_attr[6] == self.pyarr_attr[6], + repr(( + self.arr_attr[6], + self.pyarr_attr[6], + flags2names(0 * self.arr_attr[6] - self.pyarr_attr[6]), + flags2names(self.arr_attr[6]), + intent, + )), + ) # flags + + if intent.is_intent("cache"): + assert_( + self.arr_attr[5][3] >= self.type.elsize, + repr((self.arr_attr[5][3], self.type.elsize)), + ) else: - assert_(self.arr_attr[5][3] == self.type.elsize, - repr((self.arr_attr[5][3], self.type.elsize))) + assert_( + self.arr_attr[5][3] == self.type.elsize, + repr((self.arr_attr[5][3], self.type.elsize)), + ) assert_(self.arr_equal(self.pyarr, self.arr)) if isinstance(self.obj, np.ndarray): if typ.elsize == Type(obj.dtype).elsize: - if not intent.is_intent('copy') and self.arr_attr[1] <= 1: + if not intent.is_intent("copy") and self.arr_attr[1] <= 1: assert_(self.has_shared_memory()) def arr_equal(self, arr1, arr2): @@ -285,8 +338,7 @@ class Array: return str(self.arr) def has_shared_memory(self): - """Check that created array shares data with input array. - """ + """Check that created array shares data with input array.""" if self.obj is self.arr: return True if not isinstance(self.obj, np.ndarray): @@ -296,25 +348,24 @@ class Array: class TestIntent: - def test_in_out(self): - assert_equal(str(intent.in_.out), 'intent(in,out)') - assert_(intent.in_.c.is_intent('c')) - assert_(not intent.in_.c.is_intent_exact('c')) - assert_(intent.in_.c.is_intent_exact('c', 'in')) - assert_(intent.in_.c.is_intent_exact('in', 'c')) - assert_(not intent.in_.is_intent('c')) + assert_equal(str(intent.in_.out), "intent(in,out)") + assert_(intent.in_.c.is_intent("c")) + assert_(not intent.in_.c.is_intent_exact("c")) + assert_(intent.in_.c.is_intent_exact("c", "in")) + assert_(intent.in_.c.is_intent_exact("in", "c")) + assert_(not intent.in_.is_intent("c")) class TestSharedMemory: num2seq = [1, 2] num23seq = [[1, 2, 3], [4, 5, 6]] - @pytest.fixture(autouse=True, scope='class', params=_type_names) + @pytest.fixture(autouse=True, scope="class", params=_type_names) def setup_type(self, request): request.cls.type = Type(request.param) - request.cls.array = lambda self, dims, intent, obj: \ - Array(Type(request.param), dims, intent, obj) + request.cls.array = lambda self, dims, intent, obj: Array( + Type(request.param), dims, intent, obj) def test_in_from_2seq(self): a = self.array([2], intent.in_, self.num2seq) @@ -325,21 +376,21 @@ class TestSharedMemory: obj = np.array(self.num2seq, dtype=t.dtype) a = self.array([len(self.num2seq)], intent.in_, obj) if t.elsize == self.type.elsize: - assert_( - a.has_shared_memory(), repr((self.type.dtype, t.dtype))) + assert_(a.has_shared_memory(), repr( + (self.type.dtype, t.dtype))) else: assert_(not a.has_shared_memory(), repr(t.dtype)) - @pytest.mark.parametrize('write', ['w', 'ro']) - @pytest.mark.parametrize('order', ['C', 'F']) - @pytest.mark.parametrize('inp', ['2seq', '23seq']) + @pytest.mark.parametrize("write", ["w", "ro"]) + @pytest.mark.parametrize("order", ["C", "F"]) + @pytest.mark.parametrize("inp", ["2seq", "23seq"]) def test_in_nocopy(self, write, order, inp): - """Test if intent(in) array can be passed without copies - """ - seq = getattr(self, 'num' + inp) + """Test if intent(in) array can be passed without copies""" + seq = getattr(self, "num" + inp) obj = np.array(seq, dtype=self.type.dtype, order=order) - obj.setflags(write=(write == 'w')) - a = self.array(obj.shape, ((order=='C' and intent.in_.c) or intent.in_), obj) + obj.setflags(write=(write == "w")) + a = self.array(obj.shape, + ((order == "C" and intent.in_.c) or intent.in_), obj) assert a.has_shared_memory() def test_inout_2seq(self): @@ -350,29 +401,29 @@ class TestSharedMemory: try: a = self.array([2], intent.in_.inout, self.num2seq) except TypeError as msg: - if not str(msg).startswith('failed to initialize intent' - '(inout|inplace|cache) array'): + if not str(msg).startswith("failed to initialize intent" + "(inout|inplace|cache) array"): raise else: - raise SystemError('intent(inout) should have failed on sequence') + raise SystemError("intent(inout) should have failed on sequence") def test_f_inout_23seq(self): - obj = np.array(self.num23seq, dtype=self.type.dtype, order='F') + obj = np.array(self.num23seq, dtype=self.type.dtype, order="F") shape = (len(self.num23seq), len(self.num23seq[0])) a = self.array(shape, intent.in_.inout, obj) assert_(a.has_shared_memory()) - obj = np.array(self.num23seq, dtype=self.type.dtype, order='C') + obj = np.array(self.num23seq, dtype=self.type.dtype, order="C") shape = (len(self.num23seq), len(self.num23seq[0])) try: a = self.array(shape, intent.in_.inout, obj) except ValueError as msg: - if not str(msg).startswith('failed to initialize intent' - '(inout) array'): + if not str(msg).startswith("failed to initialize intent" + "(inout) array"): raise else: raise SystemError( - 'intent(inout) should have failed on improper array') + "intent(inout) should have failed on improper array") def test_c_inout_23seq(self): obj = np.array(self.num23seq, dtype=self.type.dtype) @@ -387,22 +438,23 @@ class TestSharedMemory: assert_(not a.has_shared_memory(), repr(t.dtype)) def test_c_in_from_23seq(self): - a = self.array([len(self.num23seq), len(self.num23seq[0])], - intent.in_, self.num23seq) + a = self.array( + [len(self.num23seq), len(self.num23seq[0])], intent.in_, + self.num23seq) assert_(not a.has_shared_memory()) def test_in_from_23casttype(self): for t in self.type.cast_types(): obj = np.array(self.num23seq, dtype=t.dtype) - a = self.array([len(self.num23seq), len(self.num23seq[0])], - intent.in_, obj) + a = self.array( + [len(self.num23seq), len(self.num23seq[0])], intent.in_, obj) assert_(not a.has_shared_memory(), repr(t.dtype)) def test_f_in_from_23casttype(self): for t in self.type.cast_types(): - obj = np.array(self.num23seq, dtype=t.dtype, order='F') - a = self.array([len(self.num23seq), len(self.num23seq[0])], - intent.in_, obj) + obj = np.array(self.num23seq, dtype=t.dtype, order="F") + a = self.array( + [len(self.num23seq), len(self.num23seq[0])], intent.in_, obj) if t.elsize == self.type.elsize: assert_(a.has_shared_memory(), repr(t.dtype)) else: @@ -411,8 +463,8 @@ class TestSharedMemory: def test_c_in_from_23casttype(self): for t in self.type.cast_types(): obj = np.array(self.num23seq, dtype=t.dtype) - a = self.array([len(self.num23seq), len(self.num23seq[0])], - intent.in_.c, obj) + a = self.array( + [len(self.num23seq), len(self.num23seq[0])], intent.in_.c, obj) if t.elsize == self.type.elsize: assert_(a.has_shared_memory(), repr(t.dtype)) else: @@ -420,16 +472,18 @@ class TestSharedMemory: def test_f_copy_in_from_23casttype(self): for t in self.type.cast_types(): - obj = np.array(self.num23seq, dtype=t.dtype, order='F') - a = self.array([len(self.num23seq), len(self.num23seq[0])], - intent.in_.copy, obj) + obj = np.array(self.num23seq, dtype=t.dtype, order="F") + a = self.array( + [len(self.num23seq), len(self.num23seq[0])], intent.in_.copy, + obj) assert_(not a.has_shared_memory(), repr(t.dtype)) def test_c_copy_in_from_23casttype(self): for t in self.type.cast_types(): obj = np.array(self.num23seq, dtype=t.dtype) - a = self.array([len(self.num23seq), len(self.num23seq[0])], - intent.in_.c.copy, obj) + a = self.array( + [len(self.num23seq), len(self.num23seq[0])], intent.in_.c.copy, + obj) assert_(not a.has_shared_memory(), repr(t.dtype)) def test_in_cache_from_2casttype(self): @@ -437,14 +491,14 @@ class TestSharedMemory: if t.elsize != self.type.elsize: continue obj = np.array(self.num2seq, dtype=t.dtype) - shape = (len(self.num2seq),) + shape = (len(self.num2seq), ) a = self.array(shape, intent.in_.c.cache, obj) assert_(a.has_shared_memory(), repr(t.dtype)) a = self.array(shape, intent.in_.cache, obj) assert_(a.has_shared_memory(), repr(t.dtype)) - obj = np.array(self.num2seq, dtype=t.dtype, order='F') + obj = np.array(self.num2seq, dtype=t.dtype, order="F") a = self.array(shape, intent.in_.c.cache, obj) assert_(a.has_shared_memory(), repr(t.dtype)) @@ -454,31 +508,31 @@ class TestSharedMemory: try: a = self.array(shape, intent.in_.cache, obj[::-1]) except ValueError as msg: - if not str(msg).startswith('failed to initialize' - ' intent(cache) array'): + if not str(msg).startswith("failed to initialize" + " intent(cache) array"): raise else: raise SystemError( - 'intent(cache) should have failed on multisegmented array') + "intent(cache) should have failed on multisegmented array") def test_in_cache_from_2casttype_failure(self): for t in self.type.all_types(): if t.elsize >= self.type.elsize: continue obj = np.array(self.num2seq, dtype=t.dtype) - shape = (len(self.num2seq),) + shape = (len(self.num2seq), ) try: self.array(shape, intent.in_.cache, obj) # Should succeed except ValueError as msg: - if not str(msg).startswith('failed to initialize' - ' intent(cache) array'): + if not str(msg).startswith("failed to initialize" + " intent(cache) array"): raise else: raise SystemError( - 'intent(cache) should have failed on smaller array') + "intent(cache) should have failed on smaller array") def test_cache_hidden(self): - shape = (2,) + shape = (2, ) a = self.array(shape, intent.cache.hide, None) assert_(a.arr.shape == shape) @@ -490,15 +544,15 @@ class TestSharedMemory: try: a = self.array(shape, intent.cache.hide, None) except ValueError as msg: - if not str(msg).startswith('failed to create intent' - '(cache|hide)|optional array'): + if not str(msg).startswith("failed to create intent" + "(cache|hide)|optional array"): raise else: raise SystemError( - 'intent(cache) should have failed on undefined dimensions') + "intent(cache) should have failed on undefined dimensions") def test_hidden(self): - shape = (2,) + shape = (2, ) a = self.array(shape, intent.hide, None) assert_(a.arr.shape == shape) assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))) @@ -507,27 +561,27 @@ class TestSharedMemory: a = self.array(shape, intent.hide, None) assert_(a.arr.shape == shape) assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))) - assert_(a.arr.flags['FORTRAN'] and not a.arr.flags['CONTIGUOUS']) + assert_(a.arr.flags["FORTRAN"] and not a.arr.flags["CONTIGUOUS"]) shape = (2, 3) a = self.array(shape, intent.c.hide, None) assert_(a.arr.shape == shape) assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))) - assert_(not a.arr.flags['FORTRAN'] and a.arr.flags['CONTIGUOUS']) + assert_(not a.arr.flags["FORTRAN"] and a.arr.flags["CONTIGUOUS"]) shape = (-1, 3) try: a = self.array(shape, intent.hide, None) except ValueError as msg: - if not str(msg).startswith('failed to create intent' - '(cache|hide)|optional array'): + if not str(msg).startswith("failed to create intent" + "(cache|hide)|optional array"): raise else: - raise SystemError('intent(hide) should have failed' - ' on undefined dimensions') + raise SystemError("intent(hide) should have failed" + " on undefined dimensions") def test_optional_none(self): - shape = (2,) + shape = (2, ) a = self.array(shape, intent.optional, None) assert_(a.arr.shape == shape) assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))) @@ -536,17 +590,17 @@ class TestSharedMemory: a = self.array(shape, intent.optional, None) assert_(a.arr.shape == shape) assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))) - assert_(a.arr.flags['FORTRAN'] and not a.arr.flags['CONTIGUOUS']) + assert_(a.arr.flags["FORTRAN"] and not a.arr.flags["CONTIGUOUS"]) shape = (2, 3) a = self.array(shape, intent.c.optional, None) assert_(a.arr.shape == shape) assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))) - assert_(not a.arr.flags['FORTRAN'] and a.arr.flags['CONTIGUOUS']) + assert_(not a.arr.flags["FORTRAN"] and a.arr.flags["CONTIGUOUS"]) def test_optional_from_2seq(self): obj = self.num2seq - shape = (len(obj),) + shape = (len(obj), ) a = self.array(shape, intent.optional, obj) assert_(a.arr.shape == shape) assert_(not a.has_shared_memory()) @@ -564,16 +618,18 @@ class TestSharedMemory: def test_inplace(self): obj = np.array(self.num23seq, dtype=self.type.dtype) - assert_(not obj.flags['FORTRAN'] and obj.flags['CONTIGUOUS']) + assert_(not obj.flags["FORTRAN"] and obj.flags["CONTIGUOUS"]) shape = obj.shape a = self.array(shape, intent.inplace, obj) assert_(obj[1][2] == a.arr[1][2], repr((obj, a.arr))) a.arr[1][2] = 54 - assert_(obj[1][2] == a.arr[1][2] == - np.array(54, dtype=self.type.dtype), repr((obj, a.arr))) + assert_( + obj[1][2] == a.arr[1][2] == np.array(54, dtype=self.type.dtype), + repr((obj, a.arr)), + ) assert_(a.arr is obj) - assert_(obj.flags['FORTRAN']) # obj attributes are changed inplace! - assert_(not obj.flags['CONTIGUOUS']) + assert_(obj.flags["FORTRAN"]) # obj attributes are changed inplace! + assert_(not obj.flags["CONTIGUOUS"]) def test_inplace_from_casttype(self): for t in self.type.cast_types(): @@ -582,14 +638,17 @@ class TestSharedMemory: obj = np.array(self.num23seq, dtype=t.dtype) assert_(obj.dtype.type == t.type) assert_(obj.dtype.type is not self.type.type) - assert_(not obj.flags['FORTRAN'] and obj.flags['CONTIGUOUS']) + assert_(not obj.flags["FORTRAN"] and obj.flags["CONTIGUOUS"]) shape = obj.shape a = self.array(shape, intent.inplace, obj) assert_(obj[1][2] == a.arr[1][2], repr((obj, a.arr))) a.arr[1][2] = 54 - assert_(obj[1][2] == a.arr[1][2] == - np.array(54, dtype=self.type.dtype), repr((obj, a.arr))) + assert_( + obj[1][2] == a.arr[1][2] == np.array(54, + dtype=self.type.dtype), + repr((obj, a.arr)), + ) assert_(a.arr is obj) - assert_(obj.flags['FORTRAN']) # obj attributes changed inplace! - assert_(not obj.flags['CONTIGUOUS']) + assert_(obj.flags["FORTRAN"]) # obj attributes changed inplace! + assert_(not obj.flags["CONTIGUOUS"]) assert_(obj.dtype.type is self.type.type) # obj changed inplace! diff --git a/numpy/f2py/tests/test_assumed_shape.py b/numpy/f2py/tests/test_assumed_shape.py index 8c86edfc8..0d226cb44 100644 --- a/numpy/f2py/tests/test_assumed_shape.py +++ b/numpy/f2py/tests/test_assumed_shape.py @@ -7,12 +7,13 @@ from . import util class TestAssumedShapeSumExample(util.F2PyTest): - sources = [util.getpath('tests', 'src', 'assumed_shape', 'foo_free.f90'), - util.getpath('tests', 'src', 'assumed_shape', 'foo_use.f90'), - util.getpath('tests', 'src', 'assumed_shape', 'precision.f90'), - util.getpath('tests', 'src', 'assumed_shape', 'foo_mod.f90'), - util.getpath('tests', 'src', 'assumed_shape', '.f2py_f2cmap'), - ] + sources = [ + util.getpath("tests", "src", "assumed_shape", "foo_free.f90"), + util.getpath("tests", "src", "assumed_shape", "foo_use.f90"), + util.getpath("tests", "src", "assumed_shape", "precision.f90"), + util.getpath("tests", "src", "assumed_shape", "foo_mod.f90"), + util.getpath("tests", "src", "assumed_shape", ".f2py_f2cmap"), + ] @pytest.mark.slow def test_all(self): @@ -36,7 +37,7 @@ class TestF2cmapOption(TestAssumedShapeSumExample): f2cmap_src = self.sources.pop(-1) self.f2cmap_file = tempfile.NamedTemporaryFile(delete=False) - with open(f2cmap_src, 'rb') as f: + with open(f2cmap_src, "rb") as f: self.f2cmap_file.write(f.read()) self.f2cmap_file.close() diff --git a/numpy/f2py/tests/test_block_docstring.py b/numpy/f2py/tests/test_block_docstring.py index 7d725165b..36446fe64 100644 --- a/numpy/f2py/tests/test_block_docstring.py +++ b/numpy/f2py/tests/test_block_docstring.py @@ -4,6 +4,7 @@ from . import util from numpy.testing import assert_equal, IS_PYPY + class TestBlockDocString(util.F2PyTest): code = """ SUBROUTINE FOO() @@ -14,8 +15,8 @@ class TestBlockDocString(util.F2PyTest): END """ - @pytest.mark.skipif(sys.platform=='win32', - reason='Fails with MinGW64 Gfortran (Issue #9673)') + @pytest.mark.skipif(sys.platform == "win32", + reason="Fails with MinGW64 Gfortran (Issue #9673)") @pytest.mark.xfail(IS_PYPY, reason="PyPy cannot modify tp_doc after PyType_Ready") def test_block_docstring(self): diff --git a/numpy/f2py/tests/test_callback.py b/numpy/f2py/tests/test_callback.py index 5d2aab94d..8682afe05 100644 --- a/numpy/f2py/tests/test_callback.py +++ b/numpy/f2py/tests/test_callback.py @@ -77,7 +77,7 @@ cf2py intent(out) r end """ - @pytest.mark.parametrize('name', 't,t2'.split(',')) + @pytest.mark.parametrize("name", "t,t2".split(",")) def test_all(self, name): self.check_function(name) @@ -116,18 +116,18 @@ cf2py intent(out) r t = getattr(self.module, name) r = t(lambda: 4) assert_(r == 4, repr(r)) - r = t(lambda a: 5, fun_extra_args=(6,)) + r = t(lambda a: 5, fun_extra_args=(6, )) assert_(r == 5, repr(r)) - r = t(lambda a: a, fun_extra_args=(6,)) + r = t(lambda a: a, fun_extra_args=(6, )) assert_(r == 6, repr(r)) - r = t(lambda a: 5 + a, fun_extra_args=(7,)) + r = t(lambda a: 5 + a, fun_extra_args=(7, )) assert_(r == 12, repr(r)) - r = t(lambda a: math.degrees(a), fun_extra_args=(math.pi,)) + r = t(lambda a: math.degrees(a), fun_extra_args=(math.pi, )) assert_(r == 180, repr(r)) - r = t(math.degrees, fun_extra_args=(math.pi,)) + r = t(math.degrees, fun_extra_args=(math.pi, )) assert_(r == 180, repr(r)) - r = t(self.module.func, fun_extra_args=(6,)) + r = t(self.module.func, fun_extra_args=(6, )) assert_(r == 17, repr(r)) r = t(self.module.func0) assert_(r == 11, repr(r)) @@ -135,48 +135,47 @@ cf2py intent(out) r assert_(r == 11, repr(r)) class A: - def __call__(self): return 7 def mth(self): return 9 + a = A() r = t(a) assert_(r == 7, repr(r)) r = t(a.mth) assert_(r == 9, repr(r)) - @pytest.mark.skipif(sys.platform=='win32', - reason='Fails with MinGW64 Gfortran (Issue #9673)') + @pytest.mark.skipif(sys.platform == "win32", + reason="Fails with MinGW64 Gfortran (Issue #9673)") def test_string_callback(self): - def callback(code): - if code == 'r': + if code == "r": return 0 else: return 1 - f = getattr(self.module, 'string_callback') + f = getattr(self.module, "string_callback") r = f(callback) assert_(r == 0, repr(r)) - @pytest.mark.skipif(sys.platform=='win32', - reason='Fails with MinGW64 Gfortran (Issue #9673)') + @pytest.mark.skipif(sys.platform == "win32", + reason="Fails with MinGW64 Gfortran (Issue #9673)") def test_string_callback_array(self): # See gh-10027 - cu = np.zeros((1, 8), 'S1') + cu = np.zeros((1, 8), "S1") def callback(cu, lencu): if cu.shape != (lencu, 8): return 1 - if cu.dtype != 'S1': + if cu.dtype != "S1": return 2 - if not np.all(cu == b''): + if not np.all(cu == b""): return 3 return 0 - f = getattr(self.module, 'string_callback_array') + f = getattr(self.module, "string_callback_array") res = f(callback, cu, len(cu)) assert_(res == 0, repr(res)) @@ -205,8 +204,10 @@ cf2py intent(out) r except Exception: errors.append(traceback.format_exc()) - threads = [threading.Thread(target=runner, args=(arg,)) - for arg in ("t", "t2") for n in range(20)] + threads = [ + threading.Thread(target=runner, args=(arg, )) + for arg in ("t", "t2") for n in range(20) + ] for t in threads: t.start() @@ -222,12 +223,12 @@ cf2py intent(out) r try: self.module.hidden_callback(2) except Exception as msg: - assert_(str(msg).startswith('Callback global_f not defined')) + assert_(str(msg).startswith("Callback global_f not defined")) try: self.module.hidden_callback2(2) except Exception as msg: - assert_(str(msg).startswith('cb: Callback global_f not defined')) + assert_(str(msg).startswith("cb: Callback global_f not defined")) self.module.global_f = lambda x: x + 1 r = self.module.hidden_callback(2) @@ -241,7 +242,7 @@ cf2py intent(out) r try: self.module.hidden_callback(2) except Exception as msg: - assert_(str(msg).startswith('Callback global_f not defined')) + assert_(str(msg).startswith("Callback global_f not defined")) self.module.global_f = lambda x=0: x + 3 r = self.module.hidden_callback(2) @@ -257,15 +258,15 @@ class TestF77CallbackPythonTLS(TestF77Callback): Callback tests using Python thread-local storage instead of compiler-provided """ + options = ["-DF2PY_USE_PYTHON_TLS"] class TestF90Callback(util.F2PyTest): - suffix = '.f90' + suffix = ".f90" - code = textwrap.dedent( - """ + code = textwrap.dedent(""" function gh17797(f, y) result(r) external f integer(8) :: r, f @@ -276,7 +277,6 @@ class TestF90Callback(util.F2PyTest): """) def test_gh17797(self): - def incr(x): return x + 123 @@ -292,10 +292,9 @@ class TestGH18335(util.F2PyTest): other tests! """ - suffix = '.f90' + suffix = ".f90" - code = textwrap.dedent( - """ + code = textwrap.dedent(""" ! When gh18335_workaround is defined as an extension, ! the issue cannot be reproduced. !subroutine gh18335_workaround(f, y) @@ -316,7 +315,6 @@ class TestGH18335(util.F2PyTest): """) def test_gh18335(self): - def foo(x): x[0] += 1 diff --git a/numpy/f2py/tests/test_common.py b/numpy/f2py/tests/test_common.py index 62587e7a9..056ae5ee8 100644 --- a/numpy/f2py/tests/test_common.py +++ b/numpy/f2py/tests/test_common.py @@ -7,16 +7,16 @@ from . import util from numpy.testing import assert_array_equal + class TestCommonBlock(util.F2PyTest): - sources = [util.getpath('tests', 'src', 'common', 'block.f')] + sources = [util.getpath("tests", "src", "common", "block.f")] - @pytest.mark.skipif(sys.platform=='win32', - reason='Fails with MinGW64 Gfortran (Issue #9673)') + @pytest.mark.skipif(sys.platform == "win32", + reason="Fails with MinGW64 Gfortran (Issue #9673)") def test_common_block(self): self.module.initcb() assert_array_equal(self.module.block.long_bn, np.array(1.0, dtype=np.float64)) assert_array_equal(self.module.block.string_bn, - np.array('2', dtype='|S1')) - assert_array_equal(self.module.block.ok, - np.array(3, dtype=np.int32)) + np.array("2", dtype="|S1")) + assert_array_equal(self.module.block.ok, np.array(3, dtype=np.int32)) diff --git a/numpy/f2py/tests/test_compile_function.py b/numpy/f2py/tests/test_compile_function.py index 33e320731..e92362d82 100644 --- a/numpy/f2py/tests/test_compile_function.py +++ b/numpy/f2py/tests/test_compile_function.py @@ -17,14 +17,13 @@ def setup_module(): if not util.has_c_compiler(): pytest.skip("Needs C compiler") if not util.has_f77_compiler(): - pytest.skip('Needs FORTRAN 77 compiler') + pytest.skip("Needs FORTRAN 77 compiler") # extra_args can be a list (since gh-11937) or string. # also test absence of extra_args -@pytest.mark.parametrize( - "extra_args", [['--noopt', '--debug'], '--noopt --debug', ''] - ) +@pytest.mark.parametrize("extra_args", + [["--noopt", "--debug"], "--noopt --debug", ""]) @pytest.mark.leaks_references(reason="Imported module seems never deleted.") def test_f2py_init_compile(extra_args): # flush through the f2py __init__ compile() function code path as a @@ -33,7 +32,7 @@ def test_f2py_init_compile(extra_args): # the Fortran 77 syntax requires 6 spaces before any commands, but # more space may be added/ - fsource = """ + fsource = """ integer function foo() foo = 10 + 5 return @@ -45,7 +44,7 @@ def test_f2py_init_compile(extra_args): modname = util.get_temp_module_name() cwd = os.getcwd() - target = os.path.join(moddir, str(uuid.uuid4()) + '.f') + target = os.path.join(moddir, str(uuid.uuid4()) + ".f") # try running compile() with and without a source_fn provided so # that the code path where a temporary file for writing Fortran # source is created is also explored @@ -55,28 +54,26 @@ def test_f2py_init_compile(extra_args): # its own invocation of subprocess that circumvents the # f2py.compile code block under test with util.switchdir(moddir): - ret_val = numpy.f2py.compile( - fsource, - modulename=modname, - extra_args=extra_args, - source_fn=source_fn - ) + ret_val = numpy.f2py.compile(fsource, + modulename=modname, + extra_args=extra_args, + source_fn=source_fn) # check for compile success return value assert_equal(ret_val, 0) - # we are not currently able to import the Python-Fortran - # interface module on Windows / Appveyor, even though we do get - # successful compilation on that platform with Python 3.x - if sys.platform != 'win32': - # check for sensible result of Fortran function; that means - # we can import the module name in Python and retrieve the - # result of the sum operation + # we are not currently able to import the Python-Fortran + # interface module on Windows / Appveyor, even though we do get + # successful compilation on that platform with Python 3.x + if sys.platform != "win32": + # check for sensible result of Fortran function; that means + # we can import the module name in Python and retrieve the + # result of the sum operation return_check = import_module(modname) calc_result = return_check.foo() assert_equal(calc_result, 15) - # Removal from sys.modules, is not as such necessary. Even with - # removal, the module (dict) stays alive. + # Removal from sys.modules, is not as such necessary. Even with + # removal, the module (dict) stays alive. del sys.modules[modname] @@ -96,7 +93,7 @@ def test_f2py_init_compile_bad_cmd(): # downstream NOTE: how bad of an idea is this patching? try: temp = sys.executable - sys.executable = 'does not exist' + sys.executable = "does not exist" # the OSError should take precedence over invalid Fortran ret_val = numpy.f2py.compile(b"invalid") @@ -105,14 +102,17 @@ def test_f2py_init_compile_bad_cmd(): sys.executable = temp -@pytest.mark.parametrize('fsource', - ['program test_f2py\nend program test_f2py', - b'program test_f2py\nend program test_f2py',]) +@pytest.mark.parametrize( + "fsource", + [ + "program test_f2py\nend program test_f2py", + b"program test_f2py\nend program test_f2py", + ], +) def test_compile_from_strings(tmpdir, fsource): # Make sure we can compile str and bytes gh-12796 with util.switchdir(tmpdir): - ret_val = numpy.f2py.compile( - fsource, - modulename='test_compile_from_strings', - extension='.f90') + ret_val = numpy.f2py.compile(fsource, + modulename="test_compile_from_strings", + extension=".f90") assert_equal(ret_val, 0) diff --git a/numpy/f2py/tests/test_crackfortran.py b/numpy/f2py/tests/test_crackfortran.py index 039e085b4..a9a818155 100644 --- a/numpy/f2py/tests/test_crackfortran.py +++ b/numpy/f2py/tests/test_crackfortran.py @@ -36,15 +36,15 @@ class TestNoSpace(util.F2PyTest): assert_array_equal(k, w + 1) self.module.subc([w, k]) assert_array_equal(k, w + 1) - assert self.module.t0(23) == b'2' + assert self.module.t0(23) == b"2" -class TestPublicPrivate(): - +class TestPublicPrivate: def test_defaultPrivate(self, tmp_path): f_path = tmp_path / "mod.f90" - with f_path.open('w') as ff: - ff.write(textwrap.dedent("""\ + with f_path.open("w") as ff: + ff.write( + textwrap.dedent("""\ module foo private integer :: a @@ -60,17 +60,18 @@ class TestPublicPrivate(): mod = crackfortran.crackfortran([str(f_path)]) assert len(mod) == 1 mod = mod[0] - assert 'private' in mod['vars']['a']['attrspec'] - assert 'public' not in mod['vars']['a']['attrspec'] - assert 'private' in mod['vars']['b']['attrspec'] - assert 'public' not in mod['vars']['b']['attrspec'] - assert 'private' not in mod['vars']['seta']['attrspec'] - assert 'public' in mod['vars']['seta']['attrspec'] + assert "private" in mod["vars"]["a"]["attrspec"] + assert "public" not in mod["vars"]["a"]["attrspec"] + assert "private" in mod["vars"]["b"]["attrspec"] + assert "public" not in mod["vars"]["b"]["attrspec"] + assert "private" not in mod["vars"]["seta"]["attrspec"] + assert "public" in mod["vars"]["seta"]["attrspec"] def test_defaultPublic(self, tmp_path): f_path = tmp_path / "mod.f90" - with f_path.open('w') as ff: - ff.write(textwrap.dedent("""\ + with f_path.open("w") as ff: + ff.write( + textwrap.dedent("""\ module foo public integer, private :: a @@ -85,10 +86,10 @@ class TestPublicPrivate(): mod = crackfortran.crackfortran([str(f_path)]) assert len(mod) == 1 mod = mod[0] - assert 'private' in mod['vars']['a']['attrspec'] - assert 'public' not in mod['vars']['a']['attrspec'] - assert 'private' not in mod['vars']['seta']['attrspec'] - assert 'public' in mod['vars']['seta']['attrspec'] + assert "private" in mod["vars"]["a"]["attrspec"] + assert "public" not in mod["vars"]["a"]["attrspec"] + assert "private" not in mod["vars"]["seta"]["attrspec"] + assert "public" in mod["vars"]["seta"]["attrspec"] class TestExternal(util.F2PyTest): @@ -111,19 +112,21 @@ class TestExternal(util.F2PyTest): def test_external_as_statement(self): def incr(x): return x + 123 + r = self.module.external_as_statement(incr) assert r == 123 def test_external_as_attribute(self): def incr(x): return x + 123 + r = self.module.external_as_attribute(incr) assert r == 123 class TestCrackFortran(util.F2PyTest): - suffix = '.f90' + suffix = ".f90" code = textwrap.dedent(""" subroutine gh2848( & @@ -146,7 +149,7 @@ class TestCrackFortran(util.F2PyTest): assert r == (1, 2) -class TestMarkinnerspaces(): +class TestMarkinnerspaces: # issue #14118: markinnerspaces does not handle multiple quotations def test_do_not_touch_normal_spaces(self): @@ -155,13 +158,13 @@ class TestMarkinnerspaces(): assert_equal(markinnerspaces(i), i) def test_one_relevant_space(self): - assert_equal(markinnerspaces("a 'b c' \\\' \\\'"), "a 'b@_@c' \\' \\'") + assert_equal(markinnerspaces("a 'b c' \\' \\'"), "a 'b@_@c' \\' \\'") assert_equal(markinnerspaces(r'a "b c" \" \"'), r'a "b@_@c" \" \"') def test_ignore_inner_quotes(self): - assert_equal(markinnerspaces('a \'b c" " d\' e'), + assert_equal(markinnerspaces("a 'b c\" \" d' e"), "a 'b@_@c\"@_@\"@_@d' e") - assert_equal(markinnerspaces('a "b c\' \' d" e'), + assert_equal(markinnerspaces("a \"b c' ' d\" e"), "a \"b@_@c'@_@'@_@d\" e") def test_multiple_relevant_spaces(self): @@ -200,7 +203,7 @@ class TestDimSpec(util.F2PyTest): """ - suffix = '.f90' + suffix = ".f90" code_template = textwrap.dedent(""" function get_arr_size_{count}(a, n) result (length) @@ -221,33 +224,36 @@ class TestDimSpec(util.F2PyTest): end subroutine """) - linear_dimspecs = ['n', '2*n', '2:n', 'n/2', '5 - n/2', '3*n:20', - 'n*(n+1):n*(n+5)'] - nonlinear_dimspecs = ['2*n:3*n*n+2*n'] + linear_dimspecs = [ + "n", "2*n", "2:n", "n/2", "5 - n/2", "3*n:20", "n*(n+1):n*(n+5)" + ] + nonlinear_dimspecs = ["2*n:3*n*n+2*n"] all_dimspecs = linear_dimspecs + nonlinear_dimspecs - code = '' + code = "" for count, dimspec in enumerate(all_dimspecs): code += code_template.format( - count=count, dimspec=dimspec, - first=dimspec.split(':')[0] if ':' in dimspec else '1') + count=count, + dimspec=dimspec, + first=dimspec.split(":")[0] if ":" in dimspec else "1", + ) - @pytest.mark.parametrize('dimspec', all_dimspecs) + @pytest.mark.parametrize("dimspec", all_dimspecs) def test_array_size(self, dimspec): count = self.all_dimspecs.index(dimspec) - get_arr_size = getattr(self.module, f'get_arr_size_{count}') + get_arr_size = getattr(self.module, f"get_arr_size_{count}") for n in [1, 2, 3, 4, 5]: sz, a = get_arr_size(n) assert len(a) == sz - @pytest.mark.parametrize('dimspec', all_dimspecs) + @pytest.mark.parametrize("dimspec", all_dimspecs) def test_inv_array_size(self, dimspec): count = self.all_dimspecs.index(dimspec) - get_arr_size = getattr(self.module, f'get_arr_size_{count}') - get_inv_arr_size = getattr(self.module, f'get_inv_arr_size_{count}') + get_arr_size = getattr(self.module, f"get_arr_size_{count}") + get_inv_arr_size = getattr(self.module, f"get_inv_arr_size_{count}") for n in [1, 2, 3, 4, 5]: sz, a = get_arr_size(n) @@ -266,11 +272,12 @@ class TestDimSpec(util.F2PyTest): assert sz == sz1, (n, n1, sz, sz1) -class TestModuleDeclaration(): +class TestModuleDeclaration: def test_dependencies(self, tmp_path): f_path = tmp_path / "mod.f90" - with f_path.open('w') as ff: - ff.write(textwrap.dedent("""\ + with f_path.open("w") as ff: + ff.write( + textwrap.dedent("""\ module foo type bar character(len = 4) :: text @@ -280,4 +287,4 @@ class TestModuleDeclaration(): """)) mod = crackfortran.crackfortran([str(f_path)]) assert len(mod) == 1 - assert mod[0]['vars']['abar']['='] == "bar('abar')" + assert mod[0]["vars"]["abar"]["="] == "bar('abar')" diff --git a/numpy/f2py/tests/test_kind.py b/numpy/f2py/tests/test_kind.py index 2ac519ca7..78a11fc6c 100644 --- a/numpy/f2py/tests/test_kind.py +++ b/numpy/f2py/tests/test_kind.py @@ -4,12 +4,13 @@ import pytest from numpy.testing import assert_ from numpy.f2py.crackfortran import ( _selected_int_kind_func as selected_int_kind, - _selected_real_kind_func as selected_real_kind - ) + _selected_real_kind_func as selected_real_kind, +) from . import util + class TestKind(util.F2PyTest): - sources = [util.getpath('tests', 'src', 'kind', 'foo.f90')] + sources = [util.getpath("tests", "src", "kind", "foo.f90")] @pytest.mark.slow def test_all(self): @@ -17,11 +18,15 @@ class TestKind(util.F2PyTest): selectedintkind = self.module.selectedintkind for i in range(40): - assert_(selectedintkind(i) in [selected_int_kind(i), -1], - 'selectedintkind(%s): expected %r but got %r' % - (i, selected_int_kind(i), selectedintkind(i))) + assert_( + selectedintkind(i) in [selected_int_kind(i), -1], + "selectedintkind(%s): expected %r but got %r" % + (i, selected_int_kind(i), selectedintkind(i)), + ) for i in range(20): - assert_(selectedrealkind(i) in [selected_real_kind(i), -1], - 'selectedrealkind(%s): expected %r but got %r' % - (i, selected_real_kind(i), selectedrealkind(i))) + assert_( + selectedrealkind(i) in [selected_real_kind(i), -1], + "selectedrealkind(%s): expected %r but got %r" % + (i, selected_real_kind(i), selectedrealkind(i)), + ) diff --git a/numpy/f2py/tests/test_mixed.py b/numpy/f2py/tests/test_mixed.py index 266e9c0d9..95444bea5 100644 --- a/numpy/f2py/tests/test_mixed.py +++ b/numpy/f2py/tests/test_mixed.py @@ -6,11 +6,12 @@ from numpy.testing import assert_, assert_equal, IS_PYPY from . import util - class TestMixed(util.F2PyTest): - sources = [util.getpath('tests', 'src', 'mixed', 'foo.f'), - util.getpath('tests', 'src', 'mixed', 'foo_fixed.f90'), - util.getpath('tests', 'src', 'mixed', 'foo_free.f90')] + sources = [ + util.getpath("tests", "src", "mixed", "foo.f"), + util.getpath("tests", "src", "mixed", "foo_fixed.f90"), + util.getpath("tests", "src", "mixed", "foo_free.f90"), + ] def test_all(self): assert_(self.module.bar11() == 11) diff --git a/numpy/f2py/tests/test_module_doc.py b/numpy/f2py/tests/test_module_doc.py index 92c03c003..b66cff000 100644 --- a/numpy/f2py/tests/test_module_doc.py +++ b/numpy/f2py/tests/test_module_doc.py @@ -8,19 +8,23 @@ from numpy.testing import assert_equal, IS_PYPY class TestModuleDocString(util.F2PyTest): - sources = [util.getpath('tests', 'src', 'module_data', 'module_data_docstring.f90')] + sources = [ + util.getpath("tests", "src", "module_data", + "module_data_docstring.f90") + ] - @pytest.mark.skipif(sys.platform=='win32', - reason='Fails with MinGW64 Gfortran (Issue #9673)') + @pytest.mark.skipif(sys.platform == "win32", + reason="Fails with MinGW64 Gfortran (Issue #9673)") @pytest.mark.xfail(IS_PYPY, reason="PyPy cannot modify tp_doc after PyType_Ready") def test_module_docstring(self): - assert_equal(self.module.mod.__doc__, - textwrap.dedent('''\ + assert_equal( + self.module.mod.__doc__, + textwrap.dedent("""\ i : 'i'-scalar x : 'i'-array(4) a : 'f'-array(2,3) b : 'f'-array(-1,-1), not allocated\x00 foo()\n - Wrapper for ``foo``.\n\n''') - ) + Wrapper for ``foo``.\n\n"""), + ) diff --git a/numpy/f2py/tests/test_parameter.py b/numpy/f2py/tests/test_parameter.py index 22e1b52d3..4ea102e84 100644 --- a/numpy/f2py/tests/test_parameter.py +++ b/numpy/f2py/tests/test_parameter.py @@ -6,13 +6,15 @@ from numpy.testing import assert_raises, assert_equal from . import util + class TestParameters(util.F2PyTest): # Check that intent(in out) translates as intent(inout) - sources = [util.getpath('tests', 'src', 'parameter', 'constant_real.f90'), - util.getpath('tests', 'src', 'parameter', 'constant_integer.f90'), - util.getpath('tests', 'src', 'parameter', 'constant_both.f90'), - util.getpath('tests', 'src', 'parameter', 'constant_compound.f90'), - util.getpath('tests', 'src', 'parameter', 'constant_non_compound.f90'), + sources = [ + util.getpath("tests", "src", "parameter", "constant_real.f90"), + util.getpath("tests", "src", "parameter", "constant_integer.f90"), + util.getpath("tests", "src", "parameter", "constant_both.f90"), + util.getpath("tests", "src", "parameter", "constant_compound.f90"), + util.getpath("tests", "src", "parameter", "constant_non_compound.f90"), ] @pytest.mark.slow @@ -24,7 +26,7 @@ class TestParameters(util.F2PyTest): # check values with contiguous array x = np.arange(3, dtype=np.float32) self.module.foo_single(x) - assert_equal(x, [0 + 1 + 2*3, 1, 2]) + assert_equal(x, [0 + 1 + 2 * 3, 1, 2]) @pytest.mark.slow def test_constant_real_double(self): @@ -35,7 +37,7 @@ class TestParameters(util.F2PyTest): # check values with contiguous array x = np.arange(3, dtype=np.float64) self.module.foo_double(x) - assert_equal(x, [0 + 1 + 2*3, 1, 2]) + assert_equal(x, [0 + 1 + 2 * 3, 1, 2]) @pytest.mark.slow def test_constant_compound_int(self): @@ -46,14 +48,14 @@ class TestParameters(util.F2PyTest): # check values with contiguous array x = np.arange(3, dtype=np.int32) self.module.foo_compound_int(x) - assert_equal(x, [0 + 1 + 2*6, 1, 2]) + assert_equal(x, [0 + 1 + 2 * 6, 1, 2]) @pytest.mark.slow def test_constant_non_compound_int(self): # check values x = np.arange(4, dtype=np.int32) self.module.foo_non_compound_int(x) - assert_equal(x, [0 + 1 + 2 + 3*4, 1, 2, 3]) + assert_equal(x, [0 + 1 + 2 + 3 * 4, 1, 2, 3]) @pytest.mark.slow def test_constant_integer_int(self): @@ -64,7 +66,7 @@ class TestParameters(util.F2PyTest): # check values with contiguous array x = np.arange(3, dtype=np.int32) self.module.foo_int(x) - assert_equal(x, [0 + 1 + 2*3, 1, 2]) + assert_equal(x, [0 + 1 + 2 * 3, 1, 2]) @pytest.mark.slow def test_constant_integer_long(self): @@ -75,7 +77,7 @@ class TestParameters(util.F2PyTest): # check values with contiguous array x = np.arange(3, dtype=np.int64) self.module.foo_long(x) - assert_equal(x, [0 + 1 + 2*3, 1, 2]) + assert_equal(x, [0 + 1 + 2 * 3, 1, 2]) @pytest.mark.slow def test_constant_both(self): @@ -86,7 +88,7 @@ class TestParameters(util.F2PyTest): # check values with contiguous array x = np.arange(3, dtype=np.float64) self.module.foo(x) - assert_equal(x, [0 + 1*3*3 + 2*3*3, 1*3, 2*3]) + assert_equal(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3]) @pytest.mark.slow def test_constant_no(self): @@ -97,7 +99,7 @@ class TestParameters(util.F2PyTest): # check values with contiguous array x = np.arange(3, dtype=np.float64) self.module.foo_no(x) - assert_equal(x, [0 + 1*3*3 + 2*3*3, 1*3, 2*3]) + assert_equal(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3]) @pytest.mark.slow def test_constant_sum(self): @@ -108,4 +110,4 @@ class TestParameters(util.F2PyTest): # check values with contiguous array x = np.arange(3, dtype=np.float64) self.module.foo_sum(x) - assert_equal(x, [0 + 1*3*3 + 2*3*3, 1*3, 2*3]) + assert_equal(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3]) diff --git a/numpy/f2py/tests/test_quoted_character.py b/numpy/f2py/tests/test_quoted_character.py index 20c77666c..efb9ad08b 100644 --- a/numpy/f2py/tests/test_quoted_character.py +++ b/numpy/f2py/tests/test_quoted_character.py @@ -26,7 +26,7 @@ Cf2py intent(out) OUT1, OUT2, OUT3, OUT4, OUT5, OUT6 END """ - @pytest.mark.skipif(sys.platform=='win32', - reason='Fails with MinGW64 Gfortran (Issue #9673)') + @pytest.mark.skipif(sys.platform == "win32", + reason="Fails with MinGW64 Gfortran (Issue #9673)") def test_quoted_character(self): - assert_equal(self.module.foo(), (b"'", b'"', b';', b'!', b'(', b')')) + assert_equal(self.module.foo(), (b"'", b'"', b";", b"!", b"(", b")")) diff --git a/numpy/f2py/tests/test_regression.py b/numpy/f2py/tests/test_regression.py index da279d772..682b9e98c 100644 --- a/numpy/f2py/tests/test_regression.py +++ b/numpy/f2py/tests/test_regression.py @@ -9,7 +9,7 @@ from . import util class TestIntentInOut(util.F2PyTest): # Check that intent(in out) translates as intent(inout) - sources = [util.getpath('tests', 'src', 'regression', 'inout.f90')] + sources = [util.getpath("tests", "src", "regression", "inout.f90")] @pytest.mark.slow def test_inout(self): @@ -26,18 +26,22 @@ class TestIntentInOut(util.F2PyTest): class TestNumpyVersionAttribute(util.F2PyTest): # Check that th attribute __f2py_numpy_version__ is present # in the compiled module and that has the value np.__version__. - sources = [util.getpath('tests', 'src', 'regression', 'inout.f90')] + sources = [util.getpath("tests", "src", "regression", "inout.f90")] @pytest.mark.slow def test_numpy_version_attribute(self): # Check that self.module has an attribute named "__f2py_numpy_version__" - assert_(hasattr(self.module, "__f2py_numpy_version__"), - msg="Fortran module does not have __f2py_numpy_version__") + assert_( + hasattr(self.module, "__f2py_numpy_version__"), + msg="Fortran module does not have __f2py_numpy_version__", + ) # Check that the attribute __f2py_numpy_version__ is a string - assert_(isinstance(self.module.__f2py_numpy_version__, str), - msg="__f2py_numpy_version__ is not a string") + assert_( + isinstance(self.module.__f2py_numpy_version__, str), + msg="__f2py_numpy_version__ is not a string", + ) # Check that __f2py_numpy_version__ has the value numpy.__version__ assert_string_equal(np.__version__, self.module.__f2py_numpy_version__) @@ -46,6 +50,5 @@ class TestNumpyVersionAttribute(util.F2PyTest): def test_include_path(): incdir = np.f2py.get_include() fnames_in_dir = os.listdir(incdir) - for fname in ('fortranobject.c', 'fortranobject.h'): + for fname in ("fortranobject.c", "fortranobject.h"): assert fname in fnames_in_dir - diff --git a/numpy/f2py/tests/test_return_character.py b/numpy/f2py/tests/test_return_character.py index 2c999ed0b..3c3a43e1b 100644 --- a/numpy/f2py/tests/test_return_character.py +++ b/numpy/f2py/tests/test_return_character.py @@ -4,29 +4,29 @@ from numpy import array from numpy.testing import assert_ from . import util import platform -IS_S390X = platform.machine() == 's390x' +IS_S390X = platform.machine() == "s390x" -class TestReturnCharacter(util.F2PyTest): +class TestReturnCharacter(util.F2PyTest): def check_function(self, t, tname): - if tname in ['t0', 't1', 's0', 's1']: - assert_(t(23) == b'2') - r = t('ab') - assert_(r == b'a', repr(r)) - r = t(array('ab')) - assert_(r == b'a', repr(r)) - r = t(array(77, 'u1')) - assert_(r == b'M', repr(r)) - #assert_(_raises(ValueError, t, array([77,87]))) - #assert_(_raises(ValueError, t, array(77))) - elif tname in ['ts', 'ss']: - assert_(t(23) == b'23', repr(t(23))) - assert_(t('123456789abcdef') == b'123456789a') - elif tname in ['t5', 's5']: - assert_(t(23) == b'23', repr(t(23))) - assert_(t('ab') == b'ab', repr(t('ab'))) - assert_(t('123456789abcdef') == b'12345') + if tname in ["t0", "t1", "s0", "s1"]: + assert_(t(23) == b"2") + r = t("ab") + assert_(r == b"a", repr(r)) + r = t(array("ab")) + assert_(r == b"a", repr(r)) + r = t(array(77, "u1")) + assert_(r == b"M", repr(r)) + # assert_(_raises(ValueError, t, array([77,87]))) + # assert_(_raises(ValueError, t, array(77))) + elif tname in ["ts", "ss"]: + assert_(t(23) == b"23", repr(t(23))) + assert_(t("123456789abcdef") == b"123456789a") + elif tname in ["t5", "s5"]: + assert_(t(23) == b"23", repr(t(23))) + assert_(t("ab") == b"ab", repr(t("ab"))) + assert_(t("123456789abcdef") == b"12345") else: raise NotImplementedError @@ -81,7 +81,7 @@ cf2py intent(out) ts """ @pytest.mark.xfail(IS_S390X, reason="callback returns ' '") - @pytest.mark.parametrize('name', 't0,t1,t5,s0,s1,s5,ss'.split(',')) + @pytest.mark.parametrize("name", "t0,t1,t5,s0,s1,s5,ss".split(",")) def test_all(self, name): self.check_function(getattr(self.module, name), name) @@ -140,6 +140,6 @@ end module f90_return_char """ @pytest.mark.xfail(IS_S390X, reason="callback returns ' '") - @pytest.mark.parametrize('name', 't0,t1,t5,ts,s0,s1,s5,ss'.split(',')) + @pytest.mark.parametrize("name", "t0,t1,t5,ts,s0,s1,s5,ss".split(",")) def test_all(self, name): self.check_function(getattr(self.module.f90_return_char, name), name) diff --git a/numpy/f2py/tests/test_return_complex.py b/numpy/f2py/tests/test_return_complex.py index 3d2e2b94f..ae0e3ab25 100644 --- a/numpy/f2py/tests/test_return_complex.py +++ b/numpy/f2py/tests/test_return_complex.py @@ -6,9 +6,8 @@ from . import util class TestReturnComplex(util.F2PyTest): - def check_function(self, t, tname): - if tname in ['t0', 't8', 's0', 's8']: + if tname in ["t0", "t8", "s0", "s8"]: err = 1e-5 else: err = 0.0 @@ -16,27 +15,27 @@ class TestReturnComplex(util.F2PyTest): assert_(abs(t(234.6) - 234.6) <= err) assert_(abs(t(234) - 234.0) <= err) assert_(abs(t(234.6 + 3j) - (234.6 + 3j)) <= err) - #assert_( abs(t('234')-234.)<=err) - #assert_( abs(t('234.6')-234.6)<=err) - assert_(abs(t(-234) + 234.) <= err) - assert_(abs(t([234]) - 234.) <= err) - assert_(abs(t((234,)) - 234.) <= err) - assert_(abs(t(array(234)) - 234.) <= err) - assert_(abs(t(array(23 + 4j, 'F')) - (23 + 4j)) <= err) - assert_(abs(t(array([234])) - 234.) <= err) - assert_(abs(t(array([[234]])) - 234.) <= err) - assert_(abs(t(array([234], 'b')) + 22.) <= err) - assert_(abs(t(array([234], 'h')) - 234.) <= err) - assert_(abs(t(array([234], 'i')) - 234.) <= err) - assert_(abs(t(array([234], 'l')) - 234.) <= err) - assert_(abs(t(array([234], 'q')) - 234.) <= err) - assert_(abs(t(array([234], 'f')) - 234.) <= err) - assert_(abs(t(array([234], 'd')) - 234.) <= err) - assert_(abs(t(array([234 + 3j], 'F')) - (234 + 3j)) <= err) - assert_(abs(t(array([234], 'D')) - 234.) <= err) - - #assert_raises(TypeError, t, array([234], 'a1')) - assert_raises(TypeError, t, 'abc') + # assert_( abs(t('234')-234.)<=err) + # assert_( abs(t('234.6')-234.6)<=err) + assert_(abs(t(-234) + 234.0) <= err) + assert_(abs(t([234]) - 234.0) <= err) + assert_(abs(t((234, )) - 234.0) <= err) + assert_(abs(t(array(234)) - 234.0) <= err) + assert_(abs(t(array(23 + 4j, "F")) - (23 + 4j)) <= err) + assert_(abs(t(array([234])) - 234.0) <= err) + assert_(abs(t(array([[234]])) - 234.0) <= err) + assert_(abs(t(array([234], "b")) + 22.0) <= err) + assert_(abs(t(array([234], "h")) - 234.0) <= err) + assert_(abs(t(array([234], "i")) - 234.0) <= err) + assert_(abs(t(array([234], "l")) - 234.0) <= err) + assert_(abs(t(array([234], "q")) - 234.0) <= err) + assert_(abs(t(array([234], "f")) - 234.0) <= err) + assert_(abs(t(array([234], "d")) - 234.0) <= err) + assert_(abs(t(array([234 + 3j], "F")) - (234 + 3j)) <= err) + assert_(abs(t(array([234], "D")) - 234.0) <= err) + + # assert_raises(TypeError, t, array([234], 'a1')) + assert_raises(TypeError, t, "abc") assert_raises(IndexError, t, []) assert_raises(IndexError, t, ()) @@ -45,8 +44,8 @@ class TestReturnComplex(util.F2PyTest): assert_raises(TypeError, t, {}) try: - r = t(10 ** 400) - assert_(repr(r) in ['(inf+0j)', '(Infinity+0j)'], repr(r)) + r = t(10**400) + assert_(repr(r) in ["(inf+0j)", "(Infinity+0j)"], repr(r)) except OverflowError: pass @@ -100,7 +99,7 @@ cf2py intent(out) td end """ - @pytest.mark.parametrize('name', 't0,t8,t16,td,s0,s8,s16,sd'.split(',')) + @pytest.mark.parametrize("name", "t0,t8,t16,td,s0,s8,s16,sd".split(",")) def test_all(self, name): self.check_function(getattr(self.module, name), name) @@ -158,6 +157,7 @@ module f90_return_complex end module f90_return_complex """ - @pytest.mark.parametrize('name', 't0,t8,t16,td,s0,s8,s16,sd'.split(',')) + @pytest.mark.parametrize("name", "t0,t8,t16,td,s0,s8,s16,sd".split(",")) def test_all(self, name): - self.check_function(getattr(self.module.f90_return_complex, name), name) + self.check_function(getattr(self.module.f90_return_complex, name), + name) diff --git a/numpy/f2py/tests/test_return_integer.py b/numpy/f2py/tests/test_return_integer.py index 0a8121dc1..9c2bdbce2 100644 --- a/numpy/f2py/tests/test_return_integer.py +++ b/numpy/f2py/tests/test_return_integer.py @@ -6,27 +6,26 @@ from . import util class TestReturnInteger(util.F2PyTest): - def check_function(self, t, tname): assert_(t(123) == 123, repr(t(123))) assert_(t(123.6) == 123) - assert_(t('123') == 123) + assert_(t("123") == 123) assert_(t(-123) == -123) assert_(t([123]) == 123) - assert_(t((123,)) == 123) + assert_(t((123, )) == 123) assert_(t(array(123)) == 123) assert_(t(array([123])) == 123) assert_(t(array([[123]])) == 123) - assert_(t(array([123], 'b')) == 123) - assert_(t(array([123], 'h')) == 123) - assert_(t(array([123], 'i')) == 123) - assert_(t(array([123], 'l')) == 123) - assert_(t(array([123], 'B')) == 123) - assert_(t(array([123], 'f')) == 123) - assert_(t(array([123], 'd')) == 123) + assert_(t(array([123], "b")) == 123) + assert_(t(array([123], "h")) == 123) + assert_(t(array([123], "i")) == 123) + assert_(t(array([123], "l")) == 123) + assert_(t(array([123], "B")) == 123) + assert_(t(array([123], "f")) == 123) + assert_(t(array([123], "d")) == 123) - #assert_raises(ValueError, t, array([123],'S3')) - assert_raises(ValueError, t, 'abc') + # assert_raises(ValueError, t, array([123],'S3')) + assert_raises(ValueError, t, "abc") assert_raises(IndexError, t, []) assert_raises(IndexError, t, ()) @@ -34,7 +33,7 @@ class TestReturnInteger(util.F2PyTest): assert_raises(Exception, t, t) assert_raises(Exception, t, {}) - if tname in ['t8', 's8']: + if tname in ["t8", "s8"]: assert_raises(OverflowError, t, 100000000000000000000000) assert_raises(OverflowError, t, 10000000011111111111111.23) @@ -99,8 +98,8 @@ cf2py intent(out) t8 end """ - @pytest.mark.parametrize('name', - 't0,t1,t2,t4,t8,s0,s1,s2,s4,s8'.split(',')) + @pytest.mark.parametrize("name", + "t0,t1,t2,t4,t8,s0,s1,s2,s4,s8".split(",")) def test_all(self, name): self.check_function(getattr(self.module, name), name) @@ -169,7 +168,8 @@ module f90_return_integer end module f90_return_integer """ - @pytest.mark.parametrize('name', - 't0,t1,t2,t4,t8,s0,s1,s2,s4,s8'.split(',')) + @pytest.mark.parametrize("name", + "t0,t1,t2,t4,t8,s0,s1,s2,s4,s8".split(",")) def test_all(self, name): - self.check_function(getattr(self.module.f90_return_integer, name), name) + self.check_function(getattr(self.module.f90_return_integer, name), + name) diff --git a/numpy/f2py/tests/test_return_logical.py b/numpy/f2py/tests/test_return_logical.py index 9db939c7e..c1a365c7a 100644 --- a/numpy/f2py/tests/test_return_logical.py +++ b/numpy/f2py/tests/test_return_logical.py @@ -6,7 +6,6 @@ from . import util class TestReturnLogical(util.F2PyTest): - def check_function(self, t): assert_(t(True) == 1, repr(t(True))) assert_(t(False) == 0, repr(t(False))) @@ -18,28 +17,28 @@ class TestReturnLogical(util.F2PyTest): assert_(t(234) == 1) assert_(t(234.6) == 1) assert_(t(234.6 + 3j) == 1) - assert_(t('234') == 1) - assert_(t('aaa') == 1) - assert_(t('') == 0) + assert_(t("234") == 1) + assert_(t("aaa") == 1) + assert_(t("") == 0) assert_(t([]) == 0) assert_(t(()) == 0) assert_(t({}) == 0) assert_(t(t) == 1) assert_(t(-234) == 1) - assert_(t(10 ** 100) == 1) + assert_(t(10**100) == 1) assert_(t([234]) == 1) - assert_(t((234,)) == 1) + assert_(t((234, )) == 1) assert_(t(array(234)) == 1) assert_(t(array([234])) == 1) assert_(t(array([[234]])) == 1) - assert_(t(array([234], 'b')) == 1) - assert_(t(array([234], 'h')) == 1) - assert_(t(array([234], 'i')) == 1) - assert_(t(array([234], 'l')) == 1) - assert_(t(array([234], 'f')) == 1) - assert_(t(array([234], 'd')) == 1) - assert_(t(array([234 + 3j], 'F')) == 1) - assert_(t(array([234], 'D')) == 1) + assert_(t(array([234], "b")) == 1) + assert_(t(array([234], "h")) == 1) + assert_(t(array([234], "i")) == 1) + assert_(t(array([234], "l")) == 1) + assert_(t(array([234], "f")) == 1) + assert_(t(array([234], "d")) == 1) + assert_(t(array([234 + 3j], "F")) == 1) + assert_(t(array([234], "D")) == 1) assert_(t(array(0)) == 0) assert_(t(array([0])) == 0) assert_(t(array([[0]])) == 0) @@ -109,7 +108,7 @@ c end """ @pytest.mark.slow - @pytest.mark.parametrize('name', 't0,t1,t2,t4,s0,s1,s2,s4'.split(',')) + @pytest.mark.parametrize("name", "t0,t1,t2,t4,s0,s1,s2,s4".split(",")) def test_all(self, name): self.check_function(getattr(self.module, name)) @@ -179,7 +178,7 @@ end module f90_return_logical """ @pytest.mark.slow - @pytest.mark.parametrize('name', - 't0,t1,t2,t4,t8,s0,s1,s2,s4,s8'.split(',')) + @pytest.mark.parametrize("name", + "t0,t1,t2,t4,t8,s0,s1,s2,s4,s8".split(",")) def test_all(self, name): self.check_function(getattr(self.module.f90_return_logical, name)) diff --git a/numpy/f2py/tests/test_return_real.py b/numpy/f2py/tests/test_return_real.py index 8e5022a8e..d5e5ee482 100644 --- a/numpy/f2py/tests/test_return_real.py +++ b/numpy/f2py/tests/test_return_real.py @@ -7,34 +7,33 @@ from . import util class TestReturnReal(util.F2PyTest): - def check_function(self, t, tname): - if tname in ['t0', 't4', 's0', 's4']: + if tname in ["t0", "t4", "s0", "s4"]: err = 1e-5 else: err = 0.0 assert_(abs(t(234) - 234.0) <= err) assert_(abs(t(234.6) - 234.6) <= err) - assert_(abs(t('234') - 234) <= err) - assert_(abs(t('234.6') - 234.6) <= err) + assert_(abs(t("234") - 234) <= err) + assert_(abs(t("234.6") - 234.6) <= err) assert_(abs(t(-234) + 234) <= err) assert_(abs(t([234]) - 234) <= err) - assert_(abs(t((234,)) - 234.) <= err) - assert_(abs(t(array(234)) - 234.) <= err) - assert_(abs(t(array([234])) - 234.) <= err) - assert_(abs(t(array([[234]])) - 234.) <= err) - assert_(abs(t(array([234], 'b')) + 22) <= err) - assert_(abs(t(array([234], 'h')) - 234.) <= err) - assert_(abs(t(array([234], 'i')) - 234.) <= err) - assert_(abs(t(array([234], 'l')) - 234.) <= err) - assert_(abs(t(array([234], 'B')) - 234.) <= err) - assert_(abs(t(array([234], 'f')) - 234.) <= err) - assert_(abs(t(array([234], 'd')) - 234.) <= err) - if tname in ['t0', 't4', 's0', 's4']: + assert_(abs(t((234, )) - 234.0) <= err) + assert_(abs(t(array(234)) - 234.0) <= err) + assert_(abs(t(array([234])) - 234.0) <= err) + assert_(abs(t(array([[234]])) - 234.0) <= err) + assert_(abs(t(array([234], "b")) + 22) <= err) + assert_(abs(t(array([234], "h")) - 234.0) <= err) + assert_(abs(t(array([234], "i")) - 234.0) <= err) + assert_(abs(t(array([234], "l")) - 234.0) <= err) + assert_(abs(t(array([234], "B")) - 234.0) <= err) + assert_(abs(t(array([234], "f")) - 234.0) <= err) + assert_(abs(t(array([234], "d")) - 234.0) <= err) + if tname in ["t0", "t4", "s0", "s4"]: assert_(t(1e200) == t(1e300)) # inf - #assert_raises(ValueError, t, array([234], 'S1')) - assert_raises(ValueError, t, 'abc') + # assert_raises(ValueError, t, array([234], 'S1')) + assert_raises(ValueError, t, "abc") assert_raises(IndexError, t, []) assert_raises(IndexError, t, ()) @@ -43,17 +42,17 @@ class TestReturnReal(util.F2PyTest): assert_raises(Exception, t, {}) try: - r = t(10 ** 400) - assert_(repr(r) in ['inf', 'Infinity'], repr(r)) + r = t(10**400) + assert_(repr(r) in ["inf", "Infinity"], repr(r)) except OverflowError: pass - @pytest.mark.skipif( - platform.system() == 'Darwin', + platform.system() == "Darwin", reason="Prone to error when run with numpy/f2py/tests on mac os, " - "but not when run in isolation") + "but not when run in isolation", +) class TestCReturnReal(TestReturnReal): suffix = ".pyf" module_name = "c_ext_return_real" @@ -86,7 +85,7 @@ end interface end python module c_ext_return_real """ - @pytest.mark.parametrize('name', 't4,t8,s4,s8'.split(',')) + @pytest.mark.parametrize("name", "t4,t8,s4,s8".split(",")) def test_all(self, name): self.check_function(getattr(self.module, name), name) @@ -140,7 +139,7 @@ cf2py intent(out) td end """ - @pytest.mark.parametrize('name', 't0,t4,t8,td,s0,s4,s8,sd'.split(',')) + @pytest.mark.parametrize("name", "t0,t4,t8,td,s0,s4,s8,sd".split(",")) def test_all(self, name): self.check_function(getattr(self.module, name), name) @@ -198,6 +197,6 @@ module f90_return_real end module f90_return_real """ - @pytest.mark.parametrize('name', 't0,t4,t8,td,s0,s4,s8,sd'.split(',')) + @pytest.mark.parametrize("name", "t0,t4,t8,td,s0,s4,s8,sd".split(",")) def test_all(self, name): self.check_function(getattr(self.module.f90_return_real, name), name) diff --git a/numpy/f2py/tests/test_semicolon_split.py b/numpy/f2py/tests/test_semicolon_split.py index d8b4bf222..138ba85a8 100644 --- a/numpy/f2py/tests/test_semicolon_split.py +++ b/numpy/f2py/tests/test_semicolon_split.py @@ -4,10 +4,12 @@ import pytest from . import util from numpy.testing import assert_equal + @pytest.mark.skipif( - platform.system() == 'Darwin', + platform.system() == "Darwin", reason="Prone to error when run with numpy/f2py/tests on mac os, " - "but not when run in isolation") + "but not when run in isolation", +) class TestMultiline(util.F2PyTest): suffix = ".pyf" module_name = "multiline" @@ -33,9 +35,10 @@ end python module {module} @pytest.mark.skipif( - platform.system() == 'Darwin', + platform.system() == "Darwin", reason="Prone to error when run with numpy/f2py/tests on mac os, " - "but not when run in isolation") + "but not when run in isolation", +) class TestCallstatement(util.F2PyTest): suffix = ".pyf" module_name = "callstatement" diff --git a/numpy/f2py/tests/test_size.py b/numpy/f2py/tests/test_size.py index cabc340ce..3360e2a3d 100644 --- a/numpy/f2py/tests/test_size.py +++ b/numpy/f2py/tests/test_size.py @@ -6,7 +6,7 @@ from . import util class TestSizeSumExample(util.F2PyTest): - sources = [util.getpath('tests', 'src', 'size', 'foo.f90')] + sources = [util.getpath("tests", "src", "size", "foo.f90")] @pytest.mark.slow def test_all(self): diff --git a/numpy/f2py/tests/test_string.py b/numpy/f2py/tests/test_string.py index b5d18ce4b..1a6d59610 100644 --- a/numpy/f2py/tests/test_string.py +++ b/numpy/f2py/tests/test_string.py @@ -7,21 +7,21 @@ from . import util class TestString(util.F2PyTest): - sources = [util.getpath('tests', 'src', 'string', 'char.f90')] + sources = [util.getpath("tests", "src", "string", "char.f90")] @pytest.mark.slow def test_char(self): - strings = np.array(['ab', 'cd', 'ef'], dtype='c').T - inp, out = self.module.char_test.change_strings(strings, - strings.shape[1]) + strings = np.array(["ab", "cd", "ef"], dtype="c").T + inp, out = self.module.char_test.change_strings( + strings, strings.shape[1]) assert_array_equal(inp, strings) expected = strings.copy() - expected[1, :] = 'AAA' + expected[1, :] = "AAA" assert_array_equal(out, expected) class TestDocStringArguments(util.F2PyTest): - suffix = '.f' + suffix = ".f" code = """ C FILE: STRING.F @@ -39,21 +39,21 @@ C END OF FILE STRING.F """ def test_example(self): - a = np.array(b'123\0\0') - b = np.array(b'123\0\0') - c = np.array(b'123') - d = np.array(b'123') + a = np.array(b"123\0\0") + b = np.array(b"123\0\0") + c = np.array(b"123") + d = np.array(b"123") self.module.foo(a, b, c, d) - assert a.tobytes() == b'123\0\0' - assert b.tobytes() == b'B23\0\0' - assert c.tobytes() == b'123' - assert d.tobytes() == b'D23' + assert a.tobytes() == b"123\0\0" + assert b.tobytes() == b"B23\0\0" + assert c.tobytes() == b"123" + assert d.tobytes() == b"D23" class TestFixedString(util.F2PyTest): - suffix = '.f90' + suffix = ".f90" code = textwrap.dedent(""" function sint(s) result(i) @@ -109,41 +109,41 @@ class TestFixedString(util.F2PyTest): end = len(s) i = 0 for j in range(start, min(end, len(s))): - i += s[j] * 10 ** j + i += s[j] * 10**j return i - def _get_input(self, intent='in'): - if intent in ['in']: - yield '' - yield '1' - yield '1234' - yield '12345' - yield b'' - yield b'\0' - yield b'1' - yield b'\01' - yield b'1\0' - yield b'1234' - yield b'12345' - yield np.ndarray((), np.bytes_, buffer=b'') # array(b'', dtype='|S0') - yield np.array(b'') # array(b'', dtype='|S1') - yield np.array(b'\0') - yield np.array(b'1') - yield np.array(b'1\0') - yield np.array(b'\01') - yield np.array(b'1234') - yield np.array(b'123\0') - yield np.array(b'12345') + def _get_input(self, intent="in"): + if intent in ["in"]: + yield "" + yield "1" + yield "1234" + yield "12345" + yield b"" + yield b"\0" + yield b"1" + yield b"\01" + yield b"1\0" + yield b"1234" + yield b"12345" + yield np.ndarray((), np.bytes_, buffer=b"") # array(b'', dtype='|S0') + yield np.array(b"") # array(b'', dtype='|S1') + yield np.array(b"\0") + yield np.array(b"1") + yield np.array(b"1\0") + yield np.array(b"\01") + yield np.array(b"1234") + yield np.array(b"123\0") + yield np.array(b"12345") def test_intent_in(self): for s in self._get_input(): r = self.module.test_in_bytes4(s) # also checks that s is not changed inplace expected = self._sint(s, end=4) - assert r == expected, (s) + assert r == expected, s def test_intent_inout(self): - for s in self._get_input(intent='inout'): + for s in self._get_input(intent="inout"): rest = self._sint(s, start=4) r = self.module.test_inout_bytes4(s) expected = self._sint(s, end=4) diff --git a/numpy/f2py/tests/test_symbolic.py b/numpy/f2py/tests/test_symbolic.py index 52cabac53..4b8993886 100644 --- a/numpy/f2py/tests/test_symbolic.py +++ b/numpy/f2py/tests/test_symbolic.py @@ -1,35 +1,55 @@ from numpy.testing import assert_raises from numpy.f2py.symbolic import ( - Expr, Op, ArithOp, Language, - as_symbol, as_number, as_string, as_array, as_complex, - as_terms, as_factors, eliminate_quotes, insert_quotes, - fromstring, as_expr, as_apply, - as_numer_denom, as_ternary, as_ref, as_deref, - normalize, as_eq, as_ne, as_lt, as_gt, as_le, as_ge - ) + Expr, + Op, + ArithOp, + Language, + as_symbol, + as_number, + as_string, + as_array, + as_complex, + as_terms, + as_factors, + eliminate_quotes, + insert_quotes, + fromstring, + as_expr, + as_apply, + as_numer_denom, + as_ternary, + as_ref, + as_deref, + normalize, + as_eq, + as_ne, + as_lt, + as_gt, + as_le, + as_ge, +) from . import util class TestSymbolic(util.F2PyTest): - def test_eliminate_quotes(self): def worker(s): r, d = eliminate_quotes(s) s1 = insert_quotes(r, d) assert s1 == s - for kind in ['', 'mykind_']: + for kind in ["", "mykind_"]: worker(kind + '"1234" // "ABCD"') worker(kind + '"1234" // ' + kind + '"ABCD"') - worker(kind + '"1234" // \'ABCD\'') - worker(kind + '"1234" // ' + kind + '\'ABCD\'') + worker(kind + "\"1234\" // 'ABCD'") + worker(kind + '"1234" // ' + kind + "'ABCD'") worker(kind + '"1\\"2\'AB\'34"') - worker('a = ' + kind + "'1\\'2\"AB\"34'") + worker("a = " + kind + "'1\\'2\"AB\"34'") def test_sanity(self): - x = as_symbol('x') - y = as_symbol('y') - z = as_symbol('z') + x = as_symbol("x") + y = as_symbol("y") + z = as_symbol("z") assert x.op == Op.SYMBOL assert repr(x) == "Expr(Op.SYMBOL, 'x')" @@ -70,7 +90,7 @@ class TestSymbolic(util.F2PyTest): assert s != s2 a = as_array((n, m)) - b = as_array((n,)) + b = as_array((n, )) assert a.op == Op.ARRAY assert repr(a) == ("Expr(Op.ARRAY, (Expr(Op.INTEGER, (123, 4))," " Expr(Op.INTEGER, (456, 4))))") @@ -108,88 +128,90 @@ class TestSymbolic(util.F2PyTest): assert hash(e) is not None def test_tostring_fortran(self): - x = as_symbol('x') - y = as_symbol('y') - z = as_symbol('z') + x = as_symbol("x") + y = as_symbol("y") + z = as_symbol("z") n = as_number(123) m = as_number(456) a = as_array((n, m)) c = as_complex(n, m) - assert str(x) == 'x' - assert str(n) == '123' - assert str(a) == '[123, 456]' - assert str(c) == '(123, 456)' - - assert str(Expr(Op.TERMS, {x: 1})) == 'x' - assert str(Expr(Op.TERMS, {x: 2})) == '2 * x' - assert str(Expr(Op.TERMS, {x: -1})) == '-x' - assert str(Expr(Op.TERMS, {x: -2})) == '-2 * x' - assert str(Expr(Op.TERMS, {x: 1, y: 1})) == 'x + y' - assert str(Expr(Op.TERMS, {x: -1, y: -1})) == '-x - y' - assert str(Expr(Op.TERMS, {x: 2, y: 3})) == '2 * x + 3 * y' - assert str(Expr(Op.TERMS, {x: -2, y: 3})) == '-2 * x + 3 * y' - assert str(Expr(Op.TERMS, {x: 2, y: -3})) == '2 * x - 3 * y' - - assert str(Expr(Op.FACTORS, {x: 1})) == 'x' - assert str(Expr(Op.FACTORS, {x: 2})) == 'x ** 2' - assert str(Expr(Op.FACTORS, {x: -1})) == 'x ** -1' - assert str(Expr(Op.FACTORS, {x: -2})) == 'x ** -2' - assert str(Expr(Op.FACTORS, {x: 1, y: 1})) == 'x * y' - assert str(Expr(Op.FACTORS, {x: 2, y: 3})) == 'x ** 2 * y ** 3' + assert str(x) == "x" + assert str(n) == "123" + assert str(a) == "[123, 456]" + assert str(c) == "(123, 456)" + + assert str(Expr(Op.TERMS, {x: 1})) == "x" + assert str(Expr(Op.TERMS, {x: 2})) == "2 * x" + assert str(Expr(Op.TERMS, {x: -1})) == "-x" + assert str(Expr(Op.TERMS, {x: -2})) == "-2 * x" + assert str(Expr(Op.TERMS, {x: 1, y: 1})) == "x + y" + assert str(Expr(Op.TERMS, {x: -1, y: -1})) == "-x - y" + assert str(Expr(Op.TERMS, {x: 2, y: 3})) == "2 * x + 3 * y" + assert str(Expr(Op.TERMS, {x: -2, y: 3})) == "-2 * x + 3 * y" + assert str(Expr(Op.TERMS, {x: 2, y: -3})) == "2 * x - 3 * y" + + assert str(Expr(Op.FACTORS, {x: 1})) == "x" + assert str(Expr(Op.FACTORS, {x: 2})) == "x ** 2" + assert str(Expr(Op.FACTORS, {x: -1})) == "x ** -1" + assert str(Expr(Op.FACTORS, {x: -2})) == "x ** -2" + assert str(Expr(Op.FACTORS, {x: 1, y: 1})) == "x * y" + assert str(Expr(Op.FACTORS, {x: 2, y: 3})) == "x ** 2 * y ** 3" v = Expr(Op.FACTORS, {x: 2, Expr(Op.TERMS, {x: 1, y: 1}): 3}) - assert str(v) == 'x ** 2 * (x + y) ** 3', str(v) + assert str(v) == "x ** 2 * (x + y) ** 3", str(v) v = Expr(Op.FACTORS, {x: 2, Expr(Op.FACTORS, {x: 1, y: 1}): 3}) - assert str(v) == 'x ** 2 * (x * y) ** 3', str(v) + assert str(v) == "x ** 2 * (x * y) ** 3", str(v) - assert str(Expr(Op.APPLY, ('f', (), {}))) == 'f()' - assert str(Expr(Op.APPLY, ('f', (x,), {}))) == 'f(x)' - assert str(Expr(Op.APPLY, ('f', (x, y), {}))) == 'f(x, y)' - assert str(Expr(Op.INDEXING, ('f', x))) == 'f[x]' + assert str(Expr(Op.APPLY, ("f", (), {}))) == "f()" + assert str(Expr(Op.APPLY, ("f", (x, ), {}))) == "f(x)" + assert str(Expr(Op.APPLY, ("f", (x, y), {}))) == "f(x, y)" + assert str(Expr(Op.INDEXING, ("f", x))) == "f[x]" - assert str(as_ternary(x, y, z)) == 'merge(y, z, x)' - assert str(as_eq(x, y)) == 'x .eq. y' - assert str(as_ne(x, y)) == 'x .ne. y' - assert str(as_lt(x, y)) == 'x .lt. y' - assert str(as_le(x, y)) == 'x .le. y' - assert str(as_gt(x, y)) == 'x .gt. y' - assert str(as_ge(x, y)) == 'x .ge. y' + assert str(as_ternary(x, y, z)) == "merge(y, z, x)" + assert str(as_eq(x, y)) == "x .eq. y" + assert str(as_ne(x, y)) == "x .ne. y" + assert str(as_lt(x, y)) == "x .lt. y" + assert str(as_le(x, y)) == "x .le. y" + assert str(as_gt(x, y)) == "x .gt. y" + assert str(as_ge(x, y)) == "x .ge. y" def test_tostring_c(self): language = Language.C - x = as_symbol('x') - y = as_symbol('y') - z = as_symbol('z') + x = as_symbol("x") + y = as_symbol("y") + z = as_symbol("z") n = as_number(123) - assert Expr(Op.FACTORS, {x: 2}).tostring(language=language) == 'x * x' - assert Expr(Op.FACTORS, {x + y: 2}).tostring( - language=language) == '(x + y) * (x + y)' - assert Expr(Op.FACTORS, {x: 12}).tostring( - language=language) == 'pow(x, 12)' - - assert as_apply(ArithOp.DIV, x, y).tostring( - language=language) == 'x / y' - assert as_apply(ArithOp.DIV, x, x + y).tostring( - language=language) == 'x / (x + y)' - assert as_apply(ArithOp.DIV, x - y, x + y).tostring( - language=language) == '(x - y) / (x + y)' - assert (x + (x - y) / (x + y) + n).tostring( - language=language) == '123 + x + (x - y) / (x + y)' - - assert as_ternary(x, y, z).tostring(language=language) == '(x ? y : z)' - assert as_eq(x, y).tostring(language=language) == 'x == y' - assert as_ne(x, y).tostring(language=language) == 'x != y' - assert as_lt(x, y).tostring(language=language) == 'x < y' - assert as_le(x, y).tostring(language=language) == 'x <= y' - assert as_gt(x, y).tostring(language=language) == 'x > y' - assert as_ge(x, y).tostring(language=language) == 'x >= y' + assert Expr(Op.FACTORS, {x: 2}).tostring(language=language) == "x * x" + assert (Expr(Op.FACTORS, { + x + y: 2 + }).tostring(language=language) == "(x + y) * (x + y)") + assert Expr(Op.FACTORS, { + x: 12 + }).tostring(language=language) == "pow(x, 12)" + + assert as_apply(ArithOp.DIV, x, + y).tostring(language=language) == "x / y" + assert (as_apply(ArithOp.DIV, x, + x + y).tostring(language=language) == "x / (x + y)") + assert (as_apply(ArithOp.DIV, x - y, x + + y).tostring(language=language) == "(x - y) / (x + y)") + assert (x + (x - y) / (x + y) + + n).tostring(language=language) == "123 + x + (x - y) / (x + y)" + + assert as_ternary(x, y, z).tostring(language=language) == "(x ? y : z)" + assert as_eq(x, y).tostring(language=language) == "x == y" + assert as_ne(x, y).tostring(language=language) == "x != y" + assert as_lt(x, y).tostring(language=language) == "x < y" + assert as_le(x, y).tostring(language=language) == "x <= y" + assert as_gt(x, y).tostring(language=language) == "x > y" + assert as_ge(x, y).tostring(language=language) == "x >= y" def test_operations(self): - x = as_symbol('x') - y = as_symbol('y') - z = as_symbol('z') + x = as_symbol("x") + y = as_symbol("y") + z = as_symbol("z") assert x + x == Expr(Op.TERMS, {x: 2}) assert x - x == Expr(Op.INTEGER, (0, 4)) @@ -205,28 +227,35 @@ class TestSymbolic(util.F2PyTest): assert 2 * x + 3 * y == Expr(Op.TERMS, {x: 2, y: 3}) assert (x + y) * 2 == Expr(Op.TERMS, {x: 2, y: 2}) - assert x ** 2 == Expr(Op.FACTORS, {x: 2}) - assert (x + y) ** 2 == Expr(Op.TERMS, - {Expr(Op.FACTORS, {x: 2}): 1, - Expr(Op.FACTORS, {y: 2}): 1, - Expr(Op.FACTORS, {x: 1, y: 1}): 2}) - assert (x + y) * x == x ** 2 + x * y - assert (x + y) ** 2 == x ** 2 + 2 * x * y + y ** 2 - assert (x + y) ** 2 + (x - y) ** 2 == 2 * x ** 2 + 2 * y ** 2 + assert x**2 == Expr(Op.FACTORS, {x: 2}) + assert (x + y)**2 == Expr( + Op.TERMS, + { + Expr(Op.FACTORS, {x: 2}): 1, + Expr(Op.FACTORS, {y: 2}): 1, + Expr(Op.FACTORS, { + x: 1, + y: 1 + }): 2, + }, + ) + assert (x + y) * x == x**2 + x * y + assert (x + y)**2 == x**2 + 2 * x * y + y**2 + assert (x + y)**2 + (x - y)**2 == 2 * x**2 + 2 * y**2 assert (x + y) * z == x * z + y * z assert z * (x + y) == x * z + y * z assert (x / 2) == as_apply(ArithOp.DIV, x, as_number(2)) assert (2 * x / 2) == x - assert (3 * x / 2) == as_apply(ArithOp.DIV, 3*x, as_number(2)) + assert (3 * x / 2) == as_apply(ArithOp.DIV, 3 * x, as_number(2)) assert (4 * x / 2) == 2 * x - assert (5 * x / 2) == as_apply(ArithOp.DIV, 5*x, as_number(2)) + assert (5 * x / 2) == as_apply(ArithOp.DIV, 5 * x, as_number(2)) assert (6 * x / 2) == 3 * x - assert ((3*5) * x / 6) == as_apply(ArithOp.DIV, 5*x, as_number(2)) - assert (30*x**2*y**4 / (24*x**3*y**3)) == as_apply(ArithOp.DIV, - 5*y, 4*x) - assert ((15 * x / 6) / 5) == as_apply( - ArithOp.DIV, x, as_number(2)), ((15 * x / 6) / 5) + assert ((3 * 5) * x / 6) == as_apply(ArithOp.DIV, 5 * x, as_number(2)) + assert (30 * x**2 * y**4 / (24 * x**3 * y**3)) == as_apply( + ArithOp.DIV, 5 * y, 4 * x) + assert ((15 * x / 6) / 5) == as_apply(ArithOp.DIV, x, + as_number(2)), (15 * x / 6) / 5 assert (x / (5 / x)) == as_apply(ArithOp.DIV, x**2, as_number(5)) assert (x / 2.0) == Expr(Op.TERMS, {x: 0.5}) @@ -238,127 +267,128 @@ class TestSymbolic(util.F2PyTest): assert s // x == Expr(Op.CONCAT, (s, x)) assert x // s == Expr(Op.CONCAT, (x, s)) - c = as_complex(1., 2.) - assert -c == as_complex(-1., -2.) - assert c + c == as_expr((1+2j)*2) - assert c * c == as_expr((1+2j)**2) + c = as_complex(1.0, 2.0) + assert -c == as_complex(-1.0, -2.0) + assert c + c == as_expr((1 + 2j) * 2) + assert c * c == as_expr((1 + 2j)**2) def test_substitute(self): - x = as_symbol('x') - y = as_symbol('y') - z = as_symbol('z') + x = as_symbol("x") + y = as_symbol("y") + z = as_symbol("z") a = as_array((x, y)) assert x.substitute({x: y}) == y assert (x + y).substitute({x: z}) == y + z assert (x * y).substitute({x: z}) == y * z - assert (x ** 4).substitute({x: z}) == z ** 4 + assert (x**4).substitute({x: z}) == z**4 assert (x / y).substitute({x: z}) == z / y assert x.substitute({x: y + z}) == y + z assert a.substitute({x: y + z}) == as_array((y + z, y)) - assert as_ternary(x, y, z).substitute( - {x: y + z}) == as_ternary(y + z, y, z) - assert as_eq(x, y).substitute( - {x: y + z}) == as_eq(y + z, y) + assert as_ternary(x, y, + z).substitute({x: y + z}) == as_ternary(y + z, y, z) + assert as_eq(x, y).substitute({x: y + z}) == as_eq(y + z, y) def test_fromstring(self): - x = as_symbol('x') - y = as_symbol('y') - z = as_symbol('z') - f = as_symbol('f') + x = as_symbol("x") + y = as_symbol("y") + z = as_symbol("z") + f = as_symbol("f") s = as_string('"ABC"') t = as_string('"123"') a = as_array((x, y)) - assert fromstring('x') == x - assert fromstring('+ x') == x - assert fromstring('- x') == -x - assert fromstring('x + y') == x + y - assert fromstring('x + 1') == x + 1 - assert fromstring('x * y') == x * y - assert fromstring('x * 2') == x * 2 - assert fromstring('x / y') == x / y - assert fromstring('x ** 2', - language=Language.Python) == x ** 2 - assert fromstring('x ** 2 ** 3', - language=Language.Python) == x ** 2 ** 3 - assert fromstring('(x + y) * z') == (x + y) * z - - assert fromstring('f(x)') == f(x) - assert fromstring('f(x,y)') == f(x, y) - assert fromstring('f[x]') == f[x] - assert fromstring('f[x][y]') == f[x][y] + assert fromstring("x") == x + assert fromstring("+ x") == x + assert fromstring("- x") == -x + assert fromstring("x + y") == x + y + assert fromstring("x + 1") == x + 1 + assert fromstring("x * y") == x * y + assert fromstring("x * 2") == x * 2 + assert fromstring("x / y") == x / y + assert fromstring("x ** 2", language=Language.Python) == x**2 + assert fromstring("x ** 2 ** 3", language=Language.Python) == x**2**3 + assert fromstring("(x + y) * z") == (x + y) * z + + assert fromstring("f(x)") == f(x) + assert fromstring("f(x,y)") == f(x, y) + assert fromstring("f[x]") == f[x] + assert fromstring("f[x][y]") == f[x][y] assert fromstring('"ABC"') == s - assert normalize(fromstring('"ABC" // "123" ', - language=Language.Fortran)) == s // t + assert (normalize( + fromstring('"ABC" // "123" ', + language=Language.Fortran)) == s // t) assert fromstring('f("ABC")') == f(s) - assert fromstring('MYSTRKIND_"ABC"') == as_string('"ABC"', 'MYSTRKIND') - - assert fromstring('(/x, y/)') == a, fromstring('(/x, y/)') - assert fromstring('f((/x, y/))') == f(a) - assert fromstring('(/(x+y)*z/)') == as_array(((x+y)*z,)) - - assert fromstring('123') == as_number(123) - assert fromstring('123_2') == as_number(123, 2) - assert fromstring('123_myintkind') == as_number(123, 'myintkind') - - assert fromstring('123.0') == as_number(123.0, 4) - assert fromstring('123.0_4') == as_number(123.0, 4) - assert fromstring('123.0_8') == as_number(123.0, 8) - assert fromstring('123.0e0') == as_number(123.0, 4) - assert fromstring('123.0d0') == as_number(123.0, 8) - assert fromstring('123d0') == as_number(123.0, 8) - assert fromstring('123e-0') == as_number(123.0, 4) - assert fromstring('123d+0') == as_number(123.0, 8) - assert fromstring('123.0_myrealkind') == as_number(123.0, 'myrealkind') - assert fromstring('3E4') == as_number(30000.0, 4) - - assert fromstring('(1, 2)') == as_complex(1, 2) - assert fromstring('(1e2, PI)') == as_complex( - as_number(100.0), as_symbol('PI')) - - assert fromstring('[1, 2]') == as_array((as_number(1), as_number(2))) - - assert fromstring('POINT(x, y=1)') == as_apply( - as_symbol('POINT'), x, y=as_number(1)) - assert (fromstring('PERSON(name="John", age=50, shape=(/34, 23/))') - == as_apply(as_symbol('PERSON'), - name=as_string('"John"'), - age=as_number(50), - shape=as_array((as_number(34), as_number(23))))) - - assert fromstring('x?y:z') == as_ternary(x, y, z) - - assert fromstring('*x') == as_deref(x) - assert fromstring('**x') == as_deref(as_deref(x)) - assert fromstring('&x') == as_ref(x) - assert fromstring('(*x) * (*y)') == as_deref(x) * as_deref(y) - assert fromstring('(*x) * *y') == as_deref(x) * as_deref(y) - assert fromstring('*x * *y') == as_deref(x) * as_deref(y) - assert fromstring('*x**y') == as_deref(x) * as_deref(y) - - assert fromstring('x == y') == as_eq(x, y) - assert fromstring('x != y') == as_ne(x, y) - assert fromstring('x < y') == as_lt(x, y) - assert fromstring('x > y') == as_gt(x, y) - assert fromstring('x <= y') == as_le(x, y) - assert fromstring('x >= y') == as_ge(x, y) - - assert fromstring('x .eq. y', language=Language.Fortran) == as_eq(x, y) - assert fromstring('x .ne. y', language=Language.Fortran) == as_ne(x, y) - assert fromstring('x .lt. y', language=Language.Fortran) == as_lt(x, y) - assert fromstring('x .gt. y', language=Language.Fortran) == as_gt(x, y) - assert fromstring('x .le. y', language=Language.Fortran) == as_le(x, y) - assert fromstring('x .ge. y', language=Language.Fortran) == as_ge(x, y) + assert fromstring('MYSTRKIND_"ABC"') == as_string('"ABC"', "MYSTRKIND") + + assert fromstring("(/x, y/)") == a, fromstring("(/x, y/)") + assert fromstring("f((/x, y/))") == f(a) + assert fromstring("(/(x+y)*z/)") == as_array(((x + y) * z, )) + + assert fromstring("123") == as_number(123) + assert fromstring("123_2") == as_number(123, 2) + assert fromstring("123_myintkind") == as_number(123, "myintkind") + + assert fromstring("123.0") == as_number(123.0, 4) + assert fromstring("123.0_4") == as_number(123.0, 4) + assert fromstring("123.0_8") == as_number(123.0, 8) + assert fromstring("123.0e0") == as_number(123.0, 4) + assert fromstring("123.0d0") == as_number(123.0, 8) + assert fromstring("123d0") == as_number(123.0, 8) + assert fromstring("123e-0") == as_number(123.0, 4) + assert fromstring("123d+0") == as_number(123.0, 8) + assert fromstring("123.0_myrealkind") == as_number(123.0, "myrealkind") + assert fromstring("3E4") == as_number(30000.0, 4) + + assert fromstring("(1, 2)") == as_complex(1, 2) + assert fromstring("(1e2, PI)") == as_complex(as_number(100.0), + as_symbol("PI")) + + assert fromstring("[1, 2]") == as_array((as_number(1), as_number(2))) + + assert fromstring("POINT(x, y=1)") == as_apply(as_symbol("POINT"), + x, + y=as_number(1)) + assert fromstring( + 'PERSON(name="John", age=50, shape=(/34, 23/))') == as_apply( + as_symbol("PERSON"), + name=as_string('"John"'), + age=as_number(50), + shape=as_array((as_number(34), as_number(23))), + ) + + assert fromstring("x?y:z") == as_ternary(x, y, z) + + assert fromstring("*x") == as_deref(x) + assert fromstring("**x") == as_deref(as_deref(x)) + assert fromstring("&x") == as_ref(x) + assert fromstring("(*x) * (*y)") == as_deref(x) * as_deref(y) + assert fromstring("(*x) * *y") == as_deref(x) * as_deref(y) + assert fromstring("*x * *y") == as_deref(x) * as_deref(y) + assert fromstring("*x**y") == as_deref(x) * as_deref(y) + + assert fromstring("x == y") == as_eq(x, y) + assert fromstring("x != y") == as_ne(x, y) + assert fromstring("x < y") == as_lt(x, y) + assert fromstring("x > y") == as_gt(x, y) + assert fromstring("x <= y") == as_le(x, y) + assert fromstring("x >= y") == as_ge(x, y) + + assert fromstring("x .eq. y", language=Language.Fortran) == as_eq(x, y) + assert fromstring("x .ne. y", language=Language.Fortran) == as_ne(x, y) + assert fromstring("x .lt. y", language=Language.Fortran) == as_lt(x, y) + assert fromstring("x .gt. y", language=Language.Fortran) == as_gt(x, y) + assert fromstring("x .le. y", language=Language.Fortran) == as_le(x, y) + assert fromstring("x .ge. y", language=Language.Fortran) == as_ge(x, y) def test_traverse(self): - x = as_symbol('x') - y = as_symbol('y') - z = as_symbol('z') - f = as_symbol('f') + x = as_symbol("x") + y = as_symbol("y") + z = as_symbol("z") + f = as_symbol("f") # Use traverse to substitute a symbol def replace_visit(s, r=z): @@ -373,8 +403,9 @@ class TestSymbolic(util.F2PyTest): assert (f[y]).traverse(replace_visit) == f[y] assert (f[z]).traverse(replace_visit) == f[z] assert (x + y + z).traverse(replace_visit) == (2 * z + y) - assert (x + f(y, x - z)).traverse( - replace_visit) == (z + f(y, as_number(0))) + assert (x + + f(y, x - z)).traverse(replace_visit) == (z + + f(y, as_number(0))) assert as_eq(x, y).traverse(replace_visit) == as_eq(z, y) # Use traverse to collect symbols, method 1 @@ -416,28 +447,28 @@ class TestSymbolic(util.F2PyTest): assert symbols == {x} def test_linear_solve(self): - x = as_symbol('x') - y = as_symbol('y') - z = as_symbol('z') + x = as_symbol("x") + y = as_symbol("y") + z = as_symbol("z") assert x.linear_solve(x) == (as_number(1), as_number(0)) - assert (x+1).linear_solve(x) == (as_number(1), as_number(1)) - assert (2*x).linear_solve(x) == (as_number(2), as_number(0)) - assert (2*x+3).linear_solve(x) == (as_number(2), as_number(3)) + assert (x + 1).linear_solve(x) == (as_number(1), as_number(1)) + assert (2 * x).linear_solve(x) == (as_number(2), as_number(0)) + assert (2 * x + 3).linear_solve(x) == (as_number(2), as_number(3)) assert as_number(3).linear_solve(x) == (as_number(0), as_number(3)) assert y.linear_solve(x) == (as_number(0), y) - assert (y*z).linear_solve(x) == (as_number(0), y * z) + assert (y * z).linear_solve(x) == (as_number(0), y * z) - assert (x+y).linear_solve(x) == (as_number(1), y) - assert (z*x+y).linear_solve(x) == (z, y) - assert ((z+y)*x+y).linear_solve(x) == (z + y, y) - assert (z*y*x+y).linear_solve(x) == (z * y, y) + assert (x + y).linear_solve(x) == (as_number(1), y) + assert (z * x + y).linear_solve(x) == (z, y) + assert ((z + y) * x + y).linear_solve(x) == (z + y, y) + assert (z * y * x + y).linear_solve(x) == (z * y, y) - assert_raises(RuntimeError, lambda: (x*x).linear_solve(x)) + assert_raises(RuntimeError, lambda: (x * x).linear_solve(x)) def test_as_numer_denom(self): - x = as_symbol('x') - y = as_symbol('y') + x = as_symbol("x") + y = as_symbol("y") n = as_number(123) assert as_numer_denom(x) == (x, as_number(1)) @@ -446,11 +477,11 @@ class TestSymbolic(util.F2PyTest): assert as_numer_denom(x / y) == (x, y) assert as_numer_denom(x * y) == (x * y, as_number(1)) assert as_numer_denom(n + x / y) == (x + n * y, y) - assert as_numer_denom(n + x / (y - x / n)) == (y * n ** 2, y * n - x) + assert as_numer_denom(n + x / (y - x / n)) == (y * n**2, y * n - x) def test_polynomial_atoms(self): - x = as_symbol('x') - y = as_symbol('y') + x = as_symbol("x") + y = as_symbol("y") n = as_number(123) assert x.polynomial_atoms() == {x} @@ -459,4 +490,4 @@ class TestSymbolic(util.F2PyTest): assert (y(x)).polynomial_atoms() == {y(x)} assert (y(x) + x).polynomial_atoms() == {y(x), x} assert (y(x) * x[y]).polynomial_atoms() == {y(x), x[y]} - assert (y(x) ** x).polynomial_atoms() == {y(x)} + assert (y(x)**x).polynomial_atoms() == {y(x)} diff --git a/numpy/f2py/tests/util.py b/numpy/f2py/tests/util.py index cfa75c16a..069a27905 100644 --- a/numpy/f2py/tests/util.py +++ b/numpy/f2py/tests/util.py @@ -81,9 +81,11 @@ def _memoize(func): if isinstance(ret, Exception): raise ret return ret + wrapper.__name__ = func.__name__ return wrapper + # # Building modules # @@ -96,8 +98,8 @@ def build_module(source_files, options=[], skip=[], only=[], module_name=None): """ - code = ("import sys; sys.path = %s; import numpy.f2py; " - "numpy.f2py.main()" % repr(sys.path)) + code = "import sys; sys.path = %s; import numpy.f2py; " "numpy.f2py.main()" % repr( + sys.path) d = get_module_dir() @@ -112,29 +114,30 @@ def build_module(source_files, options=[], skip=[], only=[], module_name=None): dst_sources.append(dst) base, ext = os.path.splitext(dst) - if ext in ('.f90', '.f', '.c', '.pyf'): + if ext in (".f90", ".f", ".c", ".pyf"): f2py_sources.append(dst) # Prepare options if module_name is None: module_name = get_temp_module_name() - f2py_opts = ['-c', '-m', module_name] + options + f2py_sources + f2py_opts = ["-c", "-m", module_name] + options + f2py_sources if skip: - f2py_opts += ['skip:'] + skip + f2py_opts += ["skip:"] + skip if only: - f2py_opts += ['only:'] + only + f2py_opts += ["only:"] + only # Build cwd = os.getcwd() try: os.chdir(d) - cmd = [sys.executable, '-c', code] + f2py_opts - p = subprocess.Popen(cmd, stdout=subprocess.PIPE, + cmd = [sys.executable, "-c", code] + f2py_opts + p = subprocess.Popen(cmd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = p.communicate() if p.returncode != 0: - raise RuntimeError("Running f2py failed: %s\n%s" - % (cmd[4:], asstr(out))) + raise RuntimeError("Running f2py failed: %s\n%s" % + (cmd[4:], asstr(out))) finally: os.chdir(cwd) @@ -147,20 +150,28 @@ def build_module(source_files, options=[], skip=[], only=[], module_name=None): @_memoize -def build_code(source_code, options=[], skip=[], only=[], suffix=None, +def build_code(source_code, + options=[], + skip=[], + only=[], + suffix=None, module_name=None): """ Compile and import Fortran code using f2py. """ if suffix is None: - suffix = '.f' + suffix = ".f" with temppath(suffix=suffix) as path: - with open(path, 'w') as f: + with open(path, "w") as f: f.write(source_code) - return build_module([path], options=options, skip=skip, only=only, + return build_module([path], + options=options, + skip=skip, + only=only, module_name=module_name) + # # Check if compilers are available at all... # @@ -202,23 +213,27 @@ def _get_compiler_status(): tmpdir = tempfile.mkdtemp() try: - script = os.path.join(tmpdir, 'setup.py') + script = os.path.join(tmpdir, "setup.py") - with open(script, 'w') as f: + with open(script, "w") as f: f.write(code) - cmd = [sys.executable, 'setup.py', 'config'] - p = subprocess.Popen(cmd, stdout=subprocess.PIPE, + cmd = [sys.executable, "setup.py", "config"] + p = subprocess.Popen(cmd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=tmpdir) out, err = p.communicate() finally: shutil.rmtree(tmpdir) - m = re.search(br'COMPILERS:(\d+),(\d+),(\d+)', out) + m = re.search(br"COMPILERS:(\d+),(\d+),(\d+)", out) if m: - _compiler_status = (bool(int(m.group(1))), bool(int(m.group(2))), - bool(int(m.group(3)))) + _compiler_status = ( + bool(int(m.group(1))), + bool(int(m.group(2))), + bool(int(m.group(3))), + ) # Finished return _compiler_status @@ -234,6 +249,7 @@ def has_f77_compiler(): def has_f90_compiler(): return _get_compiler_status()[2] + # # Building with distutils # @@ -259,7 +275,7 @@ def build_module_distutils(source_files, config_code, module_name, **kw): # Build script config_code = textwrap.dedent(config_code).replace("\n", "\n ") - code = textwrap.dedent("""\ + code = (textwrap.dedent("""\ import os import sys sys.path = %(syspath)s @@ -273,24 +289,25 @@ def build_module_distutils(source_files, config_code, module_name, **kw): if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration) - """) % dict(config_code=config_code, syspath=repr(sys.path)) + """) % dict(config_code=config_code, syspath=repr(sys.path))) - script = os.path.join(d, get_temp_module_name() + '.py') + script = os.path.join(d, get_temp_module_name() + ".py") dst_sources.append(script) - with open(script, 'wb') as f: + with open(script, "wb") as f: f.write(asbytes(code)) # Build cwd = os.getcwd() try: os.chdir(d) - cmd = [sys.executable, script, 'build_ext', '-i'] - p = subprocess.Popen(cmd, stdout=subprocess.PIPE, + cmd = [sys.executable, script, "build_ext", "-i"] + p = subprocess.Popen(cmd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = p.communicate() if p.returncode != 0: - raise RuntimeError("Running distutils build failed: %s\n%s" - % (cmd[4:], asstr(out))) + raise RuntimeError("Running distutils build failed: %s\n%s" % + (cmd[4:], asstr(out))) finally: os.chdir(cwd) @@ -302,6 +319,7 @@ def build_module_distutils(source_files, config_code, module_name, **kw): __import__(module_name) return sys.modules[module_name] + # # Unittest convenience # @@ -313,13 +331,13 @@ class F2PyTest: options = [] skip = [] only = [] - suffix = '.f' + suffix = ".f" module = None module_name = None def setup(self): - if sys.platform == 'win32': - pytest.skip('Fails with MinGW64 Gfortran (Issue #9673)') + if sys.platform == "win32": + pytest.skip("Fails with MinGW64 Gfortran (Issue #9673)") if self.module is not None: return @@ -337,9 +355,9 @@ class F2PyTest: needs_f77 = False needs_f90 = False for fn in codes: - if str( fn ).endswith('.f'): + if str(fn).endswith(".f"): needs_f77 = True - elif str( fn ).endswith('.f90'): + elif str(fn).endswith(".f90"): needs_f90 = True if needs_f77 and not has_f77_compiler(): pytest.skip("No Fortran 77 compiler available") @@ -348,25 +366,36 @@ class F2PyTest: # Build the module if self.code is not None: - self.module = build_code(self.code, options=self.options, - skip=self.skip, only=self.only, - suffix=self.suffix, - module_name=self.module_name) + self.module = build_code( + self.code, + options=self.options, + skip=self.skip, + only=self.only, + suffix=self.suffix, + module_name=self.module_name, + ) if self.sources is not None: - self.module = build_module(self.sources, options=self.options, - skip=self.skip, only=self.only, - module_name=self.module_name) + self.module = build_module( + self.sources, + options=self.options, + skip=self.skip, + only=self.only, + module_name=self.module_name, + ) + # # Helper functions # + def getpath(*a): # Package root d = Path(__file__).parent.parent.resolve() return d.joinpath(*a) + @contextlib.contextmanager def switchdir(path): curpath = Path.cwd() |