diff options
author | Seth Troisi <sethtroisi@google.com> | 2020-01-08 23:49:17 -0800 |
---|---|---|
committer | Seth Troisi <sethtroisi@google.com> | 2020-01-15 13:19:56 -0800 |
commit | 1427484e9015e73b7017ee9336ce914a6f15187b (patch) | |
tree | 2db89078addee6a01697ab8bd4160c25d59fffc4 /numpy | |
parent | b6bc0941d4f07310456079ab2497c3d1bde4a5e7 (diff) | |
download | numpy-1427484e9015e73b7017ee9336ce914a6f15187b.tar.gz |
MAINT: Remove sys.version checks in tests
Diffstat (limited to 'numpy')
31 files changed, 246 insertions, 553 deletions
diff --git a/numpy/core/tests/test_arrayprint.py b/numpy/core/tests/test_arrayprint.py index 2d0abc517..96240be0f 100644 --- a/numpy/core/tests/test_arrayprint.py +++ b/numpy/core/tests/test_arrayprint.py @@ -233,12 +233,8 @@ class TestArray2String: return 'O' x = np.arange(3) - if sys.version_info[0] >= 3: - x_hex = "[0x0 0x1 0x2]" - x_oct = "[0o0 0o1 0o2]" - else: - x_hex = "[0x0L 0x1L 0x2L]" - x_oct = "[0L 01L 02L]" + x_hex = "[0x0 0x1 0x2]" + x_oct = "[0o0 0o1 0o2]" assert_(np.array2string(x, formatter={'all':_format_function}) == "[. o O]") assert_(np.array2string(x, formatter={'int_kind':_format_function}) == @@ -469,12 +465,8 @@ class TestPrintOptions: assert_equal(unicode(np.array(u'café', '<U4')), u'café') - if sys.version_info[0] >= 3: - assert_equal(repr(np.array('café', '<U4')), - "array('café', dtype='<U4')") - else: - assert_equal(repr(np.array(u'café', '<U4')), - "array(u'caf\\xe9', dtype='<U4')") + assert_equal(repr(np.array('café', '<U4')), + "array('café', dtype='<U4')") assert_equal(str(np.array('test', np.str_)), 'test') a = np.zeros(1, dtype=[('a', '<i4', (3,))]) @@ -707,7 +699,7 @@ class TestPrintOptions: array([10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22.], dtype=float32)""")) - styp = '<U4' if sys.version_info[0] >= 3 else '|S4' + styp = '<U4' assert_equal(repr(np.ones(3, dtype=styp)), "array(['1', '1', '1'], dtype='{}')".format(styp)) assert_equal(repr(np.ones(12, dtype=styp)), textwrap.dedent("""\ @@ -846,10 +838,7 @@ class TestPrintOptions: def test_unicode_object_array(): import sys - if sys.version_info[0] >= 3: - expected = "array(['é'], dtype=object)" - else: - expected = "array([u'\\xe9'], dtype=object)" + expected = "array(['é'], dtype=object)" x = np.array([u'\xe9'], dtype=object) assert_equal(repr(x), expected) diff --git a/numpy/core/tests/test_defchararray.py b/numpy/core/tests/test_defchararray.py index d2a1e86d2..4c9016c3e 100644 --- a/numpy/core/tests/test_defchararray.py +++ b/numpy/core/tests/test_defchararray.py @@ -341,15 +341,8 @@ class TestMethods: assert_array_equal(C, tgt) def test_decode(self): - if sys.version_info[0] >= 3: - A = np.char.array([b'\\u03a3']) - assert_(A.decode('unicode-escape')[0] == '\u03a3') - else: - with suppress_warnings() as sup: - if sys.py3kwarning: - sup.filter(DeprecationWarning, "'hex_codec'") - A = np.char.array(['736563726574206d657373616765']) - assert_(A.decode('hex_codec')[0] == 'secret message') + A = np.char.array([b'\\u03a3']) + assert_(A.decode('unicode-escape')[0] == '\u03a3') def test_encode(self): B = self.B.encode('unicode_escape') @@ -360,18 +353,12 @@ class TestMethods: assert_(T[2, 0] == b'123 345 \0') def test_join(self): - if sys.version_info[0] >= 3: - # NOTE: list(b'123') == [49, 50, 51] - # so that b','.join(b'123') results to an error on Py3 - A0 = self.A.decode('ascii') - else: - A0 = self.A + # NOTE: list(b'123') == [49, 50, 51] + # so that b','.join(b'123') results to an error on Py3 + A0 = self.A.decode('ascii') A = np.char.join([',', '#'], A0) - if sys.version_info[0] >= 3: - assert_(issubclass(A.dtype.type, np.unicode_)) - else: - assert_(issubclass(A.dtype.type, np.string_)) + assert_(issubclass(A.dtype.type, np.unicode_)) tgt = np.array([[' ,a,b,c, ', ''], ['1,2,3,4,5', 'M#i#x#e#d#C#a#s#e'], ['1,2,3, ,\t, ,3,4,5, ,\x00, ', 'U#P#P#E#R']]) @@ -442,15 +429,6 @@ class TestMethods: assert_(issubclass(R.dtype.type, np.string_)) assert_array_equal(R, tgt) - if sys.version_info[0] < 3: - # NOTE: b'abc'.replace(b'a', 'b') is not allowed on Py3 - R = self.A.replace(b'a', u'\u03a3') - tgt = [[u' \u03a3bc ', ''], - ['12345', u'MixedC\u03a3se'], - ['123 \t 345 \x00', 'UPPER']] - assert_(issubclass(R.dtype.type, np.unicode_)) - assert_array_equal(R, tgt) - def test_rjust(self): assert_(issubclass(self.A.rjust(10).dtype.type, np.string_)) diff --git a/numpy/core/tests/test_deprecations.py b/numpy/core/tests/test_deprecations.py index 7232b5949..9d68167fa 100644 --- a/numpy/core/tests/test_deprecations.py +++ b/numpy/core/tests/test_deprecations.py @@ -227,15 +227,10 @@ class TestComparisonDeprecations(_DeprecationTestCase): struct = np.zeros(2, dtype="i4,i4") for arg2 in [struct, "a"]: for f in [operator.lt, operator.le, operator.gt, operator.ge]: - if sys.version_info[0] >= 3: - # py3 - with warnings.catch_warnings() as l: - warnings.filterwarnings("always") - assert_raises(TypeError, f, arg1, arg2) - assert_(not l) - else: - # py2 - assert_warns(DeprecationWarning, f, arg1, arg2) + with warnings.catch_warnings() as l: + warnings.filterwarnings("always") + assert_raises(TypeError, f, arg1, arg2) + assert_(not l) class TestDatetime64Timezone(_DeprecationTestCase): @@ -332,9 +327,6 @@ class TestNumericStyleTypecodes(_DeprecationTestCase): 'Int8', 'Int16', 'Int32', 'Int64', 'Object0', 'Timedelta64', 'UInt8', 'UInt16', 'UInt32', 'UInt64', 'Void0' ] - if sys.version_info[0] < 3: - deprecated_types.extend(['Unicode0', 'String0']) - for dt in deprecated_types: self.assert_deprecated(np.dtype, exceptions=(TypeError,), args=(dt,)) @@ -355,28 +347,6 @@ class TestTestDeprecated: test_case_instance.teardown() -class TestClassicIntDivision(_DeprecationTestCase): - """ - See #7949. Deprecate the numeric-style dtypes with -3 flag in python 2 - if used for division - List of data types: https://docs.scipy.org/doc/numpy/user/basics.types.html - """ - def test_int_dtypes(self): - #scramble types and do some mix and match testing - deprecated_types = [ - 'bool_', 'int_', 'intc', 'uint8', 'int8', 'uint64', 'int32', 'uint16', - 'intp', 'int64', 'uint32', 'int16' - ] - if sys.version_info[0] < 3 and sys.py3kwarning: - import operator as op - dt2 = 'bool_' - for dt1 in deprecated_types: - a = np.array([1,2,3], dtype=dt1) - b = np.array([1,2,3], dtype=dt2) - self.assert_deprecated(op.div, args=(a,b)) - dt2 = dt1 - - class TestNonNumericConjugate(_DeprecationTestCase): """ Deprecate no-op behavior of ndarray.conjugate on non-numeric dtypes, diff --git a/numpy/core/tests/test_dtype.py b/numpy/core/tests/test_dtype.py index 1d24d8a3d..c9a65cd9c 100644 --- a/numpy/core/tests/test_dtype.py +++ b/numpy/core/tests/test_dtype.py @@ -136,11 +136,11 @@ class TestBuiltin: 'offsets':[0, 2]}, align=True) def test_field_order_equality(self): - x = np.dtype({'names': ['A', 'B'], - 'formats': ['i4', 'f4'], + x = np.dtype({'names': ['A', 'B'], + 'formats': ['i4', 'f4'], 'offsets': [0, 4]}) - y = np.dtype({'names': ['B', 'A'], - 'formats': ['f4', 'i4'], + y = np.dtype({'names': ['B', 'A'], + 'formats': ['f4', 'i4'], 'offsets': [4, 0]}) assert_equal(x == y, False) @@ -418,7 +418,7 @@ class TestRecord: {'formats': ['i4', 'i4'], 'f0': ('i4', 0), 'f1':('i4', 4)}) def test_fieldless_views(self): - a = np.zeros(2, dtype={'names':[], 'formats':[], 'offsets':[], + a = np.zeros(2, dtype={'names':[], 'formats':[], 'offsets':[], 'itemsize':8}) assert_raises(ValueError, a.view, np.dtype([])) @@ -900,11 +900,6 @@ class TestString: assert_equal(repr(dt), "dtype(('<i2', (1,)))") assert_equal(str(dt), "('<i2', (1,))") - @pytest.mark.skipif(sys.version_info[0] >= 3, reason="Python 2 only") - def test_dtype_str_with_long_in_shape(self): - # Pull request #376, should not error - np.dtype('(1L,)i4') - def test_base_dtype_with_object_type(self): # Issue gh-2798, should not error. np.array(['a'], dtype="O").astype(("O", [("name", "O")])) diff --git a/numpy/core/tests/test_mem_overlap.py b/numpy/core/tests/test_mem_overlap.py index c5115fa7e..7c1cff9b7 100644 --- a/numpy/core/tests/test_mem_overlap.py +++ b/numpy/core/tests/test_mem_overlap.py @@ -11,9 +11,6 @@ from numpy.testing import ( assert_, assert_raises, assert_equal, assert_array_equal ) -if sys.version_info[0] >= 3: - xrange = range - ndims = 2 size = 10 @@ -138,11 +135,7 @@ def test_diophantine_fuzz(): # Check no solution exists (provided the problem is # small enough so that brute force checking doesn't # take too long) - try: - ranges = tuple(xrange(0, a*ub+1, a) for a, ub in zip(A, U)) - except OverflowError: - # xrange on 32-bit Python 2 may overflow - continue + ranges = tuple(range(0, a*ub+1, a) for a, ub in zip(A, U)) size = 1 for r in ranges: @@ -475,7 +468,7 @@ def check_internal_overlap(a, manual_expected=None): # Brute-force check m = set() - ranges = tuple(xrange(n) for n in a.shape) + ranges = tuple(range(n) for n in a.shape) for v in itertools.product(*ranges): offset = sum(s*w for s, w in zip(a.strides, v)) if offset in m: diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py index ab1112b65..fef9ba234 100644 --- a/numpy/core/tests/test_multiarray.py +++ b/numpy/core/tests/test_multiarray.py @@ -29,10 +29,7 @@ except ImportError: except ImportError: pathlib = None -if sys.version_info[0] >= 3: - import builtins -else: - import __builtin__ as builtins +import builtins from decimal import Decimal import numpy as np @@ -161,7 +158,6 @@ class TestFlags: vals.setflags(write=True) assert_(vals.flags.writeable) - @pytest.mark.skipif(sys.version_info[0] < 3, reason="Python 2 always copies") @pytest.mark.skipif(IS_PYPY, reason="PyPy always copies") def test_writeable_pickle(self): import pickle @@ -943,13 +939,6 @@ class TestCreation: assert_equal(np.array([[1j, 1j],[1, 1]]).dtype, complex) assert_equal(np.array([[1, 1, 1],[1, 1j, 1.], [1, 1, 1]]).dtype, complex) - @pytest.mark.skipif(sys.version_info[0] >= 3, reason="Not Python 2") - def test_sequence_long(self): - assert_equal(np.array([long(4), long(4)]).dtype, long) - assert_equal(np.array([long(4), 2**80]).dtype, object) - assert_equal(np.array([long(4), 2**80, long(4)]).dtype, object) - assert_equal(np.array([2**80, long(4)]).dtype, object) - def test_non_sequence_sequence(self): """Should not segfault. @@ -3347,6 +3336,7 @@ class TestBinop: 'and': (np.bitwise_and, True, int), 'xor': (np.bitwise_xor, True, int), 'or': (np.bitwise_or, True, int), + 'matmul': (np.matmul, False, float), # 'ge': (np.less_equal, False), # 'gt': (np.less, False), # 'le': (np.greater_equal, False), @@ -3354,8 +3344,6 @@ class TestBinop: # 'eq': (np.equal, False), # 'ne': (np.not_equal, False), } - if sys.version_info >= (3, 5): - ops['matmul'] = (np.matmul, False, float) class Coerced(Exception): pass @@ -3780,8 +3768,6 @@ class TestSubscripting: def test_test_zero_rank(self): x = np.array([1, 2, 3]) assert_(isinstance(x[0], np.int_)) - if sys.version_info[0] < 3: - assert_(isinstance(x[0], int)) assert_(type(x[0, ...]) is np.ndarray) @@ -3880,10 +3866,7 @@ class TestPickling: assert ref() is None def _loads(self, obj): - if sys.version_info[0] >= 3: - return pickle.loads(obj, encoding='latin1') - else: - return pickle.loads(obj) + return pickle.loads(obj, encoding='latin1') # version 0 pickles, using protocol=2 to pickle # version 0 doesn't have a version field @@ -5192,7 +5175,6 @@ class TestRecord: # Error raised when multiple fields have the same name assert_raises(ValueError, test_dtype_init) - @pytest.mark.skipif(sys.version_info[0] < 3, reason="Not Python 3") def test_bytes_fields(self): # Bytes are not allowed in field names and not recognized in titles # on Py3 @@ -5208,7 +5190,6 @@ class TestRecord: y = x[0] assert_raises(IndexError, y.__getitem__, b'a') - @pytest.mark.skipif(sys.version_info[0] < 3, reason="Not Python 3") def test_multiple_field_name_unicode(self): def test_dtype_unicode(): np.dtype([("\u20B9", "f8"), ("B", "f8"), ("\u20B9", "f8")]) @@ -5216,32 +5197,6 @@ class TestRecord: # Error raised when multiple fields have the same name(unicode included) assert_raises(ValueError, test_dtype_unicode) - @pytest.mark.skipif(sys.version_info[0] >= 3, reason="Not Python 2") - def test_unicode_field_titles(self): - # Unicode field titles are added to field dict on Py2 - title = u'b' - dt = np.dtype([((title, 'a'), int)]) - dt[title] - dt['a'] - x = np.array([(1,), (2,), (3,)], dtype=dt) - x[title] - x['a'] - y = x[0] - y[title] - y['a'] - - @pytest.mark.skipif(sys.version_info[0] >= 3, reason="Not Python 2") - def test_unicode_field_names(self): - # Unicode field names are converted to ascii on Python 2: - encodable_name = u'b' - assert_equal(np.dtype([(encodable_name, int)]).names[0], b'b') - assert_equal(np.dtype([(('a', encodable_name), int)]).names[0], b'b') - - # But raises UnicodeEncodeError if it can't be encoded: - nonencodable_name = u'\uc3bc' - assert_raises(UnicodeEncodeError, np.dtype, [(nonencodable_name, int)]) - assert_raises(UnicodeEncodeError, np.dtype, [(('a', nonencodable_name), int)]) - def test_fromarrays_unicode(self): # A single name string provided to fromarrays() is allowed to be unicode # on both Python 2 and 3: @@ -6269,56 +6224,55 @@ class TestMatmul(MatmulCommon): assert not np.any(c) -if sys.version_info[:2] >= (3, 5): - class TestMatmulOperator(MatmulCommon): - import operator - matmul = operator.matmul - - def test_array_priority_override(self): - - class A: - __array_priority__ = 1000 +class TestMatmulOperator(MatmulCommon): + import operator + matmul = operator.matmul - def __matmul__(self, other): - return "A" + def test_array_priority_override(self): - def __rmatmul__(self, other): - return "A" - - a = A() - b = np.ones(2) - assert_equal(self.matmul(a, b), "A") - assert_equal(self.matmul(b, a), "A") - - def test_matmul_raises(self): - assert_raises(TypeError, self.matmul, np.int8(5), np.int8(5)) - assert_raises(TypeError, self.matmul, np.void(b'abc'), np.void(b'abc')) - assert_raises(ValueError, self.matmul, np.arange(10), np.void(b'abc')) - - def test_matmul_inplace(): - # It would be nice to support in-place matmul eventually, but for now - # we don't have a working implementation, so better just to error out - # and nudge people to writing "a = a @ b". - a = np.eye(3) - b = np.eye(3) - assert_raises(TypeError, a.__imatmul__, b) - import operator - assert_raises(TypeError, operator.imatmul, a, b) - # we avoid writing the token `exec` so as not to crash python 2's - # parser - exec_ = getattr(builtins, "exec") - assert_raises(TypeError, exec_, "a @= b", globals(), locals()) - - def test_matmul_axes(): - a = np.arange(3*4*5).reshape(3, 4, 5) - c = np.matmul(a, a, axes=[(-2, -1), (-1, -2), (1, 2)]) - assert c.shape == (3, 4, 4) - d = np.matmul(a, a, axes=[(-2, -1), (-1, -2), (0, 1)]) - assert d.shape == (4, 4, 3) - e = np.swapaxes(d, 0, 2) - assert_array_equal(e, c) - f = np.matmul(a, np.arange(3), axes=[(1, 0), (0), (0)]) - assert f.shape == (4, 5) + class A: + __array_priority__ = 1000 + + def __matmul__(self, other): + return "A" + + def __rmatmul__(self, other): + return "A" + + a = A() + b = np.ones(2) + assert_equal(self.matmul(a, b), "A") + assert_equal(self.matmul(b, a), "A") + + def test_matmul_raises(self): + assert_raises(TypeError, self.matmul, np.int8(5), np.int8(5)) + assert_raises(TypeError, self.matmul, np.void(b'abc'), np.void(b'abc')) + assert_raises(ValueError, self.matmul, np.arange(10), np.void(b'abc')) + +def test_matmul_inplace(): + # It would be nice to support in-place matmul eventually, but for now + # we don't have a working implementation, so better just to error out + # and nudge people to writing "a = a @ b". + a = np.eye(3) + b = np.eye(3) + assert_raises(TypeError, a.__imatmul__, b) + import operator + assert_raises(TypeError, operator.imatmul, a, b) + # we avoid writing the token `exec` so as not to crash python 2's + # parser + exec_ = getattr(builtins, "exec") + assert_raises(TypeError, exec_, "a @= b", globals(), locals()) + +def test_matmul_axes(): + a = np.arange(3*4*5).reshape(3, 4, 5) + c = np.matmul(a, a, axes=[(-2, -1), (-1, -2), (1, 2)]) + assert c.shape == (3, 4, 4) + d = np.matmul(a, a, axes=[(-2, -1), (-1, -2), (0, 1)]) + assert d.shape == (4, 4, 3) + e = np.swapaxes(d, 0, 2) + assert_array_equal(e, c) + f = np.matmul(a, np.arange(3), axes=[(1, 0), (0), (0)]) + assert f.shape == (4, 5) class TestInner: @@ -7195,7 +7149,6 @@ class TestNewBufferProtocol: a = np.empty((1,) * 32) self._check_roundtrip(a) - @pytest.mark.skipif(sys.version_info < (2, 7, 7), reason="See gh-11115") def test_error_too_many_dims(self): def make_ctype(shape, scalar_type): t = scalar_type @@ -7236,12 +7189,11 @@ class TestNewBufferProtocol: np.array(t()) exc = cm.exception - if sys.version_info.major > 2: - with assert_raises_regex( - NotImplementedError, - r"Unrepresentable .* 'u' \(UCS-2 strings\)" - ): - raise exc.__cause__ + with assert_raises_regex( + NotImplementedError, + r"Unrepresentable .* 'u' \(UCS-2 strings\)" + ): + raise exc.__cause__ def test_ctypes_integer_via_memoryview(self): # gh-11150, due to bpo-10746 @@ -7797,11 +7749,6 @@ class TestArrayPriority: op.ge, op.lt, op.le, op.ne, op.eq ] - # See #7949. Don't use "/" operator With -3 switch, since python reports it - # as a DeprecationWarning - if sys.version_info[0] < 3 and not sys.py3kwarning: - binary_ops.append(op.div) - class Foo(np.ndarray): __array_priority__ = 100. @@ -7929,14 +7876,7 @@ class TestFormat: def test_1d_format(self): # until gh-5543, ensure that the behaviour matches what it used to be a = np.array([np.pi]) - if sys.version_info[:2] >= (3, 4): - assert_raises(TypeError, '{:30}'.format, a) - else: - with suppress_warnings() as sup: - sup.filter(PendingDeprecationWarning) - res = '{:30}'.format(a) - dst = object.__format__(a, '30') - assert_equal(res, dst) + assert_raises(TypeError, '{:30}'.format, a) from numpy.testing import IS_PYPY diff --git a/numpy/core/tests/test_numerictypes.py b/numpy/core/tests/test_numerictypes.py index 7105154ed..c72d13947 100644 --- a/numpy/core/tests/test_numerictypes.py +++ b/numpy/core/tests/test_numerictypes.py @@ -306,10 +306,7 @@ class ReadValuesNested: h = np.array(self._buffer, dtype=self._descr) assert_(h.dtype['Info']['value'].name == 'complex128') assert_(h.dtype['Info']['y2'].name == 'float64') - if sys.version_info[0] >= 3: - assert_(h.dtype['info']['Name'].name == 'str256') - else: - assert_(h.dtype['info']['Name'].name == 'unicode256') + assert_(h.dtype['info']['Name'].name == 'str256') assert_(h.dtype['info']['Value'].name == 'complex128') def test_nested2_descriptor(self): diff --git a/numpy/core/tests/test_print.py b/numpy/core/tests/test_print.py index 36d652a41..89a8b48bf 100644 --- a/numpy/core/tests/test_print.py +++ b/numpy/core/tests/test_print.py @@ -7,10 +7,7 @@ from numpy.testing import assert_, assert_equal from numpy.core.tests._locales import CommaDecimalPointLocale -if sys.version_info[0] >= 3: - from io import StringIO -else: - from StringIO import StringIO +from io import StringIO _REF = {np.inf: 'inf', -np.inf: '-inf', np.nan: 'nan'} diff --git a/numpy/core/tests/test_records.py b/numpy/core/tests/test_records.py index 060176d3d..bf43fedcc 100644 --- a/numpy/core/tests/test_records.py +++ b/numpy/core/tests/test_records.py @@ -24,12 +24,8 @@ class TestFromrecords: names='col1,col2,col3') assert_equal(r[0].item(), (456, 'dbe', 1.2)) assert_equal(r['col1'].dtype.kind, 'i') - if sys.version_info[0] >= 3: - assert_equal(r['col2'].dtype.kind, 'U') - assert_equal(r['col2'].dtype.itemsize, 12) - else: - assert_equal(r['col2'].dtype.kind, 'S') - assert_equal(r['col2'].dtype.itemsize, 3) + assert_equal(r['col2'].dtype.kind, 'U') + assert_equal(r['col2'].dtype.itemsize, 12) assert_equal(r['col3'].dtype.kind, 'f') def test_fromrecords_0len(self): diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py index 10255b88d..1d268d3fc 100644 --- a/numpy/core/tests/test_regression.py +++ b/numpy/core/tests/test_regression.py @@ -487,15 +487,13 @@ class TestRegression: b"bI00\nS'O\\x81\\xb7Z\\xaa:\\xabY'\np22\ntp23\nb."), ] - if sys.version_info[:2] >= (3, 4): - # encoding='bytes' was added in Py3.4 - for original, data in test_data: - result = pickle.loads(data, encoding='bytes') - assert_equal(result, original) + for original, data in test_data: + result = pickle.loads(data, encoding='bytes') + assert_equal(result, original) - if isinstance(result, np.ndarray) and result.dtype.names is not None: - for name in result.dtype.names: - assert_(isinstance(name, str)) + if isinstance(result, np.ndarray) and result.dtype.names is not None: + for name in result.dtype.names: + assert_(isinstance(name, str)) def test_pickle_dtype(self): # Ticket #251 @@ -1106,14 +1104,8 @@ class TestRegression: # The dtype is float64, but the isbuiltin attribute is 0. data_dir = path.join(path.dirname(__file__), 'data') filename = path.join(data_dir, "astype_copy.pkl") - if sys.version_info[0] >= 3: - f = open(filename, 'rb') + with open(filename, 'rb') as f: xp = pickle.load(f, encoding='latin1') - f.close() - else: - f = open(filename) - xp = pickle.load(f) - f.close() xpd = xp.astype(np.float64) assert_((xp.__array_interface__['data'][0] != xpd.__array_interface__['data'][0])) @@ -1230,10 +1222,7 @@ class TestRegression: msg = 'unicode offset: %d chars' % i t = np.dtype([('a', 'S%d' % i), ('b', 'U2')]) x = np.array([(b'a', u'b')], dtype=t) - if sys.version_info[0] >= 3: - assert_equal(str(x), "[(b'a', 'b')]", err_msg=msg) - else: - assert_equal(str(x), "[('a', u'b')]", err_msg=msg) + assert_equal(str(x), "[(b'a', 'b')]", err_msg=msg) def test_sign_for_complex_nan(self): # Ticket 794. @@ -1815,11 +1804,6 @@ class TestRegression: assert_raises(RecursionError, int, a) assert_raises(RecursionError, long, a) assert_raises(RecursionError, float, a) - if sys.version_info.major == 2: - # in python 3, this falls back on operator.index, which fails on - # on dtype=object - assert_raises(RecursionError, oct, a) - assert_raises(RecursionError, hex, a) a[()] = None def test_object_array_circular_reference(self): @@ -1846,11 +1830,6 @@ class TestRegression: assert_equal(int(a), int(0)) assert_equal(long(a), long(0)) assert_equal(float(a), float(0)) - if sys.version_info.major == 2: - # in python 3, this falls back on operator.index, which fails on - # on dtype=object - assert_equal(oct(a), oct(0)) - assert_equal(hex(a), hex(0)) def test_object_array_self_copy(self): # An object array being copied into itself DECREF'ed before INCREF'ing @@ -1954,13 +1933,12 @@ class TestRegression: assert_equal(s[0], "\x01") def test_pickle_bytes_overwrite(self): - if sys.version_info[0] >= 3: - for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): - data = np.array([1], dtype='b') - data = pickle.loads(pickle.dumps(data, protocol=proto)) - data[0] = 0xdd - bytestring = "\x01 ".encode('ascii') - assert_equal(bytestring[0:1], '\x01'.encode('ascii')) + for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): + data = np.array([1], dtype='b') + data = pickle.loads(pickle.dumps(data, protocol=proto)) + data[0] = 0xdd + bytestring = "\x01 ".encode('ascii') + assert_equal(bytestring[0:1], '\x01'.encode('ascii')) def test_pickle_py2_array_latin1_hack(self): # Check that unpickling hacks in Py3 that support @@ -1971,12 +1949,11 @@ class TestRegression: b"tp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n(S'i1'\np8\n" b"I0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nNNNI-1\nI-1\nI0\ntp12\nbI00\nS'\\x81'\n" b"p13\ntp14\nb.") - if sys.version_info[0] >= 3: - # This should work: - result = pickle.loads(data, encoding='latin1') - assert_array_equal(result, np.array([129], dtype='b')) - # Should not segfault: - assert_raises(Exception, pickle.loads, data, encoding='koi8-r') + # This should work: + result = pickle.loads(data, encoding='latin1') + assert_array_equal(result, np.array([129], dtype='b')) + # Should not segfault: + assert_raises(Exception, pickle.loads, data, encoding='koi8-r') def test_pickle_py2_scalar_latin1_hack(self): # Check that scalar unpickling hack in Py3 that supports @@ -2003,25 +1980,24 @@ class TestRegression: b"tp8\nRp9\n."), 'different'), ] - if sys.version_info[0] >= 3: - for original, data, koi8r_validity in datas: - result = pickle.loads(data, encoding='latin1') - assert_equal(result, original) - - # Decoding under non-latin1 encoding (e.g.) KOI8-R can - # produce bad results, but should not segfault. - if koi8r_validity == 'different': - # Unicode code points happen to lie within latin1, - # but are different in koi8-r, resulting to silent - # bogus results - result = pickle.loads(data, encoding='koi8-r') - assert_(result != original) - elif koi8r_validity == 'invalid': - # Unicode code points outside latin1, so results - # to an encoding exception - assert_raises(ValueError, pickle.loads, data, encoding='koi8-r') - else: - raise ValueError(koi8r_validity) + for original, data, koi8r_validity in datas: + result = pickle.loads(data, encoding='latin1') + assert_equal(result, original) + + # Decoding under non-latin1 encoding (e.g.) KOI8-R can + # produce bad results, but should not segfault. + if koi8r_validity == 'different': + # Unicode code points happen to lie within latin1, + # but are different in koi8-r, resulting to silent + # bogus results + result = pickle.loads(data, encoding='koi8-r') + assert_(result != original) + elif koi8r_validity == 'invalid': + # Unicode code points outside latin1, so results + # to an encoding exception + assert_raises(ValueError, pickle.loads, data, encoding='koi8-r') + else: + raise ValueError(koi8r_validity) def test_structured_type_to_object(self): a_rec = np.array([(0, 1), (3, 2)], dtype='i4,i8') @@ -2094,10 +2070,7 @@ class TestRegression: # Ticket #2081. Python compiled with two byte unicode # can lead to truncation if itemsize is not properly # adjusted for NumPy's four byte unicode. - if sys.version_info[0] >= 3: - a = np.array(['abcd']) - else: - a = np.array([u'abcd']) + a = np.array(['abcd']) assert_equal(a.dtype.itemsize, 16) def test_unique_stable(self): @@ -2240,12 +2213,7 @@ class TestRegression: rhs = Foo() lhs = np.array(1) for f in [op.lt, op.le, op.gt, op.ge]: - if sys.version_info[0] >= 3: - assert_raises(TypeError, f, lhs, rhs) - elif not sys.py3kwarning: - # With -3 switch in python 2, DeprecationWarning is raised - # which we are not interested in - f(lhs, rhs) + assert_raises(TypeError, f, lhs, rhs) assert_(not op.eq(lhs, rhs)) assert_(op.ne(lhs, rhs)) diff --git a/numpy/core/tests/test_scalar_ctors.py b/numpy/core/tests/test_scalar_ctors.py index ae29d0605..d3592a5fc 100644 --- a/numpy/core/tests/test_scalar_ctors.py +++ b/numpy/core/tests/test_scalar_ctors.py @@ -40,19 +40,6 @@ class TestFromString: flongdouble = assert_warns(RuntimeWarning, np.longdouble, '-1e10000') assert_equal(flongdouble, -np.inf) - @pytest.mark.skipif((sys.version_info[0] >= 3) - or (sys.platform == "win32" - and platform.architecture()[0] == "64bit"), - reason="numpy.intp('0xff', 16) not supported on Py3 " - "or 64 bit Windows") - def test_intp(self): - # Ticket #99 - i_width = np.int_(0).nbytes*2 - 1 - np.intp('0x' + 'f'*i_width, 16) - assert_raises(OverflowError, np.intp, '0x' + 'f'*(i_width+1), 16) - assert_raises(ValueError, np.intp, '0x1', 32) - assert_equal(255, np.intp('0xFF', 16)) - class TestFromInt: def test_intp(self): diff --git a/numpy/core/tests/test_scalarbuffer.py b/numpy/core/tests/test_scalarbuffer.py index 85673e3ab..bda1c5333 100644 --- a/numpy/core/tests/test_scalarbuffer.py +++ b/numpy/core/tests/test_scalarbuffer.py @@ -31,8 +31,6 @@ scalars_and_codes = [ scalars_only, codes_only = zip(*scalars_and_codes) -@pytest.mark.skipif(sys.version_info.major < 3, - reason="Python 2 scalars lack a buffer interface") class TestScalarPEP3118: @pytest.mark.parametrize('scalar', scalars_only, ids=codes_only) @@ -91,7 +89,7 @@ class TestScalarPEP3118: expected = {'strides': (1,), 'itemsize': 1, 'ndim': 1, 'shape': (8,), 'format': 'B'} v = memoryview(dt1) - res = as_dict(v) + res = as_dict(v) assert_equal(res, expected) v = memoryview(dt2 - dt1) diff --git a/numpy/core/tests/test_scalarmath.py b/numpy/core/tests/test_scalarmath.py index 789ef4acd..c7f44cf50 100644 --- a/numpy/core/tests/test_scalarmath.py +++ b/numpy/core/tests/test_scalarmath.py @@ -84,7 +84,7 @@ class TestBaseMath: assert_almost_equal(np.square(inp2), np.multiply(inp2, inp2), err_msg=msg) # skip true divide for ints - if dt != np.int32 or (sys.version_info.major < 3 and not sys.py3kwarning): + if dt != np.int32: assert_almost_equal(np.reciprocal(inp2), np.divide(1, inp2), err_msg=msg) diff --git a/numpy/core/tests/test_shape_base.py b/numpy/core/tests/test_shape_base.py index d2f5287a6..7c23c7128 100644 --- a/numpy/core/tests/test_shape_base.py +++ b/numpy/core/tests/test_shape_base.py @@ -157,10 +157,8 @@ class TestHstack: def test_generator(self): with assert_warns(FutureWarning): hstack((np.arange(3) for _ in range(2))) - if sys.version_info.major > 2: - # map returns a list on Python 2 - with assert_warns(FutureWarning): - hstack(map(lambda x: x, np.ones((3, 2)))) + with assert_warns(FutureWarning): + hstack(map(lambda x: x, np.ones((3, 2)))) class TestVstack: diff --git a/numpy/core/tests/test_unicode.py b/numpy/core/tests/test_unicode.py index b8ec56116..686998aae 100644 --- a/numpy/core/tests/test_unicode.py +++ b/numpy/core/tests/test_unicode.py @@ -4,40 +4,28 @@ import numpy as np from numpy.compat import unicode from numpy.testing import assert_, assert_equal, assert_array_equal -# Guess the UCS length for this python interpreter -if sys.version_info[:2] >= (3, 3): - # Python 3.3 uses a flexible string representation - ucs4 = False - - def buffer_length(arr): - if isinstance(arr, unicode): - arr = str(arr) - if not arr: - charmax = 0 - else: - charmax = max([ord(c) for c in arr]) - if charmax < 256: - size = 1 - elif charmax < 65536: - size = 2 - else: - size = 4 - return size * len(arr) - v = memoryview(arr) - if v.shape is None: - return len(v) * v.itemsize +# Python 3.3+ uses a flexible string representation +ucs4 = False + +def buffer_length(arr): + if isinstance(arr, unicode): + arr = str(arr) + if not arr: + charmax = 0 + else: + charmax = max([ord(c) for c in arr]) + if charmax < 256: + size = 1 + elif charmax < 65536: + size = 2 else: - return np.prod(v.shape) * v.itemsize -else: - if len(buffer(u'u')) == 4: - ucs4 = True + size = 4 + return size * len(arr) + v = memoryview(arr) + if v.shape is None: + return len(v) * v.itemsize else: - ucs4 = False - - def buffer_length(arr): - if isinstance(arr, np.ndarray): - return len(arr.data) - return len(buffer(arr)) + return np.prod(v.shape) * v.itemsize # In both cases below we need to make sure that the byte swapped value (as # UCS4) is still a valid unicode: @@ -52,12 +40,8 @@ def test_string_cast(): uni_arr1 = str_arr.astype('>U') uni_arr2 = str_arr.astype('<U') - if sys.version_info[0] < 3: - assert_array_equal(str_arr, uni_arr1) - assert_array_equal(str_arr, uni_arr2) - else: - assert_(str_arr != uni_arr1) - assert_(str_arr != uni_arr2) + assert_(str_arr != uni_arr1) + assert_(str_arr != uni_arr2) assert_array_equal(uni_arr1, uni_arr2) diff --git a/numpy/distutils/tests/test_exec_command.py b/numpy/distutils/tests/test_exec_command.py index 2ac0a6308..3bbad9386 100644 --- a/numpy/distutils/tests/test_exec_command.py +++ b/numpy/distutils/tests/test_exec_command.py @@ -8,10 +8,7 @@ from numpy.testing import tempdir, assert_, assert_warns # In python 3 stdout, stderr are text (unicode compliant) devices, so to # emulate them import StringIO from the io module. -if sys.version_info[0] >= 3: - from io import StringIO -else: - from StringIO import StringIO +from io import StringIO class redirect_stdout: """Context manager to redirect stdout for exec_command test.""" diff --git a/numpy/f2py/tests/test_compile_function.py b/numpy/f2py/tests/test_compile_function.py index d40ed63cf..f76fd6448 100644 --- a/numpy/f2py/tests/test_compile_function.py +++ b/numpy/f2py/tests/test_compile_function.py @@ -14,8 +14,6 @@ from . import util def setup_module(): - if sys.platform == 'win32' and sys.version_info[0] < 3: - pytest.skip('Fails with MinGW64 Gfortran (Issue #9673)') if not util.has_c_compiler(): pytest.skip("Needs C compiler") if not util.has_f77_compiler(): diff --git a/numpy/fft/tests/test_pocketfft.py b/numpy/fft/tests/test_pocketfft.py index da31ec09e..14f92c081 100644 --- a/numpy/fft/tests/test_pocketfft.py +++ b/numpy/fft/tests/test_pocketfft.py @@ -6,10 +6,7 @@ from numpy.testing import ( ) import threading import sys -if sys.version_info[0] >= 3: - import queue -else: - import Queue as queue +import queue def fft1(x): diff --git a/numpy/lib/tests/test__datasource.py b/numpy/lib/tests/test__datasource.py index fdd22347d..d3bd88d7f 100644 --- a/numpy/lib/tests/test__datasource.py +++ b/numpy/lib/tests/test__datasource.py @@ -9,14 +9,9 @@ from numpy.testing import ( assert_, assert_equal, assert_raises, assert_warns ) -if sys.version_info[0] >= 3: - import urllib.request as urllib_request - from urllib.parse import urlparse - from urllib.error import URLError -else: - import urllib2 as urllib_request - from urlparse import urlparse - from urllib2 import URLError +import urllib.request as urllib_request +from urllib.parse import urlparse +from urllib.error import URLError def urlopen_stub(url, data=None): @@ -162,24 +157,6 @@ class TestDataSourceOpen: fp.close() assert_equal(magic_line, result) - @pytest.mark.skipif(sys.version_info[0] >= 3, reason="Python 2 only") - def test_Bz2File_text_mode_warning(self): - try: - import bz2 - except ImportError: - # We don't have the bz2 capabilities to test. - pytest.skip() - # Test datasource's internal file_opener for BZip2 files. - filepath = os.path.join(self.tmpdir, 'foobar.txt.bz2') - fp = bz2.BZ2File(filepath, 'w') - fp.write(magic_line) - fp.close() - with assert_warns(RuntimeWarning): - fp = self.ds.open(filepath, 'rt') - result = fp.readline() - fp.close() - assert_equal(magic_line, result) - class TestDataSourceExists: def setup(self): diff --git a/numpy/lib/tests/test_format.py b/numpy/lib/tests/test_format.py index 28ce038ae..24593d7b3 100644 --- a/numpy/lib/tests/test_format.py +++ b/numpy/lib/tests/test_format.py @@ -548,10 +548,7 @@ def test_load_padded_dtype(dt): def test_python2_python3_interoperability(): - if sys.version_info[0] >= 3: - fname = 'win64python2.npy' - else: - fname = 'python3.npy' + fname = 'win64python2.npy' path = os.path.join(os.path.dirname(__file__), 'data', fname) data = np.load(path) assert_array_equal(data, np.ones(2)) @@ -561,13 +558,7 @@ def test_pickle_python2_python3(): # Python 2 and Python 3 and vice versa data_dir = os.path.join(os.path.dirname(__file__), 'data') - if sys.version_info[0] >= 3: - xrange = range - else: - import __builtin__ - xrange = __builtin__.xrange - - expected = np.array([None, xrange, u'\u512a\u826f', + expected = np.array([None, range, u'\u512a\u826f', b'\xe4\xb8\x8d\xe8\x89\xaf'], dtype=object) @@ -583,34 +574,30 @@ def test_pickle_python2_python3(): else: data = data_f - if sys.version_info[0] >= 3: - if encoding == 'latin1' and fname.startswith('py2'): - assert_(isinstance(data[3], str)) - assert_array_equal(data[:-1], expected[:-1]) - # mojibake occurs - assert_array_equal(data[-1].encode(encoding), expected[-1]) - else: - assert_(isinstance(data[3], bytes)) - assert_array_equal(data, expected) + if encoding == 'latin1' and fname.startswith('py2'): + assert_(isinstance(data[3], str)) + assert_array_equal(data[:-1], expected[:-1]) + # mojibake occurs + assert_array_equal(data[-1].encode(encoding), expected[-1]) else: + assert_(isinstance(data[3], bytes)) assert_array_equal(data, expected) - if sys.version_info[0] >= 3: - if fname.startswith('py2'): - if fname.endswith('.npz'): - data = np.load(path, allow_pickle=True) - assert_raises(UnicodeError, data.__getitem__, 'x') - data.close() - data = np.load(path, allow_pickle=True, fix_imports=False, - encoding='latin1') - assert_raises(ImportError, data.__getitem__, 'x') - data.close() - else: - assert_raises(UnicodeError, np.load, path, - allow_pickle=True) - assert_raises(ImportError, np.load, path, - allow_pickle=True, fix_imports=False, - encoding='latin1') + if fname.startswith('py2'): + if fname.endswith('.npz'): + data = np.load(path, allow_pickle=True) + assert_raises(UnicodeError, data.__getitem__, 'x') + data.close() + data = np.load(path, allow_pickle=True, fix_imports=False, + encoding='latin1') + assert_raises(ImportError, data.__getitem__, 'x') + data.close() + else: + assert_raises(UnicodeError, np.load, path, + allow_pickle=True) + assert_raises(ImportError, np.load, path, + allow_pickle=True, fix_imports=False, + encoding='latin1') def test_pickle_disallow(): diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index dfce2d55d..7953de15d 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -23,8 +23,6 @@ from numpy.lib import ( from numpy.compat import long -PY2 = sys.version_info[0] == 2 - def get_mat(n): data = np.arange(n) data = np.add.outer(data, data) @@ -1568,11 +1566,8 @@ class TestLeaks: a.f = np.frompyfunc(getattr(a, name), 1, 1) out = a.f(np.arange(10)) a = None - if PY2: - assert_equal(sys.getrefcount(A_func), refcount) - else: - # A.func is part of a reference cycle if incr is non-zero - assert_equal(sys.getrefcount(A_func), refcount + incr) + # A.func is part of a reference cycle if incr is non-zero + assert_equal(sys.getrefcount(A_func), refcount + incr) for i in range(5): gc.collect() assert_equal(sys.getrefcount(A_func), refcount) diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index ba27eea6c..6460741b5 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -44,7 +44,6 @@ class TextIO(BytesIO): BytesIO.writelines(self, [asbytes(s) for s in lines]) -MAJVER, MINVER = sys.version_info[:2] IS_64BIT = sys.maxsize > 2**32 try: import bz2 @@ -528,12 +527,10 @@ class TestSaveTxt: a = np.array([utf8], dtype=np.unicode_) # our gz wrapper support encoding suffixes = ['', '.gz'] - # stdlib 2 versions do not support encoding - if MAJVER > 2: - if HAS_BZ2: - suffixes.append('.bz2') - if HAS_LZMA: - suffixes.extend(['.xz', '.lzma']) + if HAS_BZ2: + suffixes.append('.bz2') + if HAS_LZMA: + suffixes.extend(['.xz', '.lzma']) with tempdir() as tmpdir: for suffix in suffixes: np.savetxt(os.path.join(tmpdir, 'test.csv' + suffix), a, @@ -599,18 +596,14 @@ class LoadTxtBase: res = self.loadfunc(f) assert_array_equal(res, wanted) - # Python2 .open does not support encoding - @pytest.mark.skipif(MAJVER == 2, reason="Needs Python version >= 3") def test_compressed_gzip(self): self.check_compressed(gzip.open, ('.gz',)) @pytest.mark.skipif(not HAS_BZ2, reason="Needs bz2") - @pytest.mark.skipif(MAJVER == 2, reason="Needs Python version >= 3") def test_compressed_bz2(self): self.check_compressed(bz2.open, ('.bz2',)) @pytest.mark.skipif(not HAS_LZMA, reason="Needs lzma") - @pytest.mark.skipif(MAJVER == 2, reason="Needs Python version >= 3") def test_compressed_lzma(self): self.check_compressed(lzma.open, ('.xz', '.lzma')) diff --git a/numpy/lib/tests/test_mixins.py b/numpy/lib/tests/test_mixins.py index 7c22dae94..e184ffe19 100644 --- a/numpy/lib/tests/test_mixins.py +++ b/numpy/lib/tests/test_mixins.py @@ -6,9 +6,6 @@ import numpy as np from numpy.testing import assert_, assert_equal, assert_raises -PY2 = sys.version_info.major < 3 - - # NOTE: This class should be kept as an exact copy of the example from the # docstring for NDArrayOperatorsMixin. @@ -202,11 +199,10 @@ class TestNDArrayOperatorsMixin: array_like = ArrayLike(array) expected = ArrayLike(np.float64(5)) _assert_equal_type_and_value(expected, np.matmul(array_like, array)) - if not PY2: - _assert_equal_type_and_value( - expected, operator.matmul(array_like, array)) - _assert_equal_type_and_value( - expected, operator.matmul(array, array_like)) + _assert_equal_type_and_value( + expected, operator.matmul(array_like, array)) + _assert_equal_type_and_value( + expected, operator.matmul(array, array_like)) def test_ufunc_at(self): array = ArrayLike(np.array([1, 2, 3, 4])) diff --git a/numpy/lib/tests/test_regression.py b/numpy/lib/tests/test_regression.py index 019b7595e..37cc158ba 100644 --- a/numpy/lib/tests/test_regression.py +++ b/numpy/lib/tests/test_regression.py @@ -206,10 +206,7 @@ class TestRegression: def test_loadtxt_fields_subarrays(self): # For ticket #1936 - if sys.version_info[0] >= 3: - from io import StringIO - else: - from StringIO import StringIO + from io import StringIO dt = [("a", 'u1', 2), ("b", 'u1', 2)] x = np.loadtxt(StringIO("0 1 2 3"), dtype=dt) diff --git a/numpy/lib/tests/test_utils.py b/numpy/lib/tests/test_utils.py index 57c840342..c96bf795a 100644 --- a/numpy/lib/tests/test_utils.py +++ b/numpy/lib/tests/test_utils.py @@ -7,10 +7,7 @@ from numpy.testing import assert_, assert_equal, assert_raises_regex from numpy.lib import deprecate import numpy.lib.utils as utils -if sys.version_info[0] >= 3: - from io import StringIO -else: - from StringIO import StringIO +from io import StringIO @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO") diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py index 458b78580..7ef4b5030 100644 --- a/numpy/ma/tests/test_core.py +++ b/numpy/ma/tests/test_core.py @@ -5006,11 +5006,6 @@ class TestMaskedConstant: assert_raises(MaskError, operator.setitem, a_i, (), np.ma.masked) assert_raises(MaskError, int, np.ma.masked) - @pytest.mark.skipif(sys.version_info.major == 3, - reason="long doesn't exist in Python 3") - def test_coercion_long(self): - assert_raises(MaskError, long, np.ma.masked) - def test_coercion_float(self): a_f = np.zeros((), float) assert_warns(UserWarning, operator.setitem, a_f, (), np.ma.masked) diff --git a/numpy/testing/_private/nosetester.py b/numpy/testing/_private/nosetester.py index 4ca5267ce..45a582bb6 100644 --- a/numpy/testing/_private/nosetester.py +++ b/numpy/testing/_private/nosetester.py @@ -448,15 +448,6 @@ class NoseTester: warnings.simplefilter("always") from ...distutils import cpuinfo sup.filter(category=UserWarning, module=cpuinfo) - # See #7949: Filter out deprecation warnings due to the -3 flag to - # python 2 - if sys.version_info.major == 2 and sys.py3kwarning: - # This is very specific, so using the fragile module filter - # is fine - import threading - sup.filter(DeprecationWarning, message=r"buffer\(\) not supported in 3\.x") - sup.filter(DeprecationWarning, message=r"CObject type is not supported in 3\.x") - sup.filter(DeprecationWarning, message=r"comparing unequal types not supported in 3\.x") # Filter out some deprecation warnings inside nose 1.3.7 when run # on python 3.5b2. See # https://github.com/nose-devs/nose/issues/929 diff --git a/numpy/testing/_private/utils.py b/numpy/testing/_private/utils.py index 69b2af4df..1b88d91f6 100644 --- a/numpy/testing/_private/utils.py +++ b/numpy/testing/_private/utils.py @@ -21,10 +21,7 @@ from numpy.core import( intp, float32, empty, arange, array_repr, ndarray, isnat, array) import numpy.linalg.lapack_lite -if sys.version_info[0] >= 3: - from io import StringIO -else: - from StringIO import StringIO +from io import StringIO __all__ = [ 'assert_equal', 'assert_almost_equal', 'assert_approx_equal', @@ -1344,14 +1341,7 @@ def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs): """ __tracebackhide__ = True # Hide traceback for py.test - - if sys.version_info.major >= 3: - funcname = _d.assertRaisesRegex - else: - # Only present in Python 2.7, missing from unittest in 2.6 - funcname = _d.assertRaisesRegexp - - return funcname(exception_class, expected_regexp, *args, **kwargs) + return _d.assertRaisesRegex(exception_class, expected_regexp, *args, **kwargs) def decorate_methods(cls, decorator, testmatch=None): diff --git a/numpy/tests/test_public_api.py b/numpy/tests/test_public_api.py index 48dd42a9f..b4aa7ec3d 100644 --- a/numpy/tests/test_public_api.py +++ b/numpy/tests/test_public_api.py @@ -28,9 +28,6 @@ def check_dir(module, module_name=None): return results -@pytest.mark.skipif( - sys.version_info[0] < 3, - reason="NumPy exposes slightly different functions on Python 2") def test_numpy_namespace(): # None of these objects are publicly documented to be part of the main # NumPy namespace (some are useful though, others need to be cleaned up) diff --git a/numpy/tests/test_reloading.py b/numpy/tests/test_reloading.py index 2b5a324ba..a6d2e62a9 100644 --- a/numpy/tests/test_reloading.py +++ b/numpy/tests/test_reloading.py @@ -3,10 +3,7 @@ import sys from numpy.testing import assert_raises, assert_, assert_equal from numpy.compat import pickle -if sys.version_info[:2] >= (3, 4): - from importlib import reload -else: - from imp import reload +from importlib import reload def test_numpy_reloading(): # gh-7844. Also check that relevant globals retain their identity. diff --git a/numpy/tests/test_warnings.py b/numpy/tests/test_warnings.py index 48896f4b7..ff75681dc 100644 --- a/numpy/tests/test_warnings.py +++ b/numpy/tests/test_warnings.py @@ -5,72 +5,71 @@ all of these occurrences but should catch almost all. import sys import pytest -if sys.version_info >= (3, 4): - from pathlib import Path - import ast - import tokenize - import numpy +from pathlib import Path +import ast +import tokenize +import numpy - class ParseCall(ast.NodeVisitor): - def __init__(self): - self.ls = [] +class ParseCall(ast.NodeVisitor): + def __init__(self): + self.ls = [] - def visit_Attribute(self, node): - ast.NodeVisitor.generic_visit(self, node) - self.ls.append(node.attr) + def visit_Attribute(self, node): + ast.NodeVisitor.generic_visit(self, node) + self.ls.append(node.attr) - def visit_Name(self, node): - self.ls.append(node.id) + def visit_Name(self, node): + self.ls.append(node.id) - class FindFuncs(ast.NodeVisitor): - def __init__(self, filename): - super().__init__() - self.__filename = filename +class FindFuncs(ast.NodeVisitor): + def __init__(self, filename): + super().__init__() + self.__filename = filename - def visit_Call(self, node): - p = ParseCall() - p.visit(node.func) - ast.NodeVisitor.generic_visit(self, node) + def visit_Call(self, node): + p = ParseCall() + p.visit(node.func) + ast.NodeVisitor.generic_visit(self, node) - if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings': - if node.args[0].s == "ignore": - raise AssertionError( - "ignore filter should not be used; found in " - "{} on line {}".format(self.__filename, node.lineno)) + if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings': + if node.args[0].s == "ignore": + raise AssertionError( + "ignore filter should not be used; found in " + "{} on line {}".format(self.__filename, node.lineno)) - if p.ls[-1] == 'warn' and ( - len(p.ls) == 1 or p.ls[-2] == 'warnings'): + if p.ls[-1] == 'warn' and ( + len(p.ls) == 1 or p.ls[-2] == 'warnings'): - if "testing/tests/test_warnings.py" == self.__filename: - # This file - return + if "testing/tests/test_warnings.py" == self.__filename: + # This file + return - # See if stacklevel exists: - if len(node.args) == 3: - return - args = {kw.arg for kw in node.keywords} - if "stacklevel" in args: - return - raise AssertionError( - "warnings should have an appropriate stacklevel; found in " - "{} on line {}".format(self.__filename, node.lineno)) + # See if stacklevel exists: + if len(node.args) == 3: + return + args = {kw.arg for kw in node.keywords} + if "stacklevel" in args: + return + raise AssertionError( + "warnings should have an appropriate stacklevel; found in " + "{} on line {}".format(self.__filename, node.lineno)) - @pytest.mark.slow - def test_warning_calls(): - # combined "ignore" and stacklevel error - base = Path(numpy.__file__).parent +@pytest.mark.slow +def test_warning_calls(): + # combined "ignore" and stacklevel error + base = Path(numpy.__file__).parent - for path in base.rglob("*.py"): - if base / "testing" in path.parents: - continue - if path == base / "__init__.py": - continue - if path == base / "random" / "__init__.py": - continue - # use tokenize to auto-detect encoding on systems where no - # default encoding is defined (e.g. LANG='C') - with tokenize.open(str(path)) as file: - tree = ast.parse(file.read()) - FindFuncs(path).visit(tree) + for path in base.rglob("*.py"): + if base / "testing" in path.parents: + continue + if path == base / "__init__.py": + continue + if path == base / "random" / "__init__.py": + continue + # use tokenize to auto-detect encoding on systems where no + # default encoding is defined (e.g. LANG='C') + with tokenize.open(str(path)) as file: + tree = ast.parse(file.read()) + FindFuncs(path).visit(tree) |