示例#1
0
def test_string_truncation_warning_masked():
    """
    Test warnings associated with in-place assignment to a string
    to a masked column, specifically where the right hand side
    contains np.ma.masked.
    """

    # Test for strings, but also cover assignment of np.ma.masked to
    # int and float masked column setting.  This was previously only
    # covered in an unrelated io.ascii test (test_line_endings) which
    # showed an unexpected difference between handling of str and numeric
    # masked arrays.
    for values in (['a', 'b'], [1, 2], [1.0, 2.0]):
        mc = table.MaskedColumn(values)

        with catch_warnings() as w:
            mc[1] = np.ma.masked
            assert len(w) == 0
            assert np.all(mc.mask == [False, True])

            mc[:] = np.ma.masked
            assert len(w) == 0
            assert np.all(mc.mask == [True, True])

    mc = table.MaskedColumn(['aa', 'bb'])

    with catch_warnings() as w:
        mc[:] = [np.ma.masked, 'ggg']  # replace item with string that gets truncated
        assert mc[1] == 'gg'
        assert np.all(mc.mask == [True, False])
        assert len(w) == 1
        assert ('truncated right side string(s) longer than 2 character(s)'
                in str(w[0].message))
示例#2
0
def test_errwarn_reporting():
    """
    Test that the ERFA error reporting mechanism works as it should
    """

    # no warning
    erfa.dat(1990, 1, 1, 0.5)

    # check warning is raised for a scalar
    with catch_warnings() as w:
        erfa.dat(100, 1, 1, 0.5)
        assert len(w) == 1
        assert w[0].category == erfa.ErfaWarning
        assert '1 of "dubious year (Note 1)"' in str(w[0].message)

    # and that the count is right for a vector.
    with catch_warnings() as w:
        erfa.dat([100, 200, 1990], 1, 1, 0.5)
        assert len(w) == 1
        assert w[0].category == erfa.ErfaWarning
        assert '2 of "dubious year (Note 1)"' in str(w[0].message)

    try:
        erfa.dat(1990, [1, 34, 2], [1, 1, 43], 0.5)
    except erfa.ErfaError as e:
        if '1 of "bad day (Note 3)", 1 of "bad month"' not in e.args[0]:
            assert False, 'Raised the correct type of error, but wrong message: ' + e.args[0]

    try:
        erfa.dat(200, [1, 34, 2], [1, 1, 43], 0.5)
    except erfa.ErfaError as e:
        if 'warning' in e.args[0]:
            assert False, 'Raised the correct type of error, but there were warnings mixed in: ' + e.args[0]
示例#3
0
def test_deprecated_class():
    orig_A = TA.__bases__[0]

    # The only thing that should be different about the new class
    # is __doc__, __init__, __bases__ and __subclasshook__.
    # and __init_subclass__ for Python 3.6+.
    for x in dir(orig_A):
        if x not in ('__doc__', '__init__', '__bases__', '__dict__',
                     '__subclasshook__', '__init_subclass__'):
            assert getattr(TA, x) == getattr(orig_A, x)

    with catch_warnings(AstropyDeprecationWarning) as w:
        TA()

    assert len(w) == 1
    if TA.__doc__ is not None:
        assert 'function' not in TA.__doc__
        assert 'deprecated' in TA.__doc__
        assert 'function' not in TA.__init__.__doc__
        assert 'deprecated' in TA.__init__.__doc__

    # Make sure the object is picklable
    pickle.dumps(TA)

    with catch_warnings(NewDeprecationWarning) as w:
        TC()

    assert len(w) == 1
    assert w[0].category == NewDeprecationWarning
示例#4
0
 def test_rshift_warns(self):
     with pytest.raises(TypeError), \
             catch_warnings() as warning_lines:
         1 >> u.m
     assert len(warning_lines) == 1
     assert warning_lines[0].category == AstropyWarning
     assert 'is not implemented' in str(warning_lines[0].message)
     q = 1. * u.km
     with pytest.raises(TypeError), \
             catch_warnings() as warning_lines:
         q >> u.m
     assert len(warning_lines) == 1
     assert warning_lines[0].category == AstropyWarning
     assert 'is not implemented' in str(warning_lines[0].message)
     with pytest.raises(TypeError), \
             catch_warnings() as warning_lines:
         q >>= u.m
     assert len(warning_lines) == 1
     assert warning_lines[0].category == AstropyWarning
     assert 'is not implemented' in str(warning_lines[0].message)
     with pytest.raises(TypeError), \
             catch_warnings() as warning_lines:
         1. >> q
     assert len(warning_lines) == 1
     assert warning_lines[0].category == AstropyWarning
     assert 'is not implemented' in str(warning_lines[0].message)
示例#5
0
def test_deprecated_class_with_new_method():
    """
    Test that a class with __new__ method still works even if it accepts
    additional arguments.
    This previously failed because the deprecated decorator would wrap objects
    __init__ which takes no arguments.
    """
    @deprecated('1.0')
    class A:
        def __new__(cls, a):
            return super().__new__(cls)

    # Creating an instance should work but raise a DeprecationWarning
    with catch_warnings(AstropyDeprecationWarning) as w:
        A(1)
    assert len(w) == 1

    @deprecated('1.0')
    class B:
        def __new__(cls, a):
            return super().__new__(cls)

        def __init__(self, a):
            pass

    # Creating an instance should work but raise a DeprecationWarning
    with catch_warnings(AstropyDeprecationWarning) as w:
        B(1)
    assert len(w) == 1
示例#6
0
def test_deprecated_static_and_classmethod():
    """
    Regression test for issue introduced by
    https://github.com/astropy/astropy/pull/2811 and mentioned also here:
    https://github.com/astropy/astropy/pull/2580#issuecomment-51049969
    where it appears that deprecated staticmethods didn't work on Python 2.6.
    """

    class A:
        """Docstring"""

        @deprecated('1.0')
        @staticmethod
        def B():
            pass

        @deprecated('1.0')
        @classmethod
        def C(cls):
            pass

    with catch_warnings(AstropyDeprecationWarning) as w:
        A.B()

    assert len(w) == 1
    if A.__doc__ is not None:
        assert 'deprecated' in A.B.__doc__

    with catch_warnings(AstropyDeprecationWarning) as w:
        A.C()

    assert len(w) == 1
    if A.__doc__ is not None:
        assert 'deprecated' in A.C.__doc__
示例#7
0
def test_deprecated_argument_pending():
    # Relax turns the TypeError if both old and new keyword are used into
    # a warning.
    @deprecated_renamed_argument('clobber', 'overwrite', '1.3', pending=True)
    def test(overwrite):
        return overwrite

    # As positional argument only
    assert test(1) == 1

    # As new keyword argument
    assert test(overwrite=1) == 1

    # Using the deprecated name
    with catch_warnings(AstropyUserWarning, AstropyDeprecationWarning) as w:
        assert test(clobber=1) == 1
        assert len(w) == 0

    # Using both. Both keyword
    with catch_warnings(AstropyUserWarning, AstropyDeprecationWarning) as w:
        assert test(clobber=2, overwrite=1) == 1
        assert len(w) == 0

    # One positional, one keyword
    with catch_warnings(AstropyUserWarning, AstropyDeprecationWarning) as w:
        assert test(1, clobber=2) == 1
        assert len(w) == 0
示例#8
0
    def test_deprecation_tolerance(self):
        """Verify uses of tolerance and rtol.
        This test should be removed in the next astropy version."""

        ha = Header([('B', 1.0), ('C', 0.1)])
        hb = ha.copy()
        hb['B'] = 1.00001
        hb['C'] = 0.100001
        with catch_warnings(AstropyDeprecationWarning) as warning_lines:
            diff = HeaderDiff(ha, hb, tolerance=1e-6)
            assert warning_lines[0].category == AstropyDeprecationWarning
            assert (str(warning_lines[0].message) == '"tolerance" was '
                    'deprecated in version 2.0 and will be removed in a '
                    'future version. Use argument "rtol" instead.')
            assert (diff.diff_keyword_values == {'C': [(0.1, 0.100001)],
                                                 'B': [(1.0, 1.00001)]})
            assert not diff.identical

        with catch_warnings(AstropyDeprecationWarning) as warning_lines:
            # `rtol` is always ignored when `tolerance` is provided
            diff = HeaderDiff(ha, hb, rtol=1e-6, tolerance=1e-5)
            assert warning_lines[0].category == AstropyDeprecationWarning
            assert (str(warning_lines[0].message) == '"tolerance" was '
                    'deprecated in version 2.0 and will be removed in a '
                    'future version. Use argument "rtol" instead.')
            assert diff.identical
示例#9
0
    def test_io_time_read_fits_location_warnings(self, table_types):
        """
        Test warnings for time column reference position.
        """
        # Time reference position "TOPOCENTER" without corresponding
        # observatory position.
        c = fits.Column(name='datetime', format='A29', coord_type='TT',
                        time_ref_pos='TOPOCENTER', array=self.time)

        bhdu = fits.BinTableHDU.from_columns([c])
        bhdu.writeto(self.temp('time.fits'), overwrite=True)

        with catch_warnings() as w:
            tm = table_types.read(self.temp('time.fits'), astropy_native=True)
            assert len(w) == 1
            assert ('observatory position is not properly specified' in
                    str(w[0].message))

        # Default value for time reference position is "TOPOCENTER"
        c = fits.Column(name='datetime', format='A29', coord_type='TT',
                        array=self.time)

        bhdu = fits.BinTableHDU.from_columns([c])
        bhdu.writeto(self.temp('time.fits'), overwrite=True)
        with catch_warnings() as w:
            tm = table_types.read(self.temp('time.fits'), astropy_native=True)
            assert len(w) == 1
            assert ('"TRPOSn" is not specified. The default value for '
                    'it is "TOPOCENTER"' in str(w[0].message))
示例#10
0
    def test_resource_warning(self):
        warnings.simplefilter('always', ResourceWarning)
        with catch_warnings() as w:
            data = fits.getdata(self.data('test0.fits'))
            assert len(w) == 0

        with catch_warnings() as w:
            header = fits.getheader(self.data('test0.fits'))
            assert len(w) == 0
示例#11
0
    def test_simple(self):

        with iers.conf.set_temp('iers_auto_url', self.iers_a_url_1):

            dat = iers.IERS_Auto.open()
            assert dat['MJD'][0] == 57359.0 * u.d
            assert dat['MJD'][-1] == 57539.0 * u.d

            # Pretend we are accessing at a time 7 days after start of predictive data
            predictive_mjd = dat.meta['predictive_mjd']
            dat._time_now = Time(predictive_mjd, format='mjd') + 7 * u.d

            # Look at times before and after the test file begins.  0.1292905 is
            # the IERS-B value from MJD=57359.  The value in
            # finals2000A-2016-02-30-test has been replaced at this point.
            assert np.allclose(dat.ut1_utc(Time(50000, format='mjd').jd).value, 0.1292905)
            assert np.allclose(dat.ut1_utc(Time(60000, format='mjd').jd).value, -0.2246227)

            # Now pretend we are accessing at time 60 days after start of predictive data.
            # There will be a warning when downloading the file doesn't give new data
            # and an exception when extrapolating into the future with insufficient data.
            dat._time_now = Time(predictive_mjd, format='mjd') + 60 * u.d
            assert np.allclose(dat.ut1_utc(Time(50000, format='mjd').jd).value, 0.1292905)
            with catch_warnings(iers.IERSStaleWarning) as warns:
                with pytest.raises(ValueError) as err:
                    dat.ut1_utc(Time(60000, format='mjd').jd)
            assert 'interpolating from IERS_Auto using predictive values' in str(err)
            assert len(warns) == 1
            assert 'IERS_Auto predictive values are older' in str(warns[0].message)

            # Warning only if we are getting return status
            with catch_warnings(iers.IERSStaleWarning) as warns:
                dat.ut1_utc(Time(60000, format='mjd').jd, return_status=True)
            assert len(warns) == 1
            assert 'IERS_Auto predictive values are older' in str(warns[0].message)

            # Now set auto_max_age = None which says that we don't care how old the
            # available IERS-A file is.  There should be no warnings or exceptions.
            with iers.conf.set_temp('auto_max_age', None):
                with catch_warnings(iers.IERSStaleWarning) as warns:
                    dat.ut1_utc(Time(60000, format='mjd').jd)
                assert not warns

        # Now point to a later file with same values but MJD increased by
        # 60 days and see that things work.  dat._time_now is still the same value
        # as before, i.e. right around the start of predictive values for the new file.
        # (In other words this is like downloading the latest file online right now).
        with iers.conf.set_temp('iers_auto_url', self.iers_a_url_2):

            # Look at times before and after the test file begins.  This forces a new download.
            assert np.allclose(dat.ut1_utc(Time(50000, format='mjd').jd).value, 0.1292905)
            assert np.allclose(dat.ut1_utc(Time(60000, format='mjd').jd).value, -0.3)

            # Now the time range should be different.
            assert dat['MJD'][0] == 57359.0 * u.d
            assert dat['MJD'][-1] == (57539.0 + 60) * u.d
示例#12
0
def test_oversize_char():
    config = {'pedantic': True}
    with catch_warnings(exceptions.W47) as w:
        field = tree.Field(
            None, name='c', datatype='char',
            config=config)
        c = converters.get_converter(field, config=config)
    assert len(w) == 1

    with catch_warnings(exceptions.W46) as w:
        c.parse("XXX")
    assert len(w) == 1
示例#13
0
def test_biweight_32bit_runtime_warnings():
    """Regression test for #6905."""
    with NumpyRNGContext(12345):
        data = np.random.random(100).astype(np.float32)
        data[50] = 30000.

        with catch_warnings(RuntimeWarning) as warning_lines:
            biweight_scale(data)
            assert len(warning_lines) == 0

        with catch_warnings(RuntimeWarning) as warning_lines:
            biweight_midvariance(data)
            assert len(warning_lines) == 0
示例#14
0
def test_parameter_default_identical_to_explicit_passed_argument():
    # If the default is identical to the explicitly passed argument this
    # should still raise a Warning and use the explicit one.
    @support_nddata
    def func(data, wcs=[1, 2, 3]):
        return wcs

    with catch_warnings(AstropyUserWarning) as w:
        assert func(NDData(1, wcs=[1, 2]), [1, 2, 3]) == [1, 2, 3]
        assert len(w) == 1

    with catch_warnings(AstropyUserWarning) as w:
        assert func(NDData(1, wcs=[1, 2])) == [1, 2]
        assert len(w) == 0
示例#15
0
def test_unit_warnings_read_write(tmpdir):
    filename = str(tmpdir.join('test_unit.fits'))
    t1 = Table([[1, 2], [3, 4]], names=['a', 'b'])
    t1['a'].unit = 'm/s'
    t1['b'].unit = 'not-a-unit'

    with catch_warnings() as l:
        t1.write(filename, overwrite=True)
        assert len(l) == 1
        assert str(l[0].message).startswith("'not-a-unit' did not parse as fits unit")

    with catch_warnings() as l:
        Table.read(filename, hdu=1)
    assert len(l) == 0
示例#16
0
def test_deprecated_argument_remove():
    @deprecated_renamed_argument('x', None, '2.0', alternative='astropy.y')
    def test(dummy=11):
        return dummy

    with catch_warnings(AstropyDeprecationWarning) as w:
        assert test(x=1) == 11
        assert len(w) == 1
        assert 'Use astropy.y instead' in str(w[0].message)

    with catch_warnings(AstropyDeprecationWarning) as w:
        assert test(x=1, dummy=10) == 10
        assert len(w) == 1

    assert test() == 11
示例#17
0
def test_type_missing_dependencies():
    from astropy.tests.helper import catch_warnings

    class MissingType(asdftypes.AsdfType):
        name = 'missing'
        organization = 'nowhere.org'
        version = (1, 0, 0)
        standard = 'custom'
        types = ['asdfghjkl12345.foo']
        requires = ["ASDFGHJKL12345"]

    class DefaultTypeExtension(CustomExtension):
        @property
        def types(self):
            return [MissingType]

    yaml = """
custom: !<tag:nowhere.org:custom/missing-1.0.0>
  b: {foo: 42}
    """
    buff = helpers.yaml_to_asdf(yaml)
    with catch_warnings() as w:
        with asdf.AsdfFile.open(buff, extensions=[DefaultTypeExtension()]) as ff:
            assert ff.tree['custom']['b']['foo'] == 42

    assert len(w) == 1
示例#18
0
def test_to_header_warning():
    fits_name = get_pkg_data_filename('data/sip.fits')
    x = wcs.WCS(fits_name)
    with catch_warnings() as w:
        x.to_header()
    assert len(w) == 1
    assert 'A_ORDER' in str(w[0])
示例#19
0
def test_deprecated_argument_multi_deprecation_2():
    @deprecated_renamed_argument(['x', 'y', 'z'], ['a', 'b', 'c'],
                                 [1.3, 1.2, 1.3], relax=[True, True, False])
    def test(a, b, c):
        return a, b, c

    with catch_warnings(AstropyUserWarning) as w:
        assert test(x=1, y=2, z=3, b=3) == (1, 3, 3)
        assert len(w) == 1

    with catch_warnings(AstropyUserWarning) as w:
        assert test(x=1, y=2, z=3, a=3) == (3, 2, 3)
        assert len(w) == 1

    with pytest.raises(TypeError):
        assert test(x=1, y=2, z=3, c=5) == (1, 2, 5)
示例#20
0
def test_deprecated_argument_in_kwargs():
    # To rename an argument that is consumed by "kwargs" the "arg_in_kwargs"
    # parameter is used.
    @deprecated_renamed_argument('clobber', 'overwrite', '1.3',
                                 arg_in_kwargs=True)
    def test(**kwargs):
        return kwargs['overwrite']

    # As positional argument only
    with pytest.raises(TypeError):
        test(1)

    # As new keyword argument
    assert test(overwrite=1) == 1

    # Using the deprecated name
    with catch_warnings(AstropyDeprecationWarning) as w:
        assert test(clobber=1) == 1
        assert len(w) == 1
        assert '1.3' in str(w[0].message)
        assert 'test_decorators.py' in str(w[0].filename)

    # Using both. Both keyword
    with pytest.raises(TypeError):
        test(clobber=2, overwrite=1)
    # One positional, one keyword
    with pytest.raises(TypeError):
        test(1, clobber=2)
示例#21
0
 def test_source_with_negval(self):
     data = self.data.copy()
     data -= 20
     with catch_warnings(AstropyUserWarning) as warning_lines:
         deblend_sources(data, self.segm, self.npixels)
         assert ('contains negative values' in
                 str(warning_lines[0].message))
示例#22
0
def test_cunit_invalid2():
    w = _wcs.Wcsprm()
    with catch_warnings() as warns:
        w.cunit = ['foo', 'bar']
    assert len(warns) == 2
    assert 'foo' in str(warns[0].message)
    assert 'bar' in str(warns[1].message)
示例#23
0
 def test_unnormalized_filter_kernel(self):
     with catch_warnings(AstropyUserWarning) as warning_lines:
         detect_sources(self.data, 0.1, npixels=1,
                        filter_kernel=self.filter_kernel*10.)
         assert warning_lines[0].category == AstropyUserWarning
         assert ('The kernel is not normalized.'
                 in str(warning_lines[0].message))
示例#24
0
 def test_dep_daofind_flux_negative(self):
     """Test handling of negative flux (here created by large sky)."""
     data = np.ones((5, 5))
     data[2, 2] = 10.
     with catch_warnings(AstropyDeprecationWarning):
         t = daofind(data, threshold=0.1, fwhm=1.0, sky=10)
     assert not np.isfinite(t['mag'])
示例#25
0
 def test_read_with_hdu_2(self, tmpdir, hdu):
     filename = str(tmpdir.join('test_read_with_hdu_2.fits'))
     self.hdus.writeto(filename)
     with catch_warnings() as l:
         t = Table.read(filename, hdu=hdu)
     assert len(l) == 0
     assert equal_data(t, self.data2)
示例#26
0
 def test_read_from_hdulist(self):
     with catch_warnings() as l:
         t = Table.read(self.hdus)
     assert len(l) == 1
     assert str(l[0].message).startswith(
         'hdu= was not specified but multiple tables are present, reading in first available table (hdu=1)')
     assert equal_data(t, self.data1)
示例#27
0
def test_preserve_serialized_compatibility_mode(tmpdir):
    test_file = str(tmpdir.join('test.hdf5'))

    t1 = Table()
    t1['a'] = Column(data=[1, 2, 3], unit="s")
    t1['a'].meta['a0'] = "A0"
    t1['a'].meta['a1'] = {"a1": [0, 1]}
    t1['a'].format = '7.3f'
    t1['a'].description = 'A column'
    t1.meta['b'] = 1
    t1.meta['c'] = {"c0": [0, 1]}

    with catch_warnings() as w:
        t1.write(test_file, path='the_table', serialize_meta=True,
                 overwrite=True, compatibility_mode=True)

    assert str(w[0].message).startswith(
        "compatibility mode for writing is deprecated")

    t2 = Table.read(test_file, path='the_table')

    assert t1['a'].unit == t2['a'].unit
    assert t1['a'].format == t2['a'].format
    assert t1['a'].description == t2['a'].description
    assert t1['a'].meta == t2['a'].meta
    assert t1.meta == t2.meta
示例#28
0
def test_pix2world():
    """
    From github issue #1463
    """
    # TODO: write this to test the expected output behavior of pix2world,
    # currently this just makes sure it doesn't error out in unexpected ways
    filename = get_pkg_data_filename('data/sip2.fits')
    with catch_warnings(wcs.wcs.FITSFixedWarning) as caught_warnings:
        # this raises a warning unimportant for this testing the pix2world
        #   FITSFixedWarning(u'The WCS transformation has more axes (2) than the
        #        image it is associated with (0)')
        ww = wcs.WCS(filename)

        # might as well monitor for changing behavior
        assert len(caught_warnings) == 1

    n = 3
    pixels = (np.arange(n) * np.ones((2, n))).T
    result = ww.wcs_pix2world(pixels, 0, ra_dec_order=True)

    # Catch #2791
    ww.wcs_pix2world(pixels[..., 0], pixels[..., 1], 0, ra_dec_order=True)

    close_enough = 1e-8
    # assuming that the data of sip2.fits doesn't change
    answer = np.array([[0.00024976, 0.00023018],
                       [0.00023043, -0.00024997]])

    assert np.all(np.abs(ww.wcs.pc - answer) < close_enough)

    answer = np.array([[202.39265216, 47.17756518],
                       [202.39335826, 47.17754619],
                       [202.39406436, 47.1775272]])

    assert np.all(np.abs(result - answer) < close_enough)
示例#29
0
    def test_open_file_with_bad_header_padding(self):
        """
        Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/136

        Open files with nulls for header block padding instead of spaces.
        """

        a = np.arange(100).reshape(10, 10)
        hdu = fits.PrimaryHDU(data=a)
        hdu.writeto(self.temp('temp.fits'))

        # Figure out where the header padding begins and fill it with nulls
        end_card_pos = str(hdu.header).index('END' + ' ' * 77)
        padding_start = end_card_pos + 80
        padding_len = 2880 - padding_start
        with open(self.temp('temp.fits'), 'r+b') as f:
            f.seek(padding_start)
            f.write('\0'.encode('ascii') * padding_len)

        with catch_warnings(AstropyUserWarning) as w:
            with fits.open(self.temp('temp.fits')) as hdul:
                assert (hdul[0].data == a).all()
        assert ('contains null bytes instead of spaces' in
                str(w[0].message))
        assert len(w) == 1
        assert len(hdul) == 1
        assert str(hdul[0].header) == str(hdu.header)
示例#30
0
    def test_invalidlabels(self):
        with catch_warnings(AstropyUserWarning) as warning_lines:
            source_properties(IMAGE, SEGM, labels=[-1, 1])

            assert warning_lines[0].category == AstropyUserWarning
            assert ('label -1 is not in the segmentation image.' in
                    str(warning_lines[0].message))
示例#31
0
 def test_load_events_noclobber(self):
     """Test event file reading w. noclobber option."""
     with catch_warnings() as w:
         command = \
             '{0} --noclobber'.format(
                 os.path.join(self.datadir, 'monol_testB.evt'))
         hen.read_events.main(command.split())
     assert str(w[0].message).strip().endswith(
         "noclobber option used. Skipping"), \
         "Unexpected warning output"
示例#32
0
def test_missing_region_warns():
    ds9_str = '# Region file format: DS9 astropy/regions\nfk5\ncircle(42.0000,43.0000,3.0000)\nnotaregiontype(blah)'

    # this will warn on both the commented first line and the not_a_region line
    with catch_warnings(AstropyUserWarning) as ASWarn:
        parser = DS9Parser(ds9_str, errors='warn')

    assert len(parser.shapes) == 1
    assert len(ASWarn) == 1
    assert "Region type 'notaregiontype' was identified, but it is not one of the known region types." in str(ASWarn[0].message)
示例#33
0
 def test_overwrite_vs_clobber(self):
     hdulist = fits.HDUList([fits.PrimaryHDU()])
     hdulist.writeto(self.temp('test_overwrite.fits'))
     hdulist.writeto(self.temp('test_overwrite.fits'), overwrite=True)
     with catch_warnings(AstropyDeprecationWarning) as warning_lines:
         hdulist.writeto(self.temp('test_overwrite.fits'), clobber=True)
         assert warning_lines[0].category == AstropyDeprecationWarning
         assert (str(warning_lines[0].message) == '"clobber" was '
                 'deprecated in version 2.0 and will be removed in a '
                 'future version. Use argument "overwrite" instead.')
示例#34
0
def test_version_mismatch_file():
    testfile = os.path.join(TEST_DATA_PATH, 'version_mismatch.fits')

    with catch_warnings() as w:
        with asdf.AsdfFile.open(testfile) as fits_handle:
            assert fits_handle.tree['a'] == complex(0j)
    # This is the warning that we expect from opening the FITS file
    assert len(w) == 1
    assert str(w[0].message) == (
        "'tag:stsci.edu:asdf/core/complex' with version 7.0.0 found in file "
        "'file://{}', but latest supported version is 1.0.0".format(testfile))

    with catch_warnings() as w:
        with fits_embed.AsdfInFits.open(testfile) as fits_handle:
            assert fits_handle.tree['a'] == complex(0j)
    assert len(w) == 1
    assert str(w[0].message) == (
        "'tag:stsci.edu:asdf/core/complex' with version 7.0.0 found in file "
        "'file://{}', but latest supported version is 1.0.0".format(testfile))
def test_blackbody_exceptions_and_warnings():
    """Test exceptions."""

    # Negative temperature
    with pytest.raises(ValueError) as exc:
        blackbody_nu(1000 * u.AA, -100)
    assert exc.value.args[0] == 'Temperature should be positive: -100.0 K'

    # Zero wavelength given for conversion to Hz
    with catch_warnings(AstropyUserWarning) as w:
        blackbody_nu(0 * u.AA, 5000)
    assert len(w) == 1
    assert 'invalid' in w[0].message.args[0]

    # Negative wavelength given for conversion to Hz
    with catch_warnings(AstropyUserWarning) as w:
        blackbody_nu(-1. * u.AA, 5000)
    assert len(w) == 1
    assert 'invalid' in w[0].message.args[0]
示例#36
0
 def test_read(self, tmpdir):
     filename = str(tmpdir.join('test_read.fits'))
     self.hdus.writeto(filename)
     with catch_warnings() as l:
         t = Table.read(filename)
     assert len(l) == 1
     assert str(l[0].message).startswith(
         'hdu= was not specified but multiple tables are present, reading in first available table (hdu=1)'
     )
     assert equal_data(t, self.data1)
示例#37
0
 def test_nw_float_to_byte(self):
     colors = np.zeros((10, 10, 3), dtype=np.float)
     byte_colors = nw_float_to_byte(colors)
     assert (byte_colors == 0).all()
     colors = np.ones((10, 10, 3), dtype=np.float)
     byte_colors = nw_float_to_byte(colors)
     assert (byte_colors == 255).all()
     with catch_warnings(PydlutilsUserWarning) as w:
         byte_colors = nw_float_to_byte(colors, bits=16)
     assert len(w) > 0
示例#38
0
 def test_simple_meta_conflicting(self, tmpdir):
     filename = str(tmpdir.join('test_simple.fits'))
     t1 = Table(self.data)
     t1.meta['ttype1'] = 'spam'
     with catch_warnings() as l:
         t1.write(filename, overwrite=True)
     assert len(l) == 1
     assert str(l[0].message).startswith(
         'Meta-data keyword ttype1 will be ignored since it conflicts with a FITS reserved keyword'
     )
        def setup_class(cls):
            m = 1
            nfreq = 100
            freq = np.arange(nfreq)
            noise = np.random.exponential(size=nfreq)
            power = noise * 2.0

            ps = Powerspectrum()
            ps.freq = freq
            ps.power = power
            ps.m = m
            ps.df = freq[1] - freq[0]
            ps.norm = "leahy"

            cls.ps = ps
            cls.a_mean, cls.a_var = 2.0, 1.0

            cls.model = models.Const1D()

            p_amplitude = lambda amplitude: \
                scipy.stats.norm(loc=cls.a_mean, scale=cls.a_var).pdf(
                    amplitude)

            cls.priors = {"amplitude": p_amplitude}
            cls.lpost = PSDPosterior(cls.ps.freq,
                                     cls.ps.power,
                                     cls.model,
                                     m=cls.ps.m)
            cls.lpost.logprior = set_logprior(cls.lpost, cls.priors)

            cls.fitmethod = "BFGS"
            cls.max_post = True
            cls.t0 = [2.0]
            cls.neg = True

            pe = ParameterEstimation()
            res = pe.fit(cls.lpost, cls.t0)

            cls.nwalkers = 50
            cls.niter = 100

            np.random.seed(200)
            p0 = np.array([
                np.random.multivariate_normal(res.p_opt, res.cov)
                for i in range(cls.nwalkers)
            ])

            cls.sampler = emcee.EnsembleSampler(cls.nwalkers,
                                                len(res.p_opt),
                                                cls.lpost,
                                                args=[False],
                                                threads=1)

            with catch_warnings(RuntimeWarning):
                _, _, _ = cls.sampler.run_mcmc(p0, cls.niter)
示例#40
0
    def test_calibrate_lrt_works_with_sampling(self):
        m = 1
        nfreq = 100
        freq = np.linspace(1, 10, nfreq)
        rng = np.random.RandomState(100)
        noise = rng.exponential(size=nfreq)
        model = models.Const1D()
        model.amplitude = 2.0
        p = model(freq)
        power = noise * p

        ps = Powerspectrum()
        ps.freq = freq
        ps.power = power
        ps.m = m
        ps.df = freq[1] - freq[0]
        ps.norm = "leahy"

        lpost = PSDPosterior(ps.freq, ps.power, model, m=1)

        p_amplitude_1 = lambda amplitude: \
            scipy.stats.norm(loc=2.0, scale=1.0).pdf(amplitude)

        p_alpha_0 = lambda alpha: \
            scipy.stats.uniform(0.0, 5.0).pdf(alpha)

        p_amplitude_0 = lambda amplitude: \
            scipy.stats.norm(loc=self.a2_mean, scale=self.a2_var).pdf(
                amplitude)


        priors = {"amplitude": p_amplitude_1}

        priors2 = {"amplitude_1": p_amplitude_1,
                      "amplitude_0": p_amplitude_0,
                      "alpha_0": p_alpha_0}


        lpost.logprior = set_logprior(lpost, priors)

        model2 = models.PowerLaw1D() + models.Const1D()
        model2.x_0_0.fixed = True
        lpost2 = PSDPosterior(ps.freq, ps.power, model2, 1)
        lpost2.logprior = set_logprior(lpost2, priors2)

        pe = PSDParEst(ps)

        with catch_warnings(RuntimeWarning):
            pval = pe.calibrate_lrt(lpost, [2.0], lpost2,
                                    [2.0, 1.0, 2.0], sample=None,
                                    max_post=True, nsim=10, nwalkers=10,
                                    burnin=10, niter=10,
                                    seed=100)

        assert pval > 0.001
示例#41
0
def test_schema_example(filename, example):
    """Pytest to check validity of a specific example within schema file

    Parameters:
    -----------
    filename : name of the schema file containing example to be tested

    example: string representing example

    This function is called with a range of parameters by pytest's
    'parametrize' utility in order to account for all examples in all schema
    files.
    """
    if not HAS_GWCS and re.search(r'frame-\d\.\d\.\d\.yaml', filename):
        return pytest.skip

    standard_version = _find_standard_version(filename)

    # Make sure that the examples in the schema files (and thus the
    # ASDF standard document) are valid.
    buff = helpers.yaml_to_asdf('example: ' + example.strip(),
                                standard_version=standard_version)
    ff = asdf.AsdfFile(uri=util.filepath_to_url(os.path.abspath(filename)),
                       extensions=TestExtension())

    # Fake an external file
    ff2 = asdf.AsdfFile({'data': np.empty((1024 * 1024 * 8), dtype=np.uint8)})

    ff._external_asdf_by_uri[util.filepath_to_url(
        os.path.abspath(
            os.path.join(os.path.dirname(filename), 'external.asdf')))] = ff2

    # Add some dummy blocks so that the ndarray examples work
    for i in range(3):
        b = block.Block(np.zeros((1024 * 1024 * 8), dtype=np.uint8))
        b._used = True
        ff.blocks.add(b)
    b._array_storage = "streamed"

    try:
        with catch_warnings() as w:
            ff._open_impl(ff, buff)
        # Do not tolerate any warnings that occur during schema validation,
        # other than a few that we expect to occur under certain circumstances
        _assert_warnings(w)
    except:
        print("From file:", filename)
        raise

    # Just test we can write it out.  A roundtrip test
    # wouldn't always yield the correct result, so those have
    # to be covered by "real" unit tests.
    if b'external.asdf' not in buff.getvalue():
        buff = io.BytesIO()
        ff.write_to(buff)
示例#42
0
    def test_io_time_read_fits_scale(self, table_types):
        """
        Test handling of 'GPS' and 'LOCAL' time scales which are
        recognized by the FITS standard but are not native to astropy.
        """
        # GPS scale column
        gps_time = np.array([630720013, 630720014])
        c = fits.Column(name='gps_time',
                        format='D',
                        unit='s',
                        coord_type='GPS',
                        coord_unit='s',
                        time_ref_pos='TOPOCENTER',
                        array=gps_time)

        cards = [('OBSGEO-L', 0), ('OBSGEO-B', 0), ('OBSGEO-H', 0)]

        with pytest.warns(AstropyDeprecationWarning,
                          match='should be set via '
                          'the Column objects: TCTYPn, TCUNIn, TRPOSn'):
            bhdu = fits.BinTableHDU.from_columns([c],
                                                 header=fits.Header(cards))
        bhdu.writeto(self.temp('time.fits'), overwrite=True)

        with catch_warnings() as w:
            tm = table_types.read(self.temp('time.fits'), astropy_native=True)
            assert len(w) == 1
            assert 'FITS recognized time scale value "GPS"' in str(
                w[0].message)

        assert isinstance(tm['gps_time'], Time)
        assert tm['gps_time'].format == 'gps'
        assert tm['gps_time'].scale == 'tai'
        assert (tm['gps_time'].value == gps_time).all()

        # LOCAL scale column
        local_time = np.array([1, 2])
        c = fits.Column(name='local_time',
                        format='D',
                        unit='d',
                        coord_type='LOCAL',
                        coord_unit='d',
                        time_ref_pos='RELOCATABLE',
                        array=local_time)

        bhdu = fits.BinTableHDU.from_columns([c])
        bhdu.writeto(self.temp('time.fits'), overwrite=True)

        tm = table_types.read(self.temp('time.fits'), astropy_native=True)

        assert isinstance(tm['local_time'], Time)
        assert tm['local_time'].format == 'mjd'

        assert tm['local_time'].scale == 'local'
        assert (tm['local_time'].value == local_time).all()
示例#43
0
def test_initialize_from_fits_with_data_in_different_extension(tmpdir):
    fake_img = np.arange(4).reshape(2, 2)
    hdu1 = fits.PrimaryHDU()
    hdu2 = fits.ImageHDU(fake_img)
    hdus = fits.HDUList([hdu1, hdu2])
    filename = tmpdir.join('afile.fits').strpath
    hdus.writeto(filename)
    with catch_warnings(FITSFixedWarning) as w:
        ccd = FrameData.read_fits(filename, unit='adu')
    check.equal(len(w), 0)
    np.testing.assert_array_equal(ccd.data, fake_img)
示例#44
0
def test_oversize_unicode():
    config = {'verify': 'exception'}
    with catch_warnings(exceptions.W46) as w:
        field = tree.Field(None,
                           name='c2',
                           datatype='unicodeChar',
                           config=config)
        c = converters.get_converter(field, config=config)

        c.parse("XXX")
    assert len(w) == 1
示例#45
0
def test_multiple_solidus():
    assert u.Unit("m/s/kg").to_string() == u.m / u.s / u.kg

    with catch_warnings(u.UnitsWarning) as warning_lines:
        assert u.Unit("m/s/kg").to_string() == u.m / (u.s * u.kg)

    assert 'm/s/kg' in str(warning_lines[0].message)
    assert 'discouraged' in str(warning_lines[0].message)

    with pytest.raises(ValueError):
        u.Unit("m/s/kg", format="vounit")
示例#46
0
def test_measures_fitness_heteroscedastic():
    np.random.seed(1)
    t = np.linspace(0, 1, 11)
    x = np.exp(-0.5 * (t - 0.5)**2 / 0.01**2)
    sigma = 0.02 + 0.02 * np.random.random(len(x))
    x = np.random.normal(x, sigma)

    with catch_warnings(AstroMLDeprecationWarning):
        bins = bayesian_blocks(t, x, sigma, fitness='measures')

    assert_allclose(bins, [0, 0.45, 0.55, 1])
示例#47
0
    def test_flush_readonly(self):
        """Test flushing changes to a file opened in a read only mode."""

        oldmtime = os.stat(self.data('test0.fits')).st_mtime
        hdul = fits.open(self.data('test0.fits'))
        hdul[0].header['FOO'] = 'BAR'
        with catch_warnings(AstropyUserWarning) as w:
            hdul.flush()
        assert len(w) == 1
        assert 'mode is not supported' in str(w[0].message)
        assert oldmtime == os.stat(self.data('test0.fits')).st_mtime
示例#48
0
def test_write_valid_meta_ipac():
    """Write an IPAC table that contains no data and has *correctly* specified
    metadata.  No warnings should be issued"""
    table = ascii.get_reader(Reader=ascii.Ipac)
    data = table.read('data/no_data_ipac.dat')
    data.meta['keywords']['blah'] = {'value': 'invalid'}

    with catch_warnings(AstropyWarning) as ASwarn:
        out = StringIO()
        data.write(out, format='ascii.ipac')
    assert len(ASwarn) == 0
示例#49
0
    def test_table_non_stringifyable_unit_to_hdu(self):
        table = Table([[1, 2, 3], ['a', 'b', 'c'], [2.3, 4.5, 6.7]],
                      names=['a', 'b', 'c'],
                      dtype=['i', 'U1', 'f'])
        table['a'].unit = u.core.IrreducibleUnit("test")

        with catch_warnings() as w:
            fits.table_to_hdu(table)
            assert len(w) == 1
            assert str(
                w[0].message).startswith("The unit 'test' could not be saved")
示例#50
0
    def test_sampler_runs(self):
        pe = ParameterEstimation()
        if os.path.exists("test_corner.pdf"):
            os.unlink("test_corner.pdf")
        with catch_warnings(RuntimeWarning):
            sample_res = pe.sample(self.lpost, [2.0], nwalkers=50, niter=10,
                                   burnin=50, print_results=True, plot=True)

        assert os.path.exists("test_corner.pdf")
        assert sample_res.acceptance > 0.25
        assert isinstance(sample_res, SamplingResults)
示例#51
0
    def test_alias_read(self):
        from astropy.utils.data import conf

        with catch_warnings() as w:
            conf.reload()
            assert conf.remote_timeout == 42

        assert len(w) == 1
        assert str(w[0].message).startswith(
            "Config parameter 'name_resolve_timeout' in section "
            "[coordinates.name_resolve]")
示例#52
0
def test_traverse_postorder_duplicate_subtrees():
    """
    Regression test for a bug in `ExpressionTree.traverse_postorder`
    where given an expression like ``(1 + 2) + (1 + 2)`` where the two proper
    subtrees are actually the same object.
    """
    with catch_warnings(AstropyDeprecationWarning):
        subtree = ET('+', ET(1), ET(2))
        tree = ET('+', subtree, subtree)
    traversal = [n.value for n in tree.traverse_postorder()]
    assert traversal == [1, 2, '+', 1, 2, '+', '+']
示例#53
0
def test_read_nopath(tmpdir):
    test_file = str(tmpdir.join('test.hdf5'))
    t1 = Table()
    t1.add_column(Column(name='a', data=[1, 2, 3]))
    t1.write(test_file, path="the_table")
    with catch_warnings(AstropyUserWarning) as warning_lines:
        t2 = Table.read(test_file)
        assert not np.any(
            ["path= was not sp" in str(wl.message) for wl in warning_lines])

    assert np.all(t1['a'] == t2['a'])
示例#54
0
def test_version_mismatch():
    from astropy.tests.helper import catch_warnings

    yaml = """
a: !core/complex-42.0.0
  0j
    """

    buff = helpers.yaml_to_asdf(yaml)
    with catch_warnings() as w:
        with asdf.AsdfFile.open(buff) as ff:
            assert isinstance(ff.tree['a'], complex)

    assert len(w) == 1
    assert str(w[0].message) == (
        "'tag:stsci.edu:asdf/core/complex' with version 42.0.0 found in file, "
        "but asdf only understands version 1.0.0.")

    # Make sure warning is repeatable
    buff.seek(0)
    with catch_warnings() as w:
        with asdf.AsdfFile.open(buff) as ff:
            assert isinstance(ff.tree['a'], complex)

    assert len(w) == 1
    assert str(w[0].message) == (
        "'tag:stsci.edu:asdf/core/complex' with version 42.0.0 found in file, "
        "but asdf only understands version 1.0.0.")

    # If the major and minor match, there should be no warning.
    yaml = """
a: !core/complex-1.0.1
  0j
    """

    buff = helpers.yaml_to_asdf(yaml)
    with catch_warnings() as w:
        with asdf.AsdfFile.open(buff) as ff:
            assert isinstance(ff.tree['a'], complex)

    assert len(w) == 0
示例#55
0
def test_write_nopath(tmpdir):
    test_file = str(tmpdir.join('test.hdf5'))
    t1 = Table()
    t1.add_column(Column(name='a', data=[1, 2, 3]))

    with catch_warnings() as warns:
        t1.write(test_file)

    assert np.any([str(w.message).startswith(
        "table path was not set via the path= argument")
                   for w in warns])
    t1 = Table.read(test_file, path='__astropy_table__')
示例#56
0
def test_deprecated_class_with_custom_metaclass():
    """
    Regression test for an issue where deprecating a class with a metaclass
    other than type did not restore the metaclass properly.
    """

    with catch_warnings(AstropyDeprecationWarning) as w:
        TB()

    assert len(w) == 1
    assert type(TB) is TMeta
    assert TB.metaclass_attr == 1
示例#57
0
def test_function_transform_with_differentials():
    tfun = lambda c, f: f.__class__(ra=c.ra, dec=c.dec)
    ftrans = t.FunctionTransform(tfun, TCoo3, TCoo2,
                                 register_graph=frame_transform_graph)

    t3 = TCoo3(ra=1*u.deg, dec=2*u.deg, pm_ra_cosdec=1*u.marcsec/u.yr,
               pm_dec=1*u.marcsec/u.yr,)

    with catch_warnings() as w:
        t2 = t3.transform_to(TCoo2)
        assert len(w) == 1
        assert 'they have been dropped' in str(w[0].message)
示例#58
0
    def check_roundtrip(self, unit):
        with catch_warnings() as w:
            s = unit.to_string(self.format_)
            a = core.Unit(s, format=self.format_)

        if s in self.deprecated_units:
            assert w
            assert 'deprecated' in str(w[0])
        else:
            assert not w

        assert_allclose(a.decompose().scale, unit.decompose().scale, rtol=1e-9)
示例#59
0
def test_duplicate_events():
    t = np.random.random(100)
    t[80:] = t[:20]

    x = np.ones_like(t)
    x[:20] += 1

    with catch_warnings(AstroMLDeprecationWarning):
        bins1 = bayesian_blocks(t)
        bins2 = bayesian_blocks(t[:80], x[:80])

    assert_allclose(bins1, bins2)
示例#60
0
def test_warning_about_defunct_keywords():
    def run():
        header = get_pkg_data_contents('data/defunct_keywords.hdr',
                                       encoding='binary')
        wcs.WCS(header)

    with catch_warnings(wcs.FITSFixedWarning) as w:
        run()

    assert len(w) == 4
    for item in w:
        assert 'PCi_ja' in str(item.message)

    # Make sure the warnings come out every time...

    with catch_warnings(wcs.FITSFixedWarning) as w:
        run()

    assert len(w) == 4
    for item in w:
        assert 'PCi_ja' in str(item.message)