Skip to content

Commit

Permalink
MNT: Replace catch_warnings in coordinates tests.
Browse files Browse the repository at this point in the history
Apply coordinates comments from @mhvk.

Fix regex for warning messages.
  • Loading branch information
pllim committed Jun 30, 2020
1 parent 2718912 commit 10391d2
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 70 deletions.
6 changes: 3 additions & 3 deletions astropy/_erfa/tests/test_erfa.py
Expand Up @@ -110,16 +110,16 @@ def test_errwarn_reporting():
erfa.dat(1990, 1, 1, 0.5)

# check warning is raised for a scalar
with pytest.warns(erfa.ErfaWarning, match='1 of "dubious year (Note 1)"') 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

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

with pytest.raises(erfa.ErfaError, match='1 of "bad day (Note 3)", 1 of "bad month"'):
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)

with pytest.raises(erfa.ErfaError) as e:
Expand Down
4 changes: 2 additions & 2 deletions astropy/config/tests/test_configs.py
Expand Up @@ -374,8 +374,8 @@ def test_alias_read(self):

with pytest.warns(
AstropyDeprecationWarning,
match="Config parameter 'name_resolve_timeout' in section "
"[coordinates.name_resolve]") as w:
match=r"Config parameter 'name_resolve_timeout' in section "
r"\[coordinates.name_resolve\].*") as w:
conf.reload()
assert conf.remote_timeout == 42

Expand Down
10 changes: 4 additions & 6 deletions astropy/coordinates/tests/test_distance.py
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
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

# 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
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')

# 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 "
"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
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
52 changes: 30 additions & 22 deletions astropy/coordinates/tests/test_transformations.py
Expand Up @@ -10,10 +10,10 @@
from astropy.coordinates.builtin_frames import ICRS, FK5, FK4, FK4NoETerms, Galactic, AltAz
from astropy.coordinates import representation as r
from astropy.coordinates.baseframe import frame_transform_graph
from astropy.tests.helper import (assert_quantity_allclose as assert_allclose,
catch_warnings)
from astropy.tests.helper import assert_quantity_allclose as assert_allclose
from astropy.time import Time
from astropy.units import allclose as quantity_allclose
from astropy.utils.exceptions import AstropyWarning


# Coordinates just for these tests.
Expand All @@ -33,10 +33,11 @@ def test_transform_classes():
"""
Tests the class-based/OO syntax for creating transforms
"""
def tfun(c, f):
return f.__class__(ra=c.ra, dec=c.dec)

tfun = lambda c, f: f.__class__(ra=c.ra, dec=c.dec)
trans1 = t.FunctionTransform(tfun, TCoo1, TCoo2,
register_graph=frame_transform_graph)
_ = t.FunctionTransform(tfun, TCoo1, TCoo2,
register_graph=frame_transform_graph)

c1 = TCoo1(ra=1*u.radian, dec=0.5*u.radian)
c2 = c1.transform_to(TCoo2)
Expand Down Expand Up @@ -321,7 +322,7 @@ def test_affine_transform_fail(transfunc):
trans.register(frame_transform_graph)

with pytest.raises(ValueError):
c2 = c.transform_to(TCoo2)
c.transform_to(TCoo2)

trans.unregister(frame_transform_graph)

Expand All @@ -344,7 +345,7 @@ def test_too_many_differentials():
c = TCoo1(rep.without_differentials())
c._data = c._data.with_differentials({'s': dif1, 's2': dif2})
with pytest.raises(ValueError):
c2 = c.transform_to(TCoo2)
c.transform_to(TCoo2)

trans.unregister(frame_transform_graph)

Expand Down Expand Up @@ -420,17 +421,18 @@ def test_vel_transformation_obstime_err():


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)
def tfun(c, f):
return f.__class__(ra=c.ra, dec=c.dec)

_ = 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)
with pytest.warns(AstropyWarning, match=r'.*they have been dropped.*') as w:
t3.transform_to(TCoo2)
assert len(w) == 1


def test_frame_override_component_with_attribute():
Expand Down Expand Up @@ -490,9 +492,9 @@ class BFrame(BaseCoordinateFrame):
t4.register(frame_transform_graph)

c = Galactic(123*u.deg, 45*u.deg)
c1 = c.transform_to(BFrame) # direct
c2 = c.transform_to(AFrame).transform_to(BFrame) # thru A
c3 = c.transform_to(ICRS).transform_to(BFrame) # thru ICRS
c1 = c.transform_to(BFrame) # direct
c2 = c.transform_to(AFrame).transform_to(BFrame) # thru A
c3 = c.transform_to(ICRS).transform_to(BFrame) # thru ICRS

assert quantity_allclose(c1.lon, c2.lon)
assert quantity_allclose(c1.lat, c2.lat)
Expand All @@ -512,11 +514,13 @@ class MultipleAliasesFrame(BaseCoordinateFrame):
name = ['alias_1', 'alias_2']
default_representation = r.SphericalRepresentation

def tfun(c, f):
return f.__class__(lon=c.lon, lat=c.lat)

# Register a transform
graph = t.TransformGraph()
tfun = lambda c, f: f.__class__(lon=c.lon, lat=c.lat)
ftrans = t.FunctionTransform(tfun, MultipleAliasesFrame, MultipleAliasesFrame,
register_graph=graph)
_ = t.FunctionTransform(tfun, MultipleAliasesFrame, MultipleAliasesFrame,
register_graph=graph)

# Test that both aliases have been added to the transform graph
assert graph.lookup_name('alias_1') == MultipleAliasesFrame
Expand All @@ -528,9 +532,11 @@ class MultipleAliasesFrame(BaseCoordinateFrame):


def test_remove_transform_and_unregister():
def tfun(c, f):
f.__class__(ra=c.ra, dec=c.dec)

# Register transforms
graph = t.TransformGraph()
tfun = lambda c, f: f.__class__(ra=c.ra, dec=c.dec)
ftrans1 = t.FunctionTransform(tfun, TCoo1, TCoo1, register_graph=graph)
ftrans2 = t.FunctionTransform(tfun, TCoo2, TCoo2, register_graph=graph)
_ = t.FunctionTransform(tfun, TCoo1, TCoo2, register_graph=graph)
Expand Down Expand Up @@ -558,8 +564,10 @@ def test_remove_transform_and_unregister():


def test_remove_transform_errors():
def tfun(c, f):
return f.__class__(ra=c.ra, dec=c.dec)

graph = t.TransformGraph()
tfun = lambda c, f: f.__class__(ra=c.ra, dec=c.dec)
_ = t.FunctionTransform(tfun, TCoo1, TCoo1, register_graph=graph)

# Test bad calls to remove_transform
Expand Down

0 comments on commit 10391d2

Please sign in to comment.