Python numpy.testing.assert_() Examples

The following are code examples for showing how to use numpy.testing.assert_(). 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: LaserTOF   Author: kyleuckert   File: test_return_character.py    MIT License 6 votes vote down vote up
def check_function(self, t):
        tname = t.__doc__.split()[0]
        if tname in ['t0', 't1', 's0', 's1']:
            assert_(t(23) == asbytes('2'))
            r = t('ab')
            assert_(r == asbytes('a'), repr(r))
            r = t(array('ab'))
            assert_(r == asbytes('a'), repr(r))
            r = t(array(77, 'u1'))
            assert_(r == asbytes('M'), repr(r))
            #assert_(_raises(ValueError, t, array([77,87])))
            #assert_(_raises(ValueError, t, array(77)))
        elif tname in ['ts', 'ss']:
            assert_(t(23) == asbytes('23        '), repr(t(23)))
            assert_(t('123456789abcdef') == asbytes('123456789a'))
        elif tname in ['t5', 's5']:
            assert_(t(23) == asbytes('23   '), repr(t(23)))
            assert_(t('ab') == asbytes('ab   '), repr(t('ab')))
            assert_(t('123456789abcdef') == asbytes('12345'))
        else:
            raise NotImplementedError 
Example 2
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 6 votes vote down vote up
def check_moment(distfn, arg, m, v, msg):
    m1 = distfn.moment(1, *arg)
    m2 = distfn.moment(2, *arg)
    if not np.isinf(m):
        npt.assert_almost_equal(m1, m, decimal=10, err_msg=msg +
                            ' - 1st moment')
    else:                     # or np.isnan(m1),
        npt.assert_(np.isinf(m1),
               msg + ' - 1st moment -infinite, m1=%s' % str(m1))

    if not np.isinf(v):
        npt.assert_almost_equal(m2 - m1 * m1, v, decimal=10, err_msg=msg +
                            ' - 2ndt moment')
    else:                     # or np.isnan(m2),
        npt.assert_(np.isinf(m2),
               msg + ' - 2nd moment -infinite, m2=%s' % str(m2)) 
Example 3
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 6 votes vote down vote up
def check_edge_support(distfn, args):
    # Make sure that x=self.a and self.b are handled correctly.
    x = [distfn.a, distfn.b]
    if isinstance(distfn, stats.rv_discrete):
        x = [distfn.a - 1, distfn.b]

    npt.assert_equal(distfn.cdf(x, *args), [0.0, 1.0])
    npt.assert_equal(distfn.sf(x, *args), [1.0, 0.0])

    if distfn.name not in ('skellam', 'dlaplace'):
        # with a = -inf, log(0) generates warnings
        npt.assert_equal(distfn.logcdf(x, *args), [-np.inf, 0.0])
        npt.assert_equal(distfn.logsf(x, *args), [0.0, -np.inf])

    npt.assert_equal(distfn.ppf([0.0, 1.0], *args), x)
    npt.assert_equal(distfn.isf([0.0, 1.0], *args), x[::-1])

    # out-of-bounds for isf & ppf
    npt.assert_(np.isnan(distfn.isf([-1, 2], *args)).all())
    npt.assert_(np.isnan(distfn.ppf([-1, 2], *args)).all()) 
Example 4
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_return_character.py    MIT License 6 votes vote down vote up
def check_function(self, t):
        tname = t.__doc__.split()[0]
        if tname in ['t0', 't1', 's0', 's1']:
            assert_(t(23) == b'2')
            r = t('ab')
            assert_(r == b'a', repr(r))
            r = t(array('ab'))
            assert_(r == b'a', repr(r))
            r = t(array(77, 'u1'))
            assert_(r == b'M', repr(r))
            #assert_(_raises(ValueError, t, array([77,87])))
            #assert_(_raises(ValueError, t, array(77)))
        elif tname in ['ts', 'ss']:
            assert_(t(23) == b'23        ', repr(t(23)))
            assert_(t('123456789abcdef') == b'123456789a')
        elif tname in ['t5', 's5']:
            assert_(t(23) == b'23   ', repr(t(23)))
            assert_(t('ab') == b'ab   ', repr(t('ab')))
            assert_(t('123456789abcdef') == b'12345')
        else:
            raise NotImplementedError 
Example 5
Project: recruit   Author: Frank-qlu   File: test_return_character.py    Apache License 2.0 6 votes vote down vote up
def check_function(self, t):
        tname = t.__doc__.split()[0]
        if tname in ['t0', 't1', 's0', 's1']:
            assert_(t(23) == b'2')
            r = t('ab')
            assert_(r == b'a', repr(r))
            r = t(array('ab'))
            assert_(r == b'a', repr(r))
            r = t(array(77, 'u1'))
            assert_(r == b'M', repr(r))
            #assert_(_raises(ValueError, t, array([77,87])))
            #assert_(_raises(ValueError, t, array(77)))
        elif tname in ['ts', 'ss']:
            assert_(t(23) == b'23        ', repr(t(23)))
            assert_(t('123456789abcdef') == b'123456789a')
        elif tname in ['t5', 's5']:
            assert_(t(23) == b'23   ', repr(t(23)))
            assert_(t('ab') == b'ab   ', repr(t('ab')))
            assert_(t('123456789abcdef') == b'12345')
        else:
            raise NotImplementedError 
Example 6
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 6 votes vote down vote up
def test_posix_home_inaccessible(self):
        # what happens when home catalog dir is innaccessible
        tmpdir = tempfile.mkdtemp()
        try:
            d_dir = catalog.default_dir_posix(tmpdir)

            try:
                os.chmod(d_dir, 0o000)
            except OSError:
                raise KnownFailureTest("Can't change permissions of default_dir.")

            new_ddir = catalog.default_dir_posix(tmpdir)
            assert_(not os.path.samefile(new_ddir, d_dir))
            new_ddir2 = catalog.default_dir_posix(tmpdir)
            assert_(os.path.samefile(new_ddir, new_ddir2))
        finally:
            os.chmod(d_dir, 0o700)
            remove_tree(tmpdir) 
Example 7
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 6 votes vote down vote up
def test_unique_module_name(self):
        # Check that we can create a file in the writable directory
        q = catalog.catalog()
        file = q.unique_module_name('bob')
        cfile1 = file+'.cpp'
        assert_(not os.path.exists(cfile1))
        # Make sure it is writable
        try:
            f = open(cfile1,'w')
            f.write('bob')
        finally:
            f.close()
        # try again with same code fragment -- should get unique name
        file = q.unique_module_name('bob')
        cfile2 = file+'.cpp'
        assert_(not os.path.exists(cfile2+'.cpp'))
        os.remove(cfile1) 
Example 8
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: common_tests.py    GNU General Public License v3.0 6 votes vote down vote up
def check_moment(distfn, arg, m, v, msg):
    m1 = distfn.moment(1, *arg)
    m2 = distfn.moment(2, *arg)
    if not np.isinf(m):
        npt.assert_almost_equal(m1, m, decimal=10, err_msg=msg +
                            ' - 1st moment')
    else:                     # or np.isnan(m1),
        npt.assert_(np.isinf(m1),
               msg + ' - 1st moment -infinite, m1=%s' % str(m1))

    if not np.isinf(v):
        npt.assert_almost_equal(m2 - m1 * m1, v, decimal=10, err_msg=msg +
                            ' - 2ndt moment')
    else:                     # or np.isnan(m2),
        npt.assert_(np.isinf(m2),
               msg + ' - 2nd moment -infinite, m2=%s' % str(m2)) 
Example 9
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_return_character.py    MIT License 6 votes vote down vote up
def check_function(self, t):
        tname = t.__doc__.split()[0]
        if tname in ['t0', 't1', 's0', 's1']:
            assert_(t(23) == b'2')
            r = t('ab')
            assert_(r == b'a', repr(r))
            r = t(array('ab'))
            assert_(r == b'a', repr(r))
            r = t(array(77, 'u1'))
            assert_(r == b'M', repr(r))
            #assert_(_raises(ValueError, t, array([77,87])))
            #assert_(_raises(ValueError, t, array(77)))
        elif tname in ['ts', 'ss']:
            assert_(t(23) == b'23        ', repr(t(23)))
            assert_(t('123456789abcdef') == b'123456789a')
        elif tname in ['t5', 's5']:
            assert_(t(23) == b'23   ', repr(t(23)))
            assert_(t('ab') == b'ab   ', repr(t('ab')))
            assert_(t('123456789abcdef') == b'12345')
        else:
            raise NotImplementedError 
Example 10
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 5 votes vote down vote up
def check_skew_expect(distfn, arg, m, v, s, msg):
    if np.isfinite(s):
        m3e = distfn.expect(lambda x: np.power(x-m, 3), arg)
        npt.assert_almost_equal(m3e, s * np.power(v, 1.5),
                decimal=5, err_msg=msg + ' - skew')
    else:
        npt.assert_(np.isnan(s)) 
Example 11
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 5 votes vote down vote up
def check_kurt_expect(distfn, arg, m, v, k, msg):
    if np.isfinite(k):
        m4e = distfn.expect(lambda x: np.power(x-m, 4), arg)
        npt.assert_allclose(m4e, (k + 3.) * np.power(v, 2), atol=1e-5, rtol=1e-5,
                err_msg=msg + ' - kurtosis')
    else:
        npt.assert_(np.isnan(k)) 
Example 12
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 13
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 5 votes vote down vote up
def check_meth_dtype(distfn, arg, meths):
    q0 = [0.25, 0.5, 0.75]
    x0 = distfn.ppf(q0, *arg)
    x_cast = [x0.astype(tp) for tp in
                        (np.int_, np.float16, np.float32, np.float64)]

    for x in x_cast:
        # casting may have clipped the values, exclude those
        distfn._argcheck(*arg)
        x = x[(distfn.a < x) & (x < distfn.b)]
        for meth in meths:
            val = meth(x, *arg)
            npt.assert_(val.dtype == np.float_) 
Example 14
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 5 votes vote down vote up
def check_ppf_dtype(distfn, arg):
    q0 = np.asarray([0.25, 0.5, 0.75])
    q_cast = [q0.astype(tp) for tp in (np.float16, np.float32, np.float64)]
    for q in q_cast:
        for meth in [distfn.ppf, distfn.isf]:
            val = meth(q, *arg)
            npt.assert_(val.dtype == np.float_) 
Example 15
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 16
Project: LaserTOF   Author: kyleuckert   File: test_continuous_basic.py    MIT License 5 votes vote down vote up
def check_sample_var(sv, n, popvar):
    # two-sided chisquare test for sample variance equal to
    # hypothesized variance
    df = n-1
    chi2 = (n-1)*popvar/float(popvar)
    pval = stats.distributions.chi2.sf(chi2, df) * 2
    npt.assert_(pval > 0.01, 'var fail, t, pval = %f, %f, v, sv=%f, %f' %
                (chi2, pval, popvar, sv)) 
Example 17
Project: LaserTOF   Author: kyleuckert   File: test_continuous_basic.py    MIT License 5 votes vote down vote up
def check_distribution_rvs(dist, args, alpha, rvs):
    # test from scipy.stats.tests
    # this version reuses existing random variables
    D, pval = stats.kstest(rvs, dist, args=args, N=1000)
    if (pval < alpha):
        D, pval = stats.kstest(dist, '', args=args, N=1000)
        npt.assert_(pval > alpha, "D = " + str(D) + "; pval = " + str(pval) +
                    "; alpha = " + str(alpha) + "\nargs = " + str(args)) 
Example 18
Project: LaserTOF   Author: kyleuckert   File: test_continuous_basic.py    MIT License 5 votes vote down vote up
def check_ppf_private(distfn, arg, msg):
    # fails by design for truncnorm self.nb not defined
    ppfs = distfn._ppf(np.array([0.1, 0.5, 0.9]), *arg)
    npt.assert_(not np.any(np.isnan(ppfs)), msg + 'ppf private is nan') 
Example 19
Project: LaserTOF   Author: kyleuckert   File: test_discrete_basic.py    MIT License 5 votes vote down vote up
def check_oth(distfn, arg, supp, msg):
    # checking other methods of distfn
    npt.assert_allclose(distfn.sf(supp, *arg), 1. - distfn.cdf(supp, *arg),
                        atol=1e-10, rtol=1e-10)

    q = np.linspace(0.01, 0.99, 20)
    npt.assert_allclose(distfn.isf(q, *arg), distfn.ppf(1. - q, *arg),
                        atol=1e-10, rtol=1e-10)

    median_sf = distfn.isf(0.5, *arg)
    npt.assert_(distfn.sf(median_sf - 1, *arg) > 0.5)
    npt.assert_(distfn.cdf(median_sf + 1, *arg) > 0.5) 
Example 20
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_subclassing.py    MIT License 5 votes vote down vote up
def assert_startswith(a, b):
    # produces a better error message than assert_(a.startswith(b))
    assert_equal(a[:len(b)], b) 
Example 21
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_subclassing.py    MIT License 5 votes vote down vote up
def test_data_subclassing(self):
        # Tests whether the subclass is kept.
        x = np.arange(5)
        m = [0, 0, 1, 0, 0]
        xsub = SubArray(x)
        xmsub = masked_array(xsub, mask=m)
        assert_(isinstance(xmsub, MaskedArray))
        assert_equal(xmsub._data, xsub)
        assert_(isinstance(xmsub._data, SubArray)) 
Example 22
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_subclassing.py    MIT License 5 votes vote down vote up
def test_maskedarray_subclassing(self):
        # Tests subclassing MaskedArray
        (x, mx) = self.data
        assert_(isinstance(mx._data, subarray)) 
Example 23
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_subclassing.py    MIT License 5 votes vote down vote up
def test_masked_binary_operations(self):
        # Tests masked_binary_operation
        (x, mx) = self.data
        # Result should be a msubarray
        assert_(isinstance(add(mx, mx), msubarray))
        assert_(isinstance(add(mx, x), msubarray))
        # Result should work
        assert_equal(add(mx, x), mx+x)
        assert_(isinstance(add(mx, mx)._data, subarray))
        assert_(isinstance(add.outer(mx, mx), msubarray))
        assert_(isinstance(hypot(mx, mx), msubarray))
        assert_(isinstance(hypot(mx, x), msubarray)) 
Example 24
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_subclassing.py    MIT License 5 votes vote down vote up
def test_masked_binary_operations2(self):
        # Tests domained_masked_binary_operation
        (x, mx) = self.data
        xmx = masked_array(mx.data.__array__(), mask=mx.mask)
        assert_(isinstance(divide(mx, mx), msubarray))
        assert_(isinstance(divide(mx, x), msubarray))
        assert_equal(divide(mx, mx), divide(xmx, xmx)) 
Example 25
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_subclassing.py    MIT License 5 votes vote down vote up
def test_attributepropagation(self):
        x = array(arange(5), mask=[0]+[1]*4)
        my = masked_array(subarray(x))
        ym = msubarray(x)
        #
        z = (my+1)
        assert_(isinstance(z, MaskedArray))
        assert_(not isinstance(z, MSubArray))
        assert_(isinstance(z._data, SubArray))
        assert_equal(z._data.info, {})
        #
        z = (ym+1)
        assert_(isinstance(z, MaskedArray))
        assert_(isinstance(z, MSubArray))
        assert_(isinstance(z._data, SubArray))
        assert_(z._data.info['added'] > 0)
        # Test that inplace methods from data get used (gh-4617)
        ym += 1
        assert_(isinstance(ym, MaskedArray))
        assert_(isinstance(ym, MSubArray))
        assert_(isinstance(ym._data, SubArray))
        assert_(ym._data.info['iadded'] > 0)
        #
        ym._set_mask([1, 0, 0, 0, 1])
        assert_equal(ym._mask, [1, 0, 0, 0, 1])
        ym._series._set_mask([0, 0, 0, 0, 1])
        assert_equal(ym._mask, [0, 0, 0, 0, 1])
        #
        xsub = subarray(x, info={'name':'x'})
        mxsub = masked_array(xsub)
        assert_(hasattr(mxsub, 'info'))
        assert_equal(mxsub.info, xsub.info) 
Example 26
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_subclassing.py    MIT License 5 votes vote down vote up
def test_subclasspreservation(self):
        # Checks that masked_array(...,subok=True) preserves the class.
        x = np.arange(5)
        m = [0, 0, 1, 0, 0]
        xinfo = [(i, j) for (i, j) in zip(x, m)]
        xsub = MSubArray(x, mask=m, info={'xsub':xinfo})
        #
        mxsub = masked_array(xsub, subok=False)
        assert_(not isinstance(mxsub, MSubArray))
        assert_(isinstance(mxsub, MaskedArray))
        assert_equal(mxsub._mask, m)
        #
        mxsub = asarray(xsub)
        assert_(not isinstance(mxsub, MSubArray))
        assert_(isinstance(mxsub, MaskedArray))
        assert_equal(mxsub._mask, m)
        #
        mxsub = masked_array(xsub, subok=True)
        assert_(isinstance(mxsub, MSubArray))
        assert_equal(mxsub.info, xsub.info)
        assert_equal(mxsub._mask, xsub._mask)
        #
        mxsub = asanyarray(xsub)
        assert_(isinstance(mxsub, MSubArray))
        assert_equal(mxsub.info, xsub.info)
        assert_equal(mxsub._mask, m) 
Example 27
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_subclassing.py    MIT License 5 votes vote down vote up
def test_subclass_items(self):
        """test that getter and setter go via baseclass"""
        x = np.arange(5)
        xcsub = ComplicatedSubArray(x)
        mxcsub = masked_array(xcsub, mask=[True, False, True, False, False])
        # getter should  return a ComplicatedSubArray, even for single item
        # first check we wrote ComplicatedSubArray correctly
        assert_(isinstance(xcsub[1], ComplicatedSubArray))
        assert_(isinstance(xcsub[1,...], ComplicatedSubArray))
        assert_(isinstance(xcsub[1:4], ComplicatedSubArray))

        # now that it propagates inside the MaskedArray
        assert_(isinstance(mxcsub[1], ComplicatedSubArray))
        assert_(isinstance(mxcsub[1,...].data, ComplicatedSubArray))
        assert_(mxcsub[0] is masked)
        assert_(isinstance(mxcsub[0,...].data, ComplicatedSubArray))
        assert_(isinstance(mxcsub[1:4].data, ComplicatedSubArray))

        # also for flattened version (which goes via MaskedIterator)
        assert_(isinstance(mxcsub.flat[1].data, ComplicatedSubArray))
        assert_(mxcsub.flat[0] is masked)
        assert_(isinstance(mxcsub.flat[1:4].base, ComplicatedSubArray))

        # setter should only work with ComplicatedSubArray input
        # first check we wrote ComplicatedSubArray correctly
        assert_raises(ValueError, xcsub.__setitem__, 1, x[4])
        # now that it propagates inside the MaskedArray
        assert_raises(ValueError, mxcsub.__setitem__, 1, x[4])
        assert_raises(ValueError, mxcsub.__setitem__, slice(1, 4), x[1:4])
        mxcsub[1] = xcsub[4]
        mxcsub[1:4] = xcsub[1:4]
        # also for flattened version (which goes via MaskedIterator)
        assert_raises(ValueError, mxcsub.flat.__setitem__, 1, x[4])
        assert_raises(ValueError, mxcsub.flat.__setitem__, slice(1, 4), x[1:4])
        mxcsub.flat[1] = xcsub[4]
        mxcsub.flat[1:4] = xcsub[1:4] 
Example 28
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_subclassing.py    MIT License 5 votes vote down vote up
def test_pure_subclass_info_preservation(self):
        # Test that ufuncs and methods conserve extra information consistently;
        # see gh-7122.
        arr1 = SubMaskedArray('test', data=[1,2,3,4,5,6])
        arr2 = SubMaskedArray(data=[0,1,2,3,4,5])
        diff1 = np.subtract(arr1, arr2)
        assert_('info' in diff1._optinfo)
        assert_(diff1._optinfo['info'] == 'test')
        diff2 = arr1 - arr2
        assert_('info' in diff2._optinfo)
        assert_(diff2._optinfo['info'] == 'test') 
Example 29
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_matrix_io.py    MIT License 5 votes vote down vote up
def _check_save_and_load(dense_matrix):
    for matrix_class in [csc_matrix, csr_matrix, bsr_matrix, dia_matrix, coo_matrix]:
        matrix = matrix_class(dense_matrix)
        loaded_matrix = _save_and_load(matrix)
        assert_(type(loaded_matrix) is matrix_class)
        assert_(loaded_matrix.shape == dense_matrix.shape)
        assert_(loaded_matrix.dtype == dense_matrix.dtype)
        assert_equal(loaded_matrix.toarray(), dense_matrix) 
Example 30
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_matrix_io.py    MIT License 5 votes vote down vote up
def test_malicious_load():
    class Executor(object):
        def __reduce__(self):
            return (assert_, (False, 'unexpected code execution'))

    fd, tmpfile = tempfile.mkstemp(suffix='.npz')
    os.close(fd)
    try:
        np.savez(tmpfile, format=Executor())

        # Should raise a ValueError, not execute code
        assert_raises(ValueError, load_npz, tmpfile)
    finally:
        os.remove(tmpfile) 
Example 31
Project: recruit   Author: Frank-qlu   File: test_subclassing.py    Apache License 2.0 5 votes vote down vote up
def assert_startswith(a, b):
    # produces a better error message than assert_(a.startswith(b))
    assert_equal(a[:len(b)], b) 
Example 32
Project: recruit   Author: Frank-qlu   File: test_subclassing.py    Apache License 2.0 5 votes vote down vote up
def test_data_subclassing(self):
        # Tests whether the subclass is kept.
        x = np.arange(5)
        m = [0, 0, 1, 0, 0]
        xsub = SubArray(x)
        xmsub = masked_array(xsub, mask=m)
        assert_(isinstance(xmsub, MaskedArray))
        assert_equal(xmsub._data, xsub)
        assert_(isinstance(xmsub._data, SubArray)) 
Example 33
Project: recruit   Author: Frank-qlu   File: test_subclassing.py    Apache License 2.0 5 votes vote down vote up
def test_maskedarray_subclassing(self):
        # Tests subclassing MaskedArray
        (x, mx) = self.data
        assert_(isinstance(mx._data, subarray)) 
Example 34
Project: recruit   Author: Frank-qlu   File: test_subclassing.py    Apache License 2.0 5 votes vote down vote up
def test_masked_binary_operations(self):
        # Tests masked_binary_operation
        (x, mx) = self.data
        # Result should be a msubarray
        assert_(isinstance(add(mx, mx), msubarray))
        assert_(isinstance(add(mx, x), msubarray))
        # Result should work
        assert_equal(add(mx, x), mx+x)
        assert_(isinstance(add(mx, mx)._data, subarray))
        assert_(isinstance(add.outer(mx, mx), msubarray))
        assert_(isinstance(hypot(mx, mx), msubarray))
        assert_(isinstance(hypot(mx, x), msubarray)) 
Example 35
Project: recruit   Author: Frank-qlu   File: test_subclassing.py    Apache License 2.0 5 votes vote down vote up
def test_masked_binary_operations2(self):
        # Tests domained_masked_binary_operation
        (x, mx) = self.data
        xmx = masked_array(mx.data.__array__(), mask=mx.mask)
        assert_(isinstance(divide(mx, mx), msubarray))
        assert_(isinstance(divide(mx, x), msubarray))
        assert_equal(divide(mx, mx), divide(xmx, xmx)) 
Example 36
Project: recruit   Author: Frank-qlu   File: test_subclassing.py    Apache License 2.0 5 votes vote down vote up
def test_attributepropagation(self):
        x = array(arange(5), mask=[0]+[1]*4)
        my = masked_array(subarray(x))
        ym = msubarray(x)
        #
        z = (my+1)
        assert_(isinstance(z, MaskedArray))
        assert_(not isinstance(z, MSubArray))
        assert_(isinstance(z._data, SubArray))
        assert_equal(z._data.info, {})
        #
        z = (ym+1)
        assert_(isinstance(z, MaskedArray))
        assert_(isinstance(z, MSubArray))
        assert_(isinstance(z._data, SubArray))
        assert_(z._data.info['added'] > 0)
        # Test that inplace methods from data get used (gh-4617)
        ym += 1
        assert_(isinstance(ym, MaskedArray))
        assert_(isinstance(ym, MSubArray))
        assert_(isinstance(ym._data, SubArray))
        assert_(ym._data.info['iadded'] > 0)
        #
        ym._set_mask([1, 0, 0, 0, 1])
        assert_equal(ym._mask, [1, 0, 0, 0, 1])
        ym._series._set_mask([0, 0, 0, 0, 1])
        assert_equal(ym._mask, [0, 0, 0, 0, 1])
        #
        xsub = subarray(x, info={'name':'x'})
        mxsub = masked_array(xsub)
        assert_(hasattr(mxsub, 'info'))
        assert_equal(mxsub.info, xsub.info) 
Example 37
Project: recruit   Author: Frank-qlu   File: test_subclassing.py    Apache License 2.0 5 votes vote down vote up
def test_subclasspreservation(self):
        # Checks that masked_array(...,subok=True) preserves the class.
        x = np.arange(5)
        m = [0, 0, 1, 0, 0]
        xinfo = [(i, j) for (i, j) in zip(x, m)]
        xsub = MSubArray(x, mask=m, info={'xsub':xinfo})
        #
        mxsub = masked_array(xsub, subok=False)
        assert_(not isinstance(mxsub, MSubArray))
        assert_(isinstance(mxsub, MaskedArray))
        assert_equal(mxsub._mask, m)
        #
        mxsub = asarray(xsub)
        assert_(not isinstance(mxsub, MSubArray))
        assert_(isinstance(mxsub, MaskedArray))
        assert_equal(mxsub._mask, m)
        #
        mxsub = masked_array(xsub, subok=True)
        assert_(isinstance(mxsub, MSubArray))
        assert_equal(mxsub.info, xsub.info)
        assert_equal(mxsub._mask, xsub._mask)
        #
        mxsub = asanyarray(xsub)
        assert_(isinstance(mxsub, MSubArray))
        assert_equal(mxsub.info, xsub.info)
        assert_equal(mxsub._mask, m) 
Example 38
Project: recruit   Author: Frank-qlu   File: test_subclassing.py    Apache License 2.0 5 votes vote down vote up
def test_subclass_items(self):
        """test that getter and setter go via baseclass"""
        x = np.arange(5)
        xcsub = ComplicatedSubArray(x)
        mxcsub = masked_array(xcsub, mask=[True, False, True, False, False])
        # getter should  return a ComplicatedSubArray, even for single item
        # first check we wrote ComplicatedSubArray correctly
        assert_(isinstance(xcsub[1], ComplicatedSubArray))
        assert_(isinstance(xcsub[1,...], ComplicatedSubArray))
        assert_(isinstance(xcsub[1:4], ComplicatedSubArray))

        # now that it propagates inside the MaskedArray
        assert_(isinstance(mxcsub[1], ComplicatedSubArray))
        assert_(isinstance(mxcsub[1,...].data, ComplicatedSubArray))
        assert_(mxcsub[0] is masked)
        assert_(isinstance(mxcsub[0,...].data, ComplicatedSubArray))
        assert_(isinstance(mxcsub[1:4].data, ComplicatedSubArray))

        # also for flattened version (which goes via MaskedIterator)
        assert_(isinstance(mxcsub.flat[1].data, ComplicatedSubArray))
        assert_(mxcsub.flat[0] is masked)
        assert_(isinstance(mxcsub.flat[1:4].base, ComplicatedSubArray))

        # setter should only work with ComplicatedSubArray input
        # first check we wrote ComplicatedSubArray correctly
        assert_raises(ValueError, xcsub.__setitem__, 1, x[4])
        # now that it propagates inside the MaskedArray
        assert_raises(ValueError, mxcsub.__setitem__, 1, x[4])
        assert_raises(ValueError, mxcsub.__setitem__, slice(1, 4), x[1:4])
        mxcsub[1] = xcsub[4]
        mxcsub[1:4] = xcsub[1:4]
        # also for flattened version (which goes via MaskedIterator)
        assert_raises(ValueError, mxcsub.flat.__setitem__, 1, x[4])
        assert_raises(ValueError, mxcsub.flat.__setitem__, slice(1, 4), x[1:4])
        mxcsub.flat[1] = xcsub[4]
        mxcsub.flat[1:4] = xcsub[1:4] 
Example 39
Project: recruit   Author: Frank-qlu   File: test_subclassing.py    Apache License 2.0 5 votes vote down vote up
def test_pure_subclass_info_preservation(self):
        # Test that ufuncs and methods conserve extra information consistently;
        # see gh-7122.
        arr1 = SubMaskedArray('test', data=[1,2,3,4,5,6])
        arr2 = SubMaskedArray(data=[0,1,2,3,4,5])
        diff1 = np.subtract(arr1, arr2)
        assert_('info' in diff1._optinfo)
        assert_(diff1._optinfo['info'] == 'test')
        diff2 = arr1 - arr2
        assert_('info' in diff2._optinfo)
        assert_(diff2._optinfo['info'] == 'test') 
Example 40
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 5 votes vote down vote up
def dirs_are_valid(self, wrong_dir, tmpdir):
        # Test if new dir is created and is consistent.
        new_im_dir = catalog.intermediate_dir(tmpdir)
        assert_(not samefile(new_im_dir, wrong_dir))
        new_im_dir2 = catalog.intermediate_dir(tmpdir)
        assert_(samefile(new_im_dir, new_im_dir2)) 
Example 41
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 5 votes vote down vote up
def test_ownership(self):
        # Test if intermediate dir is owned by correct user.
        im_dir = catalog.intermediate_dir()
        im_dir_stat = os.stat(im_dir)
        proc_uid = os.getuid()
        assert_(proc_uid == im_dir_stat.st_uid)
        r_im_dir_stat = os.stat(os.path.dirname(im_dir))
        assert_(proc_uid == r_im_dir_stat.st_uid) 
Example 42
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 5 votes vote down vote up
def test_permissions(self):
        # im dir should have permissions 0700
        im_dir = catalog.intermediate_dir()
        im_dir_stat = os.stat(im_dir)
        assert_(stat.S_IMODE(im_dir_stat.st_mode) == 0o0700)
        r_im_dir_stat = os.stat(os.path.dirname(im_dir))
        assert_(stat.S_IMODE(r_im_dir_stat.st_mode) == 0o0700) 
Example 43
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 5 votes vote down vote up
def test_symlink(self):
        # im dir shouldn't be a symlink
        r_im_dir = os.path.dirname(catalog.intermediate_dir())
        assert_(os.path.islink(r_im_dir) is False) 
Example 44
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 5 votes vote down vote up
def test_win(self):
        # test if default_dir for Windows platform is accessible
        #
        # since default_dir_win() does not have any Windows specific code,
        # let's test it everywhere
        d = catalog.default_dir_win()
        assert_(catalog.is_writable(d)) 
Example 45
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 5 votes vote down vote up
def test_posix_dirs_inaccessible(self):
        # test if new dir is created if both implicit dirs are not valid
        tmpdir = tempfile.mkdtemp()
        try:
            d_dir = catalog.default_dir_posix(tmpdir)

            try:
                os.chmod(d_dir, 0o000)
            except OSError:
                raise KnownFailureTest("Can't change permissions of default_dir.")

            d_dir2 = catalog.default_dir_posix(tmpdir)

            try:
                os.chmod(d_dir2, 0o000)
            except OSError:
                raise KnownFailureTest("Can't change permissions of default_dir.")

            new_ddir = catalog.default_dir_posix(tmpdir)
            assert_(not (os.path.samefile(new_ddir, d_dir) or os.path.samefile(new_ddir, d_dir2)))
            new_ddir2 = catalog.default_dir_posix(tmpdir)
            assert_(os.path.samefile(new_ddir, new_ddir2))
        finally:
            os.chmod(d_dir, 0o700)
            os.chmod(d_dir2, 0o700)
            remove_tree(tmpdir) 
Example 46
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 5 votes vote down vote up
def test_default(self):
        in_path = catalog.default_dir()
        path = catalog.catalog_path(in_path)
        d,f = os.path.split(path)
        assert_(d == in_path)
        assert_(f == catalog.os_dependent_catalog_name()) 
Example 47
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 5 votes vote down vote up
def test_current(self):
        in_path = '.'
        path = catalog.catalog_path(in_path)
        d,f = os.path.split(path)
        assert_(d == os.path.abspath(in_path))
        assert_(f == catalog.os_dependent_catalog_name()) 
Example 48
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 5 votes vote down vote up
def test_user(path):
        in_path = '~'
        path = catalog.catalog_path(in_path)
        d,f = os.path.split(path)
        assert_(d == os.path.expanduser(in_path))
        assert_(f == catalog.os_dependent_catalog_name()) 
Example 49
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 5 votes vote down vote up
def test_path(self):
        # use os.__file__ to get a usable directory.
        in_path,f = os.path.split(os.__file__)
        path = catalog.catalog_path(in_path)
        d,f = os.path.split(path)
        assert_(d == in_path) 
Example 50
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 5 votes vote down vote up
def test_bad_path(self):
        # stupid_path_name
        in_path = 'stupid_path_name'
        path = catalog.catalog_path(in_path)
        assert_(path is None)