Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
164c1ba
MNT: Replace catch_warnings in erfa tests
pllim Jun 17, 2020
2718912
MNT: Replace catch_warnings in config tests
pllim Jun 17, 2020
10391d2
MNT: Replace catch_warnings in coordinates tests.
pllim Jun 17, 2020
faf20ec
MNT: Replace catch_warnings in io.ascii tests
pllim Jun 19, 2020
d3ae2df
MNT: Remove catch_warnings from test guide
pllim Jun 19, 2020
3f1fc48
MNT: Remove catch_warnings from units tests.
pllim Jun 25, 2020
d5504cc
MNT: Remove catch_warnings from wcsaxes tests
pllim Jun 26, 2020
089626d
MNT: Remove catch_warnings from utils iers and decorators
pllim Jun 26, 2020
9748b1b
MNT: Remove catch_warnings from utils data
pllim Jun 26, 2020
51a59b4
Fix test failure seen in image-tests-mpl222
pllim Jun 26, 2020
60146b5
More fixes for coordinates, table, wcsapi
pllim Jun 26, 2020
ce7b5c8
MNT: Remove catch_warnings and raises from io.fits
pllim Jun 26, 2020
5166ade
MNT: Remove catch_warnings from io.misc
pllim Jun 26, 2020
70ae5aa
MNT: Remove catch_warnings and raises from io.votable
pllim Jun 27, 2020
0328481
MNT: Remove catch_warnings and raises from modeling
pllim Jun 27, 2020
f193be1
MNT: Remove catch_warnings from nddata
pllim Jun 27, 2020
d14d246
MNT: Remove catch_warnings from stats
pllim Jun 27, 2020
a7dc955
MNT: Remove catch_warnings from table tests
pllim Jun 27, 2020
a89eda3
MNT: Remove catch_warnings from logger tests
pllim Jun 27, 2020
0fc7831
MNT: Remove catch_warnings from time tests
pllim Jun 27, 2020
a4ee90a
MNT: Remove catch_warnings and raises from units tests
pllim Jun 27, 2020
ad61c7d
MNT: Remove outdated imports
pllim Jun 27, 2020
fa2dd7b
DOC: Also add a note about raises
pllim Jun 27, 2020
6b11398
Fix typo and CI error
pllim Jun 27, 2020
f467c4a
MNT: Remove catch_warning and raises from wcs tests
pllim Jun 30, 2020
8301175
Fix test_oversize_unicode in io.votable
pllim Jul 1, 2020
0c348c6
Delete duplicate test_write_nopath in test_hdf5
pllim Jul 1, 2020
73b94a4
Apply @mhvk comments for modeling, table, utils tests
pllim Jul 1, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 10 additions & 20 deletions astropy/_erfa/tests/test_erfa.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

from astropy import _erfa as erfa
from astropy.time import Time
from astropy.tests.helper import catch_warnings


def test_erfa_wrapper():
Expand All @@ -20,13 +19,13 @@ def test_erfa_wrapper():
ra = np.linspace(0.0, np.pi*2.0, 5)
dec = np.linspace(-np.pi/2.0, np.pi/2.0, 4)

aob, zob, hob, dob, rob, eo = erfa.atco13(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, jd, 0.0, 0.0, 0.0, np.pi/4.0, 0.0, 0.0, 0.0, 1014.0, 0.0, 0.0, 0.5)
aob, zob, hob, dob, rob, eo = erfa.atco13(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, jd, 0.0, 0.0, 0.0, np.pi/4.0, 0.0, 0.0, 0.0, 1014.0, 0.0, 0.0, 0.5) # noqa
assert aob.shape == (121,)

aob, zob, hob, dob, rob, eo = erfa.atco13(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, jd[0], 0.0, 0.0, 0.0, np.pi/4.0, 0.0, 0.0, 0.0, 1014.0, 0.0, 0.0, 0.5)
aob, zob, hob, dob, rob, eo = erfa.atco13(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, jd[0], 0.0, 0.0, 0.0, np.pi/4.0, 0.0, 0.0, 0.0, 1014.0, 0.0, 0.0, 0.5) # noqa
assert aob.shape == ()

aob, zob, hob, dob, rob, eo = erfa.atco13(ra[:, None, None], dec[None, :, None], 0.0, 0.0, 0.0, 0.0, jd[None, None, :], 0.0, 0.0, 0.0, np.pi/4.0, 0.0, 0.0, 0.0, 1014.0, 0.0, 0.0, 0.5)
aob, zob, hob, dob, rob, eo = erfa.atco13(ra[:, None, None], dec[None, :, None], 0.0, 0.0, 0.0, 0.0, jd[None, None, :], 0.0, 0.0, 0.0, np.pi/4.0, 0.0, 0.0, 0.0, 1014.0, 0.0, 0.0, 0.5) # noqa
(aob.shape) == (5, 4, 121)

iy, im, id, ihmsf = erfa.d2dtf("UTC", 3, jd, 0.0)
Expand Down Expand Up @@ -111,30 +110,21 @@ def test_errwarn_reporting():
erfa.dat(1990, 1, 1, 0.5)

# check warning is raised for a scalar
with catch_warnings() as w:
with pytest.warns(erfa.ErfaWarning, match=r'.* 1 of "dubious year \(Note 1\)"') 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)
assert len(w) == 1

# and that the count is right for a vector.
with catch_warnings() as w:
with pytest.warns(erfa.ErfaWarning, match=r'.* 2 of "dubious year \(Note 1\)".*') 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)
assert len(w) == 1

try:
with pytest.raises(erfa.ErfaError, match=r'.* 1 of "bad day \(Note 3\)", 1 of "bad month".*'):
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:
with pytest.raises(erfa.ErfaError) as e:
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]
assert 'warning' not in str(e.value), f'Raised the correct type of error, but there were warnings mixed in: {str(e.value)}' # noqa


def test_vector_inouts():
Expand Down
17 changes: 7 additions & 10 deletions astropy/config/tests/test_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@

import pytest

from astropy.tests.helper import catch_warnings

from astropy.config import configuration
from astropy.config import paths
from astropy.utils.data import get_pkg_data_filename
Expand Down Expand Up @@ -310,11 +308,10 @@ def osraiser(dirnm, linkto, pkgname=None):

# now run the basic tests, and make sure the warning about no astropy
# is present
with catch_warnings(configuration.ConfigurationMissingWarning) as w:
with pytest.warns(configuration.ConfigurationMissingWarning,
match='Configuration defaults will be used') as w:
test_configitem()
assert len(w) == 1
w = w[0]
assert 'Configuration defaults will be used' in str(w.message)


def test_configitem_setters():
Expand Down Expand Up @@ -375,14 +372,14 @@ def setup_class(self):
def test_alias_read(self):
from astropy.utils.data import conf

with catch_warnings() as w:
with pytest.warns(
AstropyDeprecationWarning,
match=r"Config parameter 'name_resolve_timeout' in section "
r"\[coordinates.name_resolve\].*") 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]")

def teardown_class(self):
from astropy.utils.data import conf
Expand Down Expand Up @@ -417,7 +414,7 @@ def test_warning_move_to_top_level():
configuration._override_config_file = get_pkg_data_filename('data/deprecated.cfg')

try:
with catch_warnings(AstropyDeprecationWarning) as w:
with pytest.warns(AstropyDeprecationWarning) as w:
conf.reload()
conf.max_lines
assert len(w) == 1
Expand Down
28 changes: 15 additions & 13 deletions astropy/coordinates/tests/test_api_ape5.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@
import numpy as np
from numpy import testing as npt

from astropy.tests.helper import raises, assert_quantity_allclose as assert_allclose
from astropy.tests.helper import assert_quantity_allclose as assert_allclose
from astropy import units as u
from astropy import time
from astropy import coordinates as coords
from astropy.units import allclose

try:
import scipy # pylint: disable=W0611
import scipy # pylint: disable=W0611 # noqa
except ImportError:
HAS_SCIPY = False
else:
Expand Down Expand Up @@ -78,7 +78,7 @@ def test_representations_api():
c2 = SphericalRepresentation(lon=[8, 9]*u.hourangle, lat=[5, 6]*u.deg, distance=10*u.kpc)
assert len(c2.distance) == 2
# when they can't be broadcast, it is a ValueError (same as Numpy)
with raises(ValueError):
with pytest.raises(ValueError):
c2 = UnitSphericalRepresentation(lon=[8, 9, 10]*u.hourangle, lat=[5, 6]*u.deg)

# It's also possible to pass in scalar quantity lists with mixed units. These
Expand All @@ -101,7 +101,7 @@ def test_representations_api():
assert isinstance(c1.distance, Distance)

# but they are read-only, as representations are immutable once created
with raises(AttributeError):
with pytest.raises(AttributeError):
c1.lat = Latitude(5, u.deg)
# Note that it is still possible to modify the array in-place, but this is not
# sanctioned by the API, as this would prevent things like caching.
Expand All @@ -111,7 +111,7 @@ def test_representations_api():
# coordinates are defined, other conventions can be included as new classes.
# Later there may be other conventions that we implement - for now just the
# physics convention, as it is one of the most common cases.
c3 = PhysicsSphericalRepresentation(phi=120*u.deg, theta=85*u.deg, r=3*u.kpc)
_ = PhysicsSphericalRepresentation(phi=120*u.deg, theta=85*u.deg, r=3*u.kpc)

# first dimension must be length-3 if a lone `Quantity` is passed in.
c1 = CartesianRepresentation(np.random.randn(3, 100) * u.kpc)
Expand Down Expand Up @@ -170,11 +170,11 @@ def test_frame_api():

# the information required to specify the frame is immutable
J2001 = time.Time('J2001')
with raises(AttributeError):
with pytest.raises(AttributeError):
fk5.equinox = J2001

# Similar for the representation data.
with raises(AttributeError):
with pytest.raises(AttributeError):
fk5.data = UnitSphericalRepresentation(lon=8*u.hour, lat=5*u.deg)

# There is also a class-level attribute that lists the attributes needed to
Expand Down Expand Up @@ -224,7 +224,7 @@ def test_frame_api():
assert coo3.separation_3d(coo4).kpc == 1.0

# The next example fails because `coo1` and `coo2` don't have distances
with raises(ValueError):
with pytest.raises(ValueError):
assert coo1.separation_3d(coo2).kpc == 1.0

# repr/str also shows info, with frame and data
Expand Down Expand Up @@ -289,7 +289,7 @@ def test_transform_api():
assert_allclose(fk5_2.ra, fk5_trans_2.ra, rtol=0, atol=1e-10*u.deg)

# Trying to transforming a frame with no data is of course an error:
with raises(ValueError):
with pytest.raises(ValueError):
FK5(equinox=J2001).transform_to(ICRS)

# To actually define a new transformation, the same scheme as in the
Expand All @@ -306,8 +306,8 @@ class SomeNewSystem(BaseCoordinateFrame):

@frame_transform_graph.transform(DynamicMatrixTransform, SomeNewSystem, FK5)
def new_to_fk5(newobj, fk5frame):
ot = newobj.obstime
eq = fk5frame.equinox
_ = newobj.obstime
_ = fk5frame.equinox
# ... build a *cartesian* transform matrix using `eq` that transforms from
# the `newobj` frame as observed at `ot` to FK5 an equinox `eq`
matrix = np.eye(3)
Expand Down Expand Up @@ -417,8 +417,10 @@ def test_highlevel_api():
# assert str(m31icrs) == '<SkyCoord (ICRS) RA=10.68471 deg, Dec=41.26875 deg>'

if HAS_SCIPY:
cat1 = coords.SkyCoord(ra=[1, 2]*u.hr, dec=[3, 4.01]*u.deg, distance=[5, 6]*u.kpc, frame='icrs')
cat2 = coords.SkyCoord(ra=[1, 2, 2.01]*u.hr, dec=[3, 4, 5]*u.deg, distance=[5, 200, 6]*u.kpc, frame='icrs')
cat1 = coords.SkyCoord(ra=[1, 2]*u.hr, dec=[3, 4.01]*u.deg,
distance=[5, 6]*u.kpc, frame='icrs')
cat2 = coords.SkyCoord(ra=[1, 2, 2.01]*u.hr, dec=[3, 4, 5]*u.deg,
distance=[5, 200, 6]*u.kpc, frame='icrs')
idx1, sep2d1, dist3d1 = cat1.match_to_catalog_sky(cat2)
idx2, sep2d2, dist3d2 = cat1.match_to_catalog_3d(cat2)

Expand Down
10 changes: 4 additions & 6 deletions astropy/coordinates/tests/test_distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,10 @@
from astropy.units import allclose as quantity_allclose
from astropy.coordinates import Longitude, Latitude, Distance, CartesianRepresentation
from astropy.coordinates.builtin_frames import ICRS, Galactic
from astropy.tests.helper import catch_warnings
from astropy.utils.exceptions import AstropyWarning

try:
import scipy # pylint: disable=W0611
import scipy # pylint: disable=W0611 # noqa
except ImportError:
HAS_SCIPY = False
else:
Expand Down Expand Up @@ -51,6 +50,7 @@ def test_distances():
# 3D position
c = Galactic(l=158.558650*u.degree, b=-43.350066*u.degree,
distance=Distance(12, u.parsec))
assert quantity_allclose(c.distance, 12 * u.pc)

# or initialize distances via redshifts - this is actually tested in the
# function below that checks for scipy. This is kept here as an example
Expand Down Expand Up @@ -233,13 +233,11 @@ def test_parallax():
with pytest.raises(ValueError):
Distance(parallax=[10, 1, -1] * u.mas)

with catch_warnings(AstropyWarning) as w:
with pytest.warns(AstropyWarning):
Distance(parallax=-1 * u.mas, allow_negative=True)
assert len(w) > 0

with catch_warnings(AstropyWarning) as w:
with pytest.warns(AstropyWarning):
Distance(parallax=[10, 1, -1] * u.mas, allow_negative=True)
assert len(w) > 0


def test_distance_in_coordinates():
Expand Down
9 changes: 3 additions & 6 deletions astropy/coordinates/tests/test_frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
import pytest

from astropy import units as u
from astropy.tests.helper import (catch_warnings,
assert_quantity_allclose as assert_allclose)
from astropy.tests.helper import assert_quantity_allclose as assert_allclose
from astropy.utils import OrderedDescriptorContainer
from astropy.utils.exceptions import AstropyWarning
from astropy.coordinates import representation as r
Expand Down Expand Up @@ -821,11 +820,9 @@ def test_represent_as():
assert isinstance(rep2.differentials['s'], r.CylindricalDifferential)

# single class with positional in_frame_units, verify that warning raised
with catch_warnings() as w:
with pytest.warns(AstropyWarning, match='argument position') as w:
icrs.represent_as(r.CylindricalRepresentation, False)
assert len(w) == 1
assert w[0].category == AstropyWarning
assert 'argument position' in str(w[0].message)
assert len(w) == 1
Comment thread
mhvk marked this conversation as resolved.
Resolved

# TODO: this should probably fail in the future once we figure out a better
# workaround for dealing with UnitSphericalRepresentation's with
Expand Down
26 changes: 9 additions & 17 deletions astropy/coordinates/tests/test_iau_fullstack.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
from astropy.coordinates.builtin_frames.utils import get_jd12
from astropy.coordinates import EarthLocation
from astropy.coordinates import SkyCoord
from astropy.tests.helper import catch_warnings
from astropy import _erfa as erfa
from astropy.utils import iers
from .utils import randomly_sample_sphere
Expand Down Expand Up @@ -164,26 +163,19 @@ def test_future_altaz():
if hasattr(utils, '__warningregistry__'):
utils.__warningregistry__.clear()

with catch_warnings() as found_warnings:

location = EarthLocation(lat=0*u.deg, lon=0*u.deg)
t = Time('J2161')

SkyCoord(1*u.deg, 2*u.deg).transform_to(AltAz(location=location, obstime=t))
location = EarthLocation(lat=0*u.deg, lon=0*u.deg)
t = Time('J2161')
Comment thread
mhvk marked this conversation as resolved.
Resolved

# check that these message(s) appear among any other warnings. If tests are run with
# --remote-data then the IERS table will be an instance of IERS_Auto which is
# assured of being "fresh". In this case getting times outside the range of the
# table does not raise an exception. Only if using IERS_B (which happens without
# --remote-data, i.e. for all CI testing) do we expect another warning.
messages_to_find = ["Tried to get polar motions for times after IERS data is valid."]
with pytest.warns(AstropyWarning, match=r"Tried to get polar motions for "
"times after IERS data is valid.*") as found_warnings:
SkyCoord(1*u.deg, 2*u.deg).transform_to(AltAz(location=location, obstime=t))

if isinstance(iers.earth_orientation_table.get(), iers.IERS_B):
messages_to_find.append("(some) times are outside of range covered by IERS table.")

messages_found = [False for _ in messages_to_find]
for w in found_warnings:
if issubclass(w.category, AstropyWarning):
for i, message_to_find in enumerate(messages_to_find):
if message_to_find in str(w.message):
messages_found[i] = True
assert all(messages_found)
messages_found = ["(some) times are outside of range covered by IERS "

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mhvk , I tried to simplify the logic here but you might want to double check.

"table." in str(w.message) for w in found_warnings]
assert any(messages_found)
25 changes: 11 additions & 14 deletions astropy/coordinates/tests/test_regression.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
place to live
"""


import io
import copy
import pytest
Expand All @@ -28,7 +27,7 @@
from astropy.utils import iers
from astropy.table import Table

from astropy.tests.helper import assert_quantity_allclose, catch_warnings
from astropy.tests.helper import assert_quantity_allclose
from .test_matching import HAS_SCIPY
from astropy.units import allclose as quantity_allclose

Expand Down Expand Up @@ -209,6 +208,7 @@ def test_regression_futuretimes_4302():

Relevant comment: https://github.com/astropy/astropy/pull/4302#discussion_r44836531
"""
from astropy.utils.compat.context import nullcontext
from astropy.utils.exceptions import AstropyWarning

# this is an ugly hack to get the warning to show up even if it has already
Expand All @@ -217,25 +217,22 @@ def test_regression_futuretimes_4302():
if hasattr(utils, '__warningregistry__'):
utils.__warningregistry__.clear()

with catch_warnings() as found_warnings:
future_time = Time('2511-5-1')
c = CIRS(1*u.deg, 2*u.deg, obstime=future_time)
c.transform_to(ITRS(obstime=future_time))

# check that out-of-range warning appears among any other warnings. If
# tests are run with --remote-data then the IERS table will be an instance
# of IERS_Auto which is assured of being "fresh". In this case getting
# times outside the range of the table does not raise an exception. Only
# if using IERS_B (which happens without --remote-data, i.e. for all CI
# testing) do we expect another warning.
if isinstance(iers.earth_orientation_table.get(), iers.IERS_B):
saw_iers_warnings = False
for w in found_warnings:
if issubclass(w.category, AstropyWarning):
if '(some) times are outside of range covered by IERS table' in str(w.message):
saw_iers_warnings = True
break
assert saw_iers_warnings, 'Never saw IERS warning'
ctx = pytest.warns(
AstropyWarning,
match=r'\(some\) times are outside of range covered by IERS table.*')
else:
ctx = nullcontext()
with ctx:
future_time = Time('2511-5-1')
c = CIRS(1*u.deg, 2*u.deg, obstime=future_time)
c.transform_to(ITRS(obstime=future_time))


def test_regression_4996():
Expand Down
Loading