Exemplo n.º 1
0
    def test_seq_repeat(self):
        # Test that basic sequences get repeated when multiplied with
        # numpy integers. And errors are raised when multiplied with others.
        # Some of this behaviour may be controversial and could be open for
        # change.
        accepted_types = set(np.typecodes["AllInteger"])
        deprecated_types = set('?')
        forbidden_types = (set(np.typecodes["All"]) - accepted_types -
                           deprecated_types)
        forbidden_types -= set('V')  # can't default-construct void scalars

        for seq_type in (list, tuple):
            seq = seq_type([1, 2, 3])
            for numpy_type in accepted_types:
                i = np.dtype(numpy_type).type(2)
                assert_equal(seq * i, seq * int(i))
                assert_equal(i * seq, int(i) * seq)

            for numpy_type in deprecated_types:
                i = np.dtype(numpy_type).type()
                assert_equal(
                    assert_warns(DeprecationWarning, operator.mul, seq, i),
                    seq * int(i))
                assert_equal(
                    assert_warns(DeprecationWarning, operator.mul, i, seq),
                    int(i) * seq)

            for numpy_type in forbidden_types:
                i = np.dtype(numpy_type).type()
                assert_raises(TypeError, operator.mul, seq, i)
                assert_raises(TypeError, operator.mul, i, seq)
Exemplo n.º 2
0
 def test_deprecations(self):
     # 2017-05-17, 1.13.0
     s = (2, 3, 4, 5)
     a = np.empty(s)
     with warnings.catch_warnings():
         warnings.simplefilter("always")
         assert_warns(DeprecationWarning, expand_dims, a, -6)
         assert_warns(DeprecationWarning, expand_dims, a, 5)
Exemplo n.º 3
0
    def test_bool_as_int_argument_errors(self):
        a = np.array([[[1]]])

        assert_raises(TypeError, np.reshape, a, (True, -1))
        assert_raises(TypeError, np.reshape, a, (np.bool_(True), -1))
        # Note that operator.index(np.array(True)) does not work, a boolean
        # array is thus also deprecated, but not with the same message:
        assert_raises(TypeError, operator.index, np.array(True))
        assert_warns(DeprecationWarning, operator.index, np.True_)
        assert_raises(TypeError, np.take, args=(a, [0], False))
Exemplo n.º 4
0
    def test_basic(self):
        a = np.zeros((5, 5))
        with warnings.catch_warnings():
            warnings.filterwarnings('always')
            assert_warns(FutureWarning, a.__getitem__, [[0, 1], [0, 1]])
            assert_warns(FutureWarning, a.__getitem__, [slice(None)])

            warnings.filterwarnings('error')
            assert_raises(FutureWarning, a.__getitem__, [[0, 1], [0, 1]])
            assert_raises(FutureWarning, a.__getitem__, [slice(None)])

            # a a[[0, 1]] always was advanced indexing, so no error/warning
            a[[0, 1]]
Exemplo n.º 5
0
    def test_warn_wrong_warning(self):
        def f():
            warnings.warn("yo", DeprecationWarning)

        failed = False
        with warnings.catch_warnings():
            warnings.simplefilter("error", DeprecationWarning)
            try:
                # Should raise a DeprecationWarning
                assert_warns(UserWarning, f)
                failed = True
            except DeprecationWarning:
                pass

        if failed:
            raise AssertionError("wrong warning caught by assert_warn")
Exemplo n.º 6
0
    def test_floating_overflow(self):
        """ Strings containing an unrepresentable float overflow """
        fhalf = np.half('1e10000')
        assert_equal(fhalf, np.inf)
        fsingle = np.single('1e10000')
        assert_equal(fsingle, np.inf)
        fdouble = np.double('1e10000')
        assert_equal(fdouble, np.inf)
        flongdouble = assert_warns(RuntimeWarning, np.longdouble, '1e10000')
        assert_equal(flongdouble, np.inf)

        fhalf = np.half('-1e10000')
        assert_equal(fhalf, -np.inf)
        fsingle = np.single('-1e10000')
        assert_equal(fsingle, -np.inf)
        fdouble = np.double('-1e10000')
        assert_equal(fdouble, -np.inf)
        flongdouble = assert_warns(RuntimeWarning, np.longdouble, '-1e10000')
        assert_equal(flongdouble, -np.inf)
Exemplo n.º 7
0
def test_qr_mode_full_future_warning():
    """Check mode='full' FutureWarning.

    In numpy 1.8 the mode options 'full' and 'economic' in linalg.qr were
    deprecated. The release date will probably be sometime in the summer
    of 2013.

    """
    a = np.eye(2)
    assert_warns(DeprecationWarning, np.linalg.qr, a, mode='full')
    assert_warns(DeprecationWarning, np.linalg.qr, a, mode='f')
    assert_warns(DeprecationWarning, np.linalg.qr, a, mode='economic')
    assert_warns(DeprecationWarning, np.linalg.qr, a, mode='e')
Exemplo n.º 8
0
    def test_boolean_index_cast_assign(self):
        # Setup the boolean index and float arrays.
        shape = (8, 63)
        bool_index = np.zeros(shape).astype(bool)
        bool_index[0, 1] = True
        zero_array = np.zeros(shape)

        # Assigning float is fine.
        zero_array[bool_index] = np.array([1])
        assert_equal(zero_array[0, 1], 1)

        # Fancy indexing works, although we get a cast warning.
        assert_warns(np.ComplexWarning,
                     zero_array.__setitem__, ([0], [1]), np.array([2 + 1j]))
        assert_equal(zero_array[0, 1], 2)  # No complex part

        # Cast complex to float, throwing away the imaginary portion.
        assert_warns(np.ComplexWarning,
                     zero_array.__setitem__, bool_index, np.array([1j]))
        assert_equal(zero_array[0, 1], 0)
Exemplo n.º 9
0
    def test_array_richcompare_legacy_weirdness(self):
        # It doesn't really work to use assert_deprecated here, b/c part of
        # the point of assert_deprecated is to check that when warnings are
        # set to "error" mode then the error is propagated -- which is good!
        # But here we are testing a bunch of code that is deprecated *because*
        # it has the habit of swallowing up errors and converting them into
        # different warnings. So assert_warns will have to be sufficient.
        assert_warns(FutureWarning, lambda: np.arange(2) == "a")
        assert_warns(FutureWarning, lambda: np.arange(2) != "a")
        # No warning for scalar comparisons
        with warnings.catch_warnings():
            warnings.filterwarnings("error")
            assert_(not (np.array(0) == "a"))
            assert_(np.array(0) != "a")
            assert_(not (np.int16(0) == "a"))
            assert_(np.int16(0) != "a")

        for arg1 in [np.asarray(0), np.int16(0)]:
            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)
Exemplo n.º 10
0
    def test_0d_arrays(self):
        unicode = type(u'')

        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(str(np.array('test', np.str_)), 'test')

        a = np.zeros(1, dtype=[('a', '<i4', (3, ))])
        assert_equal(str(a[0]), '([0, 0, 0],)')

        assert_equal(repr(np.datetime64('2005-02-25')[...]),
                     "array('2005-02-25', dtype='datetime64[D]')")

        assert_equal(repr(np.timedelta64('10', 'Y')[...]),
                     "array(10, dtype='timedelta64[Y]')")

        # repr of 0d arrays is affected by printoptions
        x = np.array(1)
        np.set_printoptions(formatter={'all': lambda x: "test"})
        assert_equal(repr(x), "array(test)")
        # str is unaffected
        assert_equal(str(x), "1")

        # check `style` arg raises
        assert_warns(DeprecationWarning,
                     np.array2string,
                     np.array(1.),
                     style=repr)
        # but not in legacy mode
        np.array2string(np.array(1.), style=repr, legacy='1.13')
        # gh-10934 style was broken in legacy mode, check it works
        np.array2string(np.array(1.), legacy='1.13')
Exemplo n.º 11
0
    def test_context_manager(self):

        before_filters = sys.modules['warnings'].filters[:]
        with assert_warns(UserWarning):
            warnings.warn("yo")
        after_filters = sys.modules['warnings'].filters

        def no_warnings():
            with assert_no_warnings():
                warnings.warn("yo")

        assert_raises(AssertionError, no_warnings)
        assert_equal(before_filters, after_filters,
                     "assert_warns does not preserver warnings state")
Exemplo n.º 12
0
    def test_format_function(self):
        """Test custom format function for each element in array."""
        def _format_function(x):
            if np.abs(x) < 1:
                return '.'
            elif np.abs(x) < 2:
                return 'o'
            else:
                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]"
        assert_(
            np.array2string(x, formatter={'all': _format_function}) ==
            "[. o O]")
        assert_(
            np.array2string(x, formatter={'int_kind': _format_function}) ==
            "[. o O]")
        assert_(
            np.array2string(x, formatter={'all': lambda x: "%.4f" % x}) ==
            "[0.0000 1.0000 2.0000]")
        assert_equal(np.array2string(x, formatter={'int': lambda x: hex(x)}),
                     x_hex)
        assert_equal(np.array2string(x, formatter={'int': lambda x: oct(x)}),
                     x_oct)

        x = np.arange(3.)
        assert_(
            np.array2string(x, formatter={'float_kind': lambda x: "%.2f" % x})
            == "[0.00 1.00 2.00]")
        assert_(
            np.array2string(x, formatter={'float': lambda x: "%.2f" % x}) ==
            "[0.00 1.00 2.00]")

        s = np.array(['abc', 'def'])
        assert_(
            np.array2string(s, formatter={'numpystr': lambda s: s * 2}) ==
            '[abcabc defdef]')

        # check for backcompat that using FloatFormat works and emits warning
        with assert_warns(DeprecationWarning):
            fmt = np.core.arrayprint.FloatFormat(x, 9, 'maxprec', False)
        assert_equal(np.array2string(x, formatter={'float_kind': fmt}),
                     '[0. 1. 2.]')
Exemplo n.º 13
0
    def test_warn(self):
        def f():
            warnings.warn("yo")
            return 3

        before_filters = sys.modules['warnings'].filters[:]
        assert_equal(assert_warns(UserWarning, f), 3)
        after_filters = sys.modules['warnings'].filters

        assert_raises(AssertionError, assert_no_warnings, f)
        assert_equal(assert_no_warnings(lambda x: x, 1), 1)

        # Check that the warnings state is unchanged
        assert_equal(before_filters, after_filters,
                     "assert_warns does not preserver warnings state")
Exemplo n.º 14
0
    def test_axis_default(self):
        # NumPy 1.13, 2017-05-06

        data1d = np.ma.arange(6)
        data2d = data1d.reshape(2, 3)

        ma_min = np.ma.minimum.reduce
        ma_max = np.ma.maximum.reduce

        # check that the default axis is still None, but warns on 2d arrays
        result = assert_warns(MaskedArrayFutureWarning, ma_max, data2d)
        assert_equal(result, ma_max(data2d, axis=None))

        result = assert_warns(MaskedArrayFutureWarning, ma_min, data2d)
        assert_equal(result, ma_min(data2d, axis=None))

        # no warnings on 1d, as both new and old defaults are equivalent
        result = ma_min(data1d)
        assert_equal(result, ma_min(data1d, axis=None))
        assert_equal(result, ma_min(data1d, axis=0))

        result = ma_max(data1d)
        assert_equal(result, ma_max(data1d, axis=None))
        assert_equal(result, ma_max(data1d, axis=0))
Exemplo n.º 15
0
    def _test_base(self, argsort, cls):
        arr_0d = np.array(1).view(cls)
        argsort(arr_0d)

        arr_1d = np.array([1, 2, 3]).view(cls)
        argsort(arr_1d)

        # argsort has a bad default for >1d arrays
        arr_2d = np.array([[1, 2], [3, 4]]).view(cls)
        result = assert_warns(
            np.ma.core.MaskedArrayFutureWarning, argsort, arr_2d)
        assert_equal(result, argsort(arr_2d, axis=None))

        # should be no warnings for explicitly specifying it
        argsort(arr_2d, axis=None)
        argsort(arr_2d, axis=-1)
Exemplo n.º 16
0
 def test_Bz2File_text_mode_warning(self):
     try:
         import bz2
     except ImportError:
         # We don't have the bz2 capabilities to test.
         raise SkipTest
     # 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)
Exemplo n.º 17
0
    def test_void_dtype_equality_failures(self):
        class NotArray(object):
            def __array__(self):
                raise TypeError

            # Needed so Python 3 does not raise DeprecationWarning twice.
            def __ne__(self, other):
                return NotImplemented

        self.assert_deprecated(lambda: np.arange(2) == NotArray())
        self.assert_deprecated(lambda: np.arange(2) != NotArray())

        struct1 = np.zeros(2, dtype="i4,i4")
        struct2 = np.zeros(2, dtype="i4,i4,i4")

        assert_warns(FutureWarning, lambda: struct1 == 1)
        assert_warns(FutureWarning, lambda: struct1 == struct2)
        assert_warns(FutureWarning, lambda: struct1 != 1)
        assert_warns(FutureWarning, lambda: struct1 != struct2)
Exemplo n.º 18
0
 def test_deprecated(self):
     # NumPy 1.13.0, 2017-04-26
     assert_warns(DeprecationWarning, ufl.fix, [1, 2], y=nx.empty(2))
     assert_warns(DeprecationWarning, ufl.isposinf, [1, 2], y=nx.empty(2))
     assert_warns(DeprecationWarning, ufl.isneginf, [1, 2], y=nx.empty(2))
Exemplo n.º 19
0
 def test_maximum(self):
     assert_warns(DeprecationWarning, np.ma.maximum, np.ma.array([1, 2]))
Exemplo n.º 20
0
 def test(self):
     a = np.arange(10)
     assert_warns(np.VisibleDeprecationWarning, np.rank, a)