Python numpy.testing.assert_raises() Examples

The following are code examples for showing how to use numpy.testing.assert_raises(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: vnpy_crypto   Author: birforce   File: test_mlemodel.py    MIT License 6 votes vote down vote up
def test_predict():
    dates = pd.date_range(start='1980-01-01', end='1981-01-01', freq='AS')
    endog = pd.Series([1,2], index=dates)
    mod = MLEModel(endog, **kwargs)
    res = mod.filter([])

    # Test that predict with start=None, end=None does prediction with full
    # dataset
    predict = res.predict()
    assert_equal(predict.shape, (mod.nobs,))
    assert_allclose(res.get_prediction().predicted_mean, predict)

    # Test a string value to the dynamic option
    assert_allclose(res.predict(dynamic='1981-01-01'), res.predict())

    # Test an invalid date string value to the dynamic option
    # assert_raises(ValueError, res.predict, dynamic='1982-01-01')

    # Test for passing a string to predict when dates are not set
    mod = MLEModel([1,2], **kwargs)
    res = mod.filter([])
    assert_raises(KeyError, res.predict, dynamic='string') 
Example 2
Project: dismalpy   Author: dismalpy   File: test_mlemodel.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_fit_misc():
    true = results_sarimax.wpi1_stationary
    endog = np.diff(true['data'])[1:]

    mod = sarimax.SARIMAX(endog, order=(1,0,1), trend='c')

    # Test optim_hessian={'opg','oim','cs'}
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        res1 = mod.fit(method='ncg', disp=True, optim_hessian='opg')
        res2 = mod.fit(method='ncg', disp=True, optim_hessian='oim')
        res3 = mod.fit(method='ncg', disp=True, optim_hessian='cs')
        assert_raises(NotImplementedError, mod.fit, method='ncg', disp=False, optim_hessian='a')
    # Check that the Hessians broadly result in the same optimum
    assert_allclose(res1.llf, res2.llf, rtol=1e-2)
    assert_allclose(res1.llf, res3.llf, rtol=1e-2)

    # Test return_params=True
    mod, _ = get_dummy_mod(fit=False)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        res_params = mod.fit(disp=-1, return_params=True)

    assert_almost_equal(res_params, [0,0], 7) 
Example 3
Project: dismalpy   Author: dismalpy   File: test_mlemodel.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_predict():
    dates = pd.date_range(start='1980-01-01', end='1981-01-01', freq='AS')
    endog = pd.TimeSeries([1,2], index=dates)
    mod = MLEModel(endog, **kwargs)
    res = mod.filter([])

    # Test that predict with start=None, end=None does prediction with full
    # dataset
    predict = res.predict()
    assert_equal(predict.shape, (mod.nobs,))
    assert_allclose(res.get_prediction().predicted_mean, predict)

    # Test a string value to the dynamic option
    assert_allclose(res.predict(dynamic='1981-01-01'), res.predict())

    # Test an invalid date string value to the dynamic option
    assert_raises(ValueError, res.predict, dynamic='1982-01-01')

    # Test for passing a string to predict when dates are not set
    mod = MLEModel([1,2], **kwargs)
    res = mod.filter([])
    assert_raises(ValueError, res.predict, dynamic='string') 
Example 4
Project: Computable   Author: ktraunmueller   File: test_continuous_extra.py    MIT License 6 votes vote down vote up
def test_erlang_runtimewarning():
    # erlang should generate a RuntimeWarning if a non-integer
    # shape parameter is used.
    with warnings.catch_warnings():
        warnings.simplefilter("error", RuntimeWarning)

        # The non-integer shape parameter 1.3 should trigger a RuntimeWarning
        npt.assert_raises(RuntimeWarning,
                          stats.erlang.rvs, 1.3, loc=0, scale=1, size=4)

        # Calling the fit method with `f0` set to an integer should
        # *not* trigger a RuntimeWarning.  It should return the same
        # values as gamma.fit(...).
        data = [0.5, 1.0, 2.0, 4.0]
        result_erlang = stats.erlang.fit(data, f0=1)
        result_gamma = stats.gamma.fit(data, f0=1)
        npt.assert_allclose(result_erlang, result_gamma, rtol=1e-3) 
Example 5
Project: LaserTOF   Author: kyleuckert   File: test_return_real.py    MIT License 5 votes vote down vote up
def check_function(self, t):
        if t.__doc__.split()[0] 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(long(234)) - 234.0) <= 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 t.__doc__.split()[0] 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(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        try:
            r = t(10 ** 400)
            assert_(repr(r) in ['inf', 'Infinity'], repr(r))
        except OverflowError:
            pass 
Example 6
Project: LaserTOF   Author: kyleuckert   File: test_return_integer.py    MIT License 5 votes vote down vote up
def check_function(self, t):
        assert_(t(123) == 123, repr(t(123)))
        assert_(t(123.6) == 123)
        assert_(t(long(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_raises(ValueError, t, array([123],'S3'))
        assert_raises(ValueError, t, 'abc')

        assert_raises(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        if t.__doc__.split()[0] in ['t8', 's8']:
            assert_raises(OverflowError, t, 100000000000000000000000)
            assert_raises(OverflowError, t, 10000000011111111111111.23) 
Example 7
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 5 votes vote down vote up
def check_named_args(distfn, x, shape_args, defaults, meths):
    ## Check calling w/ named arguments.

    # check consistency of shapes, numargs and _parse signature
    signature = _getargspec(distfn._parse_args)
    npt.assert_(signature.varargs is None)
    npt.assert_(signature.keywords is None)
    npt.assert_(list(signature.defaults) == list(defaults))

    shape_argnames = signature.args[:-len(defaults)]  # a, b, loc=0, scale=1
    if distfn.shapes:
        shapes_ = distfn.shapes.replace(',', ' ').split()
    else:
        shapes_ = ''
    npt.assert_(len(shapes_) == distfn.numargs)
    npt.assert_(len(shapes_) == len(shape_argnames))

    # check calling w/ named arguments
    shape_args = list(shape_args)

    vals = [meth(x, *shape_args) for meth in meths]
    npt.assert_(np.all(np.isfinite(vals)))

    names, a, k = shape_argnames[:], shape_args[:], {}
    while names:
        k.update({names.pop(): a.pop()})
        v = [meth(x, *a, **k) for meth in meths]
        npt.assert_array_equal(vals, v)
        if 'n' not in k.keys():
            # `n` is first parameter of moment(), so can't be used as named arg
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", UserWarning)
                npt.assert_equal(distfn.moment(1, *a, **k),
                                 distfn.moment(1, *shape_args))

    # unknown arguments should not go through:
    k.update({'kaboom': 42})
    npt.assert_raises(TypeError, distfn.cdf, x, **k) 
Example 8
Project: LaserTOF   Author: kyleuckert   File: test_continuous_basic.py    MIT License 5 votes vote down vote up
def test_rvs_gh2069_regression():
    # Regression tests for gh-2069.  In scipy 0.17 and earlier,
    # these tests would fail.
    #
    # A typical example of the broken behavior:
    # >>> norm.rvs(loc=np.zeros(5), scale=np.ones(5))
    # array([-2.49613705, -2.49613705, -2.49613705, -2.49613705, -2.49613705])
    np.random.seed(123)
    vals = stats.norm.rvs(loc=np.zeros(5), scale=1)
    d = np.diff(vals)
    npt.assert_(np.all(d != 0), "All the values are equal, but they shouldn't be!")
    vals = stats.norm.rvs(loc=0, scale=np.ones(5))
    d = np.diff(vals)
    npt.assert_(np.all(d != 0), "All the values are equal, but they shouldn't be!")
    vals = stats.norm.rvs(loc=np.zeros(5), scale=np.ones(5))
    d = np.diff(vals)
    npt.assert_(np.all(d != 0), "All the values are equal, but they shouldn't be!")
    vals = stats.norm.rvs(loc=np.array([[0], [0]]), scale=np.ones(5))
    d = np.diff(vals.ravel())
    npt.assert_(np.all(d != 0), "All the values are equal, but they shouldn't be!")

    npt.assert_raises(ValueError, stats.norm.rvs, [[0, 0], [0, 0]],
                  [[1, 1], [1, 1]], 1)
    npt.assert_raises(ValueError, stats.gamma.rvs, [2, 3, 4, 5], 0, 1, (2, 2))
    npt.assert_raises(ValueError, stats.gamma.rvs, [1, 1, 1, 1], [0, 0, 0, 0],
                     [[1], [2]], (4,)) 
Example 9
Project: LaserTOF   Author: kyleuckert   File: test_sf_error.py    MIT License 5 votes vote down vote up
def test_errstate_pyx_basic():
    olderr = sc.geterr()
    with sc.errstate(singular='raise'):
        with assert_raises(sc.SpecialFunctionError):
            sc.loggamma(0)
    assert_equal(olderr, sc.geterr()) 
Example 10
Project: LaserTOF   Author: kyleuckert   File: test_sf_error.py    MIT License 5 votes vote down vote up
def test_errstate_c_basic():
    olderr = sc.geterr()
    with sc.errstate(domain='raise'):
        with assert_raises(sc.SpecialFunctionError):
            sc.spence(-1)
    assert_equal(olderr, sc.geterr()) 
Example 11
Project: LaserTOF   Author: kyleuckert   File: test_sf_error.py    MIT License 5 votes vote down vote up
def test_errstate_cpp_basic():
    olderr = sc.geterr()
    with sc.errstate(underflow='raise'):
        with assert_raises(sc.SpecialFunctionError):
            sc.wrightomega(-1000)
    assert_equal(olderr, sc.geterr()) 
Example 12
Project: LaserTOF   Author: kyleuckert   File: test_sf_error.py    MIT License 5 votes vote down vote up
def test_errstate_all_but_one():
    olderr = sc.geterr()
    with sc.errstate(all='raise', singular='ignore'):
        sc.gammaln(0)
        with assert_raises(sc.SpecialFunctionError):
            sc.spence(-1.0)
    assert_equal(olderr, sc.geterr()) 
Example 13
Project: LaserTOF   Author: kyleuckert   File: test_interpolative.py    MIT License 5 votes vote down vote up
def test_badcall(self):
        A = hilbert(5).astype(np.float32)
        assert_raises(ValueError, pymatrixid.interp_decomp, A, 1e-6, rand=False) 
Example 14
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_recfunctions.py    MIT License 5 votes vote down vote up
def test_autoconversion(self):
        # Tests autoconversion
        adtype = [('A', int), ('B', bool), ('C', float)]
        a = ma.array([(1, 2, 3)], mask=[(0, 1, 0)], dtype=adtype)
        bdtype = [('A', int), ('B', float), ('C', float)]
        b = ma.array([(4, 5, 6)], dtype=bdtype)
        control = ma.array([(1, 2, 3), (4, 5, 6)], mask=[(0, 1, 0), (0, 0, 0)],
                           dtype=bdtype)
        test = stack_arrays((a, b), autoconvert=True)
        assert_equal(test, control)
        assert_equal(test.mask, control.mask)
        with assert_raises(TypeError):
            stack_arrays((a, b), autoconvert=False) 
Example 15
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_recfunctions.py    MIT License 5 votes vote down vote up
def test_duplicate_keys(self):
        a = np.zeros(3, dtype=[('a', 'i4'), ('b', 'f4'), ('c', 'u1')])
        b = np.ones(3, dtype=[('c', 'u1'), ('b', 'f4'), ('a', 'i4')])
        assert_raises(ValueError, join_by, ['a', 'b', 'b'], a, b) 
Example 16
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_recfunctions.py    MIT License 5 votes vote down vote up
def test_no_postfix(self):
        assert_raises(ValueError, join_by, 'a', self.a, self.b,
                      r1postfix='', r2postfix='') 
Example 17
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_mixins.py    MIT License 5 votes vote down vote up
def test_opt_out(self):

        class OptOut(object):
            """Object that opts out of __array_ufunc__."""
            __array_ufunc__ = None

            def __add__(self, other):
                return self

            def __radd__(self, other):
                return self

        array_like = ArrayLike(1)
        opt_out = OptOut()

        # supported operations
        assert_(array_like + opt_out is opt_out)
        assert_(opt_out + array_like is opt_out)

        # not supported
        with assert_raises(TypeError):
            # don't use the Python default, array_like = array_like + opt_out
            array_like += opt_out
        with assert_raises(TypeError):
            array_like - opt_out
        with assert_raises(TypeError):
            opt_out - array_like 
Example 18
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_mixins.py    MIT License 5 votes vote down vote up
def test_object(self):
        x = ArrayLike(0)
        obj = object()
        with assert_raises(TypeError):
            x + obj
        with assert_raises(TypeError):
            obj + x
        with assert_raises(TypeError):
            x += obj 
Example 19
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_return_real.py    MIT License 5 votes vote down vote up
def check_function(self, t):
        if t.__doc__.split()[0] 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(long(234)) - 234.0) <= 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 t.__doc__.split()[0] 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(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        try:
            r = t(10 ** 400)
            assert_(repr(r) in ['inf', 'Infinity'], repr(r))
        except OverflowError:
            pass 
Example 20
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_return_integer.py    MIT License 5 votes vote down vote up
def check_function(self, t):
        assert_(t(123) == 123, repr(t(123)))
        assert_(t(123.6) == 123)
        assert_(t(long(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_raises(ValueError, t, array([123],'S3'))
        assert_raises(ValueError, t, 'abc')

        assert_raises(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        if t.__doc__.split()[0] in ['t8', 's8']:
            assert_raises(OverflowError, t, 100000000000000000000000)
            assert_raises(OverflowError, t, 10000000011111111111111.23) 
Example 21
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_errstate.py    MIT License 5 votes vote down vote up
def test_invalid(self):
        with np.errstate(all='raise', under='ignore'):
            a = -np.arange(3)
            # This should work
            with np.errstate(invalid='ignore'):
                np.sqrt(a)
            # While this should fail!
            with assert_raises(FloatingPointError):
                np.sqrt(a) 
Example 22
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_errstate.py    MIT License 5 votes vote down vote up
def test_divide(self):
        with np.errstate(all='raise', under='ignore'):
            a = -np.arange(3)
            # This should work
            with np.errstate(divide='ignore'):
                a // 0
            # While this should fail!
            with assert_raises(FloatingPointError):
                a // 0 
Example 23
Project: CLMM   Author: LSSTDESC   File: test_modeling_addback.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_reduced_shear():
    testing.assert_raises(ValueError, clmm.get_reduced_shear_from_convergence, np.array([-1,2,1]),
                          np.array([0.4,0.2]))
    
    testing.assert_equal(clmm.get_reduced_shear_from_convergence(1,0.5), 2)
    testing.assert_equal(clmm.get_reduced_shear_from_convergence(np.array([0.5, 0.75, 1.25]),
                                                                 np.array([0.75, -0.2, 0])),
                                                                 np.array([2, 0.625, 1.25])) 
Example 24
Project: CLMM   Author: LSSTDESC   File: test_load_clusters_with_gcr.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_types():
    testing.assert_raises(TypeError, clmm.lsst.load_from_dc2, 1.5, 'cosmoDC2_v1.1.4_small',
                          '.', _reader='test')
    testing.assert_raises(TypeError, clmm.lsst.load_from_dc2, 5, 'cosmoDC2_v1.1.4_small',
                          10, _reader='test') 
Example 25
Project: CLMM   Author: LSSTDESC   File: test_load_clusters_with_gcr.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ranges():
    testing.assert_raises(ValueError, clmm.lsst.load_from_dc2, -1, 'cosmoDC2_v1.1.4_small', '.',
                          _reader='test')
    testing.assert_raises(ValueError, clmm.lsst.load_from_dc2, int(1e10), 'cosmoDC2_v1.1.4_small', '.',
                          _reader='test')
    testing.assert_raises(ValueError, clmm.lsst.load_from_dc2, 5, 'cosmoDC2_v1.1.4_small', '.',
                          (-0.3, 0.3), (-0.3, 0.3, 0.1), (0.1, 1.5), _reader='test')
    testing.assert_raises(ValueError, clmm.lsst.load_from_dc2, 5, 'cosmoDC2_v1.1.4_small', '.',
                          (0.3, -0.3), (-0.3, 0.3), (0.1, 1.5), _reader='test') 
Example 26
Project: CLMM   Author: LSSTDESC   File: test_galaxycluster.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_integrity(): # Converge on name
    # Ensure we have all necessary values to make a GalaxyCluster
    testing.assert_raises(TypeError, clmm.GalaxyCluster, ra=161.3, dec=34., z=0.3, galcat=Table())
    testing.assert_raises(TypeError, clmm.GalaxyCluster, unique_id=1, dec=34., z=0.3, galcat=Table())
    testing.assert_raises(TypeError, clmm.GalaxyCluster, unique_id=1, ra=161.3, z=0.3, galcat=Table())
    testing.assert_raises(TypeError, clmm.GalaxyCluster, unique_id=1, ra=161.3, dec=34., galcat=Table())

    # Test that we get errors when we pass in values outside of the domains
    testing.assert_raises(ValueError, clmm.GalaxyCluster, unique_id=1, ra=-360.3, dec=34., z=0.3, galcat=Table())
    testing.assert_raises(ValueError, clmm.GalaxyCluster, unique_id=1, ra=360.3, dec=34., z=0.3, galcat=Table())
    testing.assert_raises(ValueError, clmm.GalaxyCluster, unique_id=1, ra=161.3, dec=95., z=0.3, galcat=Table())
    testing.assert_raises(ValueError, clmm.GalaxyCluster, unique_id=1, ra=161.3, dec=-95., z=0.3, galcat=Table())
    testing.assert_raises(ValueError, clmm.GalaxyCluster, unique_id=1, ra=161.3, dec=34., z=-0.3, galcat=Table())

    # Test that inputs are the correct type
    testing.assert_raises(TypeError, clmm.GalaxyCluster, unique_id=1, ra=161.3, dec=34., z=0.3, galcat=1)
    testing.assert_raises(TypeError, clmm.GalaxyCluster, unique_id=1, ra=161.3, dec=34., z=0.3, galcat=[])
    testing.assert_raises(TypeError, clmm.GalaxyCluster, unique_id=1, ra=None, dec=34., z=0.3, galcat=Table())
    testing.assert_raises(TypeError, clmm.GalaxyCluster, unique_id=1, ra=161.3, dec=None, z=0.3, galcat=Table())
    testing.assert_raises(TypeError, clmm.GalaxyCluster, unique_id=1, ra=161.3, dec=34., z=None, galcat=Table())

    # Test that id can support numbers and strings
    assert isinstance(clmm.GalaxyCluster(unique_id=1, ra=161.3, dec=34., z=0.3, galcat=Table()).unique_id, str)
    # assert clmm.GalaxyCluster(unique_id=1.0, ra=161.3, dec=34., z=0.3, galcat=Table()).unique_id == '1'
    assert isinstance(clmm.GalaxyCluster(unique_id='1', ra=161.3, dec=34., z=0.3, galcat=Table()).unique_id, str)

    # Test that ra/dec/z can be converted from int/str to float if needed
    assert clmm.GalaxyCluster('1', '161.', '55.', '.3', Table())
    assert clmm.GalaxyCluster('1', 161, 55, 1, Table()) 
Example 27
Project: recruit   Author: Frank-qlu   File: test_recfunctions.py    Apache License 2.0 5 votes vote down vote up
def test_autoconversion(self):
        # Tests autoconversion
        adtype = [('A', int), ('B', bool), ('C', float)]
        a = ma.array([(1, 2, 3)], mask=[(0, 1, 0)], dtype=adtype)
        bdtype = [('A', int), ('B', float), ('C', float)]
        b = ma.array([(4, 5, 6)], dtype=bdtype)
        control = ma.array([(1, 2, 3), (4, 5, 6)], mask=[(0, 1, 0), (0, 0, 0)],
                           dtype=bdtype)
        test = stack_arrays((a, b), autoconvert=True)
        assert_equal(test, control)
        assert_equal(test.mask, control.mask)
        with assert_raises(TypeError):
            stack_arrays((a, b), autoconvert=False) 
Example 28
Project: recruit   Author: Frank-qlu   File: test_recfunctions.py    Apache License 2.0 5 votes vote down vote up
def test_duplicate_keys(self):
        a = np.zeros(3, dtype=[('a', 'i4'), ('b', 'f4'), ('c', 'u1')])
        b = np.ones(3, dtype=[('c', 'u1'), ('b', 'f4'), ('a', 'i4')])
        assert_raises(ValueError, join_by, ['a', 'b', 'b'], a, b) 
Example 29
Project: recruit   Author: Frank-qlu   File: test_recfunctions.py    Apache License 2.0 5 votes vote down vote up
def test_no_postfix(self):
        assert_raises(ValueError, join_by, 'a', self.a, self.b,
                      r1postfix='', r2postfix='') 
Example 30
Project: recruit   Author: Frank-qlu   File: test_mixins.py    Apache License 2.0 5 votes vote down vote up
def test_opt_out(self):

        class OptOut(object):
            """Object that opts out of __array_ufunc__."""
            __array_ufunc__ = None

            def __add__(self, other):
                return self

            def __radd__(self, other):
                return self

        array_like = ArrayLike(1)
        opt_out = OptOut()

        # supported operations
        assert_(array_like + opt_out is opt_out)
        assert_(opt_out + array_like is opt_out)

        # not supported
        with assert_raises(TypeError):
            # don't use the Python default, array_like = array_like + opt_out
            array_like += opt_out
        with assert_raises(TypeError):
            array_like - opt_out
        with assert_raises(TypeError):
            opt_out - array_like 
Example 31
Project: recruit   Author: Frank-qlu   File: test_mixins.py    Apache License 2.0 5 votes vote down vote up
def test_object(self):
        x = ArrayLike(0)
        obj = object()
        with assert_raises(TypeError):
            x + obj
        with assert_raises(TypeError):
            obj + x
        with assert_raises(TypeError):
            x += obj 
Example 32
Project: recruit   Author: Frank-qlu   File: test_return_real.py    Apache License 2.0 5 votes vote down vote up
def check_function(self, t):
        if t.__doc__.split()[0] 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(long(234)) - 234.0) <= 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 t.__doc__.split()[0] 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(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        try:
            r = t(10 ** 400)
            assert_(repr(r) in ['inf', 'Infinity'], repr(r))
        except OverflowError:
            pass 
Example 33
Project: recruit   Author: Frank-qlu   File: test_return_integer.py    Apache License 2.0 5 votes vote down vote up
def check_function(self, t):
        assert_(t(123) == 123, repr(t(123)))
        assert_(t(123.6) == 123)
        assert_(t(long(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_raises(ValueError, t, array([123],'S3'))
        assert_raises(ValueError, t, 'abc')

        assert_raises(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        if t.__doc__.split()[0] in ['t8', 's8']:
            assert_raises(OverflowError, t, 100000000000000000000000)
            assert_raises(OverflowError, t, 10000000011111111111111.23) 
Example 34
Project: recruit   Author: Frank-qlu   File: test_errstate.py    Apache License 2.0 5 votes vote down vote up
def test_invalid(self):
        with np.errstate(all='raise', under='ignore'):
            a = -np.arange(3)
            # This should work
            with np.errstate(invalid='ignore'):
                np.sqrt(a)
            # While this should fail!
            with assert_raises(FloatingPointError):
                np.sqrt(a) 
Example 35
Project: recruit   Author: Frank-qlu   File: test_errstate.py    Apache License 2.0 5 votes vote down vote up
def test_divide(self):
        with np.errstate(all='raise', under='ignore'):
            a = -np.arange(3)
            # This should work
            with np.errstate(divide='ignore'):
                a // 0
            # While this should fail!
            with assert_raises(FloatingPointError):
                a // 0 
Example 36
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: common_tests.py    GNU General Public License v3.0 5 votes vote down vote up
def check_named_args(distfn, x, shape_args, defaults, meths):
    ## Check calling w/ named arguments.

    # check consistency of shapes, numargs and _parse signature
    signature = inspect.getargspec(distfn._parse_args)
    npt.assert_(signature.varargs is None)
    npt.assert_(signature.keywords is None)
    npt.assert_(signature.defaults == defaults)

    shape_argnames = signature.args[1:-len(defaults)]  # self, a, b, loc=0, scale=1
    if distfn.shapes:
        shapes_ = distfn.shapes.replace(',', ' ').split()
    else:
        shapes_ = ''
    npt.assert_(len(shapes_) == distfn.numargs)
    npt.assert_(len(shapes_) == len(shape_argnames))

    # check calling w/ named arguments
    shape_args = list(shape_args)

    vals = [meth(x, *shape_args) for meth in meths]
    npt.assert_(np.all(np.isfinite(vals)))

    names, a, k = shape_argnames[:], shape_args[:], {}
    while names:
        k.update({names.pop(): a.pop()})
        v = [meth(x, *a, **k) for meth in meths]
        npt.assert_array_equal(vals, v)
        if 'n' not in k.keys():
            # `n` is first parameter of moment(), so can't be used as named arg
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", UserWarning)
                npt.assert_equal(distfn.moment(1, *a, **k),
                                 distfn.moment(1, *shape_args))

    # unknown arguments should not go through:
    k.update({'kaboom': 42})
    npt.assert_raises(TypeError, distfn.cdf, x, **k) 
Example 37
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_mixins.py    MIT License 5 votes vote down vote up
def test_opt_out(self):

        class OptOut(object):
            """Object that opts out of __array_ufunc__."""
            __array_ufunc__ = None

            def __add__(self, other):
                return self

            def __radd__(self, other):
                return self

        array_like = ArrayLike(1)
        opt_out = OptOut()

        # supported operations
        assert_(array_like + opt_out is opt_out)
        assert_(opt_out + array_like is opt_out)

        # not supported
        with assert_raises(TypeError):
            # don't use the Python default, array_like = array_like + opt_out
            array_like += opt_out
        with assert_raises(TypeError):
            array_like - opt_out
        with assert_raises(TypeError):
            opt_out - array_like 
Example 38
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_mixins.py    MIT License 5 votes vote down vote up
def test_object(self):
        x = ArrayLike(0)
        obj = object()
        with assert_raises(TypeError):
            x + obj
        with assert_raises(TypeError):
            obj + x
        with assert_raises(TypeError):
            x += obj 
Example 39
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_return_real.py    MIT License 5 votes vote down vote up
def check_function(self, t):
        if t.__doc__.split()[0] 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(long(234)) - 234.0) <= 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 t.__doc__.split()[0] 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(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        try:
            r = t(10 ** 400)
            assert_(repr(r) in ['inf', 'Infinity'], repr(r))
        except OverflowError:
            pass 
Example 40
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_return_integer.py    MIT License 5 votes vote down vote up
def check_function(self, t):
        assert_(t(123) == 123, repr(t(123)))
        assert_(t(123.6) == 123)
        assert_(t(long(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_raises(ValueError, t, array([123],'S3'))
        assert_raises(ValueError, t, 'abc')

        assert_raises(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        if t.__doc__.split()[0] in ['t8', 's8']:
            assert_raises(OverflowError, t, 100000000000000000000000)
            assert_raises(OverflowError, t, 10000000011111111111111.23) 
Example 41
Project: MARRtino-2.0   Author: DaniAffCH   File: test_recfunctions.py    GNU General Public License v3.0 5 votes vote down vote up
def test_autoconversion(self):
        # Tests autoconversion
        adtype = [('A', int), ('B', bool), ('C', float)]
        a = ma.array([(1, 2, 3)], mask=[(0, 1, 0)], dtype=adtype)
        bdtype = [('A', int), ('B', float), ('C', float)]
        b = ma.array([(4, 5, 6)], dtype=bdtype)
        control = ma.array([(1, 2, 3), (4, 5, 6)], mask=[(0, 1, 0), (0, 0, 0)],
                           dtype=bdtype)
        test = stack_arrays((a, b), autoconvert=True)
        assert_equal(test, control)
        assert_equal(test.mask, control.mask)
        with assert_raises(TypeError):
            stack_arrays((a, b), autoconvert=False) 
Example 42
Project: MARRtino-2.0   Author: DaniAffCH   File: test_recfunctions.py    GNU General Public License v3.0 5 votes vote down vote up
def test_duplicate_keys(self):
        a = np.zeros(3, dtype=[('a', 'i4'), ('b', 'f4'), ('c', 'u1')])
        b = np.ones(3, dtype=[('c', 'u1'), ('b', 'f4'), ('a', 'i4')])
        assert_raises(ValueError, join_by, ['a', 'b', 'b'], a, b) 
Example 43
Project: MARRtino-2.0   Author: DaniAffCH   File: test_recfunctions.py    GNU General Public License v3.0 5 votes vote down vote up
def test_no_postfix(self):
        assert_raises(ValueError, join_by, 'a', self.a, self.b,
                      r1postfix='', r2postfix='') 
Example 44
Project: MARRtino-2.0   Author: DaniAffCH   File: test_mixins.py    GNU General Public License v3.0 5 votes vote down vote up
def test_opt_out(self):

        class OptOut(object):
            """Object that opts out of __array_ufunc__."""
            __array_ufunc__ = None

            def __add__(self, other):
                return self

            def __radd__(self, other):
                return self

        array_like = ArrayLike(1)
        opt_out = OptOut()

        # supported operations
        assert_(array_like + opt_out is opt_out)
        assert_(opt_out + array_like is opt_out)

        # not supported
        with assert_raises(TypeError):
            # don't use the Python default, array_like = array_like + opt_out
            array_like += opt_out
        with assert_raises(TypeError):
            array_like - opt_out
        with assert_raises(TypeError):
            opt_out - array_like 
Example 45
Project: MARRtino-2.0   Author: DaniAffCH   File: test_mixins.py    GNU General Public License v3.0 5 votes vote down vote up
def test_object(self):
        x = ArrayLike(0)
        obj = object()
        with assert_raises(TypeError):
            x + obj
        with assert_raises(TypeError):
            obj + x
        with assert_raises(TypeError):
            x += obj 
Example 46
Project: MARRtino-2.0   Author: DaniAffCH   File: test_return_real.py    GNU General Public License v3.0 5 votes vote down vote up
def check_function(self, t):
        if t.__doc__.split()[0] 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(long(234)) - 234.0) <= 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 t.__doc__.split()[0] 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(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        try:
            r = t(10 ** 400)
            assert_(repr(r) in ['inf', 'Infinity'], repr(r))
        except OverflowError:
            pass 
Example 47
Project: MARRtino-2.0   Author: DaniAffCH   File: test_return_integer.py    GNU General Public License v3.0 5 votes vote down vote up
def check_function(self, t):
        assert_(t(123) == 123, repr(t(123)))
        assert_(t(123.6) == 123)
        assert_(t(long(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_raises(ValueError, t, array([123],'S3'))
        assert_raises(ValueError, t, 'abc')

        assert_raises(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        if t.__doc__.split()[0] in ['t8', 's8']:
            assert_raises(OverflowError, t, 100000000000000000000000)
            assert_raises(OverflowError, t, 10000000011111111111111.23) 
Example 48
Project: MARRtino-2.0   Author: DaniAffCH   File: test_errstate.py    GNU General Public License v3.0 5 votes vote down vote up
def test_invalid(self):
        with np.errstate(all='raise', under='ignore'):
            a = -np.arange(3)
            # This should work
            with np.errstate(invalid='ignore'):
                np.sqrt(a)
            # While this should fail!
            with assert_raises(FloatingPointError):
                np.sqrt(a) 
Example 49
Project: MARRtino-2.0   Author: DaniAffCH   File: test_errstate.py    GNU General Public License v3.0 5 votes vote down vote up
def test_divide(self):
        with np.errstate(all='raise', under='ignore'):
            a = -np.arange(3)
            # This should work
            with np.errstate(divide='ignore'):
                a // 0
            # While this should fail!
            with assert_raises(FloatingPointError):
                a // 0 
Example 50
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_return_real.py    MIT License 5 votes vote down vote up
def check_function(self, t):
        if t.__doc__.split()[0] 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(long(234)) - 234.0) <= 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 t.__doc__.split()[0] 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(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        try:
            r = t(10 ** 400)
            assert_(repr(r) in ['inf', 'Infinity'], repr(r))
        except OverflowError:
            pass