Skip to content

MNT: Stop using our own catch_warnings and raises - #10504

Merged
pllim merged 28 commits into
astropy:masterfrom
pllim:no-catch-warnings
Jul 2, 2020
Merged

pllim merged 28 commits into
astropy:masterfrom
pllim:no-catch-warnings

Conversation

@pllim

@pllim pllim commented Jun 17, 2020 •

Copy link
Copy Markdown
Member

Description

This pull request is to replace our own catch_warnings with standard pytest stuff. This addresses most of #6761 but not going to deprecate anything.

Also see https://docs.pytest.org/en/stable/warnings.html . pytest was at 5.4.1 when this PR was opened.

As for deprecation warning, local testing indicates that it will bubble through and be caught by filterwarnings = error in setup.cfg even without our own catch_warnings.

Similarly, our own raises can be replaced with pytest.raises.

TODO

  • Why astropy/coordinates/tests/test_iau_fullstack.py:180 and astropy/coordinates/tests/test_regression.py:229 try to access internet on CI? I thought we already set auto_download=False. Maybe problem will fix itself after Remove unnecessary remote_data in (mostly) coordinates. #10474 is merged?
  • Fix message being caught in astropy/io/ascii/tests/test_ecsv.py:479 when pyyaml is not installed.
  • Replace catch_warnings usage in remaining tests:
    • astropy/units/tests/test_format.py
    • astropy/units/tests/test_quantity_ufuncs.py
    • astropy/units/tests/test_equivalencies.py
    • astropy/units/tests/test_quantity.py
    • astropy/utils/iers/tests/test_iers.py
    • astropy/utils/tests/test_decorators.py
    • astropy/utils/tests/test_data.py (this should be its own commit in case it conflicts with Lock-free cache implementation #10437)
    • astropy/visualization/wcsaxes/tests/test_misc.py
    • astropy/visualization/wcsaxes/tests/test_wcsapi.py (false positive)
    • astropy/wcs/tests/test_wcs.py
    • astropy/wcs/tests/test_wcsprm.py
    • astropy/wcs/tests/test_utils.py
    • astropy/wcs/tests/test_profiling.py
    • astropy/wcs/wcsapi/tests/test_fitswcs.py (false positive)
    • astropy/wcs/wcsapi/wrappers/tests/test_sliced_wcs.py (false positive)
  • Since this might drag on for a while, might need to grep again towards the end to make sure no new catch_warnings snuck in upstream in the meanwhile.
    • Tip: Add a raise RuntimeError in raise.__enter__ and catch_warnings.__enter__ to make sure nothing besides fitscheck.py is using them.
  • Hmm, what about astropy.tests.helper.raises?
  • Make sure tests pass, even the remote data job that is allowed to fail.

p.s. Oh dear, I didn't realize I was going to touch so many lines. Initial grep-fu failed me and I underestimated the impact. If this sits too long and conflicts start to creep in, this PR might need to be broken down into smaller pieces that can be merged faster. Or someone can come do a mega-review quick and get this in sooner than later. 😬

@mhvk mhvk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Yes, nice! Nitpicks only.

Comment thread astropy/coordinates/tests/test_distance.py Outdated
Comment thread astropy/coordinates/tests/test_distance.py Outdated
Comment thread astropy/coordinates/tests/test_frames.py
Comment thread astropy/coordinates/tests/test_iau_fullstack.py Outdated
Comment thread astropy/coordinates/tests/test_distance.py Outdated
Comment thread astropy/coordinates/tests/test_iau_fullstack.py
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.

altaz_auto = sc.transform_to(altaz)

assert len(w) == 0
altaz_auto = sc.transform_to(altaz)

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.

Note: Now that we turn all warnings into errors, except for the ones we explicitly ignore, check for zero warning is no longer necessary.

values = np.array([1.01e200, np.inf, np.inf, 0.0, -np.inf])
with catch_warnings(AstropyWarning) as w:
# NOTE: Warning behavior varies for the parameters being passed in.
with pytest.warns(None) as w:

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.

This test file is a tricky one. nullcontext doesn't work and too strict a warns catching doesn't work either; must be due to weird interactions between pyx and pure Python. 🤷

At least this way, I think I didn't change the original intent of the tests.

Comment thread astropy/io/ascii/tests/test_c_reader.py
Comment thread astropy/io/ascii/tests/test_c_reader.py
assert isinstance(t2['l'].unit, u.UnrecognizedUnit)
assert str(t2['l'].unit) == 'bandpass_sol_lum'
if table_cls is QTable:
assert len(w) == 1

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.

For whatever reason, catch_warnings did not see the ResourceWarning but pytest.warns did. 🤷

Comment thread docs/development/testguide.rst Outdated
@pllim

This comment has been minimized.

@pllim
pllim force-pushed the no-catch-warnings branch 2 times, most recently from 9ab3457 to d62b324 Compare June 25, 2020 21:35
@pllim pllim changed the title MNT: Stop using our own catch_warnings MNT: Stop using our own catch_warnings and raises Jun 25, 2020
@pllim

pllim commented Jun 30, 2020

Copy link
Copy Markdown
Member Author

I was wondering mostly as an easy way for us to know that we are regressing

Yes, it is a risk we have to take until we're ready to issue that deprecation warning. I removed mention of it from dev docs, so hopefully that would reduce the risk but it is not foolproof. :(

@pllim
pllim force-pushed the no-catch-warnings branch from 23cc99a to f467c4a Compare June 30, 2020 21:47
@pllim

pllim commented Jun 30, 2020

Copy link
Copy Markdown
Member Author

not quite clear what the status is

Update: I undid my damage to wcs tests. Should be good for review now.

@pytest.mark.skipif(not HAS_BZ2, reason='Python built without bz2 module')
def test_detect_bzipped(self):
"""Test detection of a bzip2 file when the extension is not .bz2."""
with ignore_warnings():

@pllim pllim Jul 1, 2020 •

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.

Note: I don't know why warnings were ignored blindly and turns out they are not necessary anyway.

with pytest.raises(OSError):
fits.open(filename, ignore_missing_end=True)
with pytest.raises(OSError):
fits.open(filename, ignore_missing_end=False)

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.

Note: The diff is a bit misleading. All I did was un-indent after removing with catch_warnings(ResourceWarning) as ws because that catch is now unnecessary.

Comment thread setup.cfg

@mhvk mhvk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks all good, especially the cases where you found ignoring warnings was not even necessary! I also think the pytest.warns(None) as w trick is actually quite nice, maybe even better than the null context (obviously, no need to adjust!), and nice to have it mentioned in the test guide. Thanks so much for doing this huge cleanup!!

Only item left would seem to get an answer to https://github.com/astropy/astropy/pull/10504/files#r446478186, plus a few really small items if you have the energy. None feel necessary, so I am approving - would definitely be good to merge sooner rather than later!

diffobj = HeaderDiff(ha, hb)
diffobj.report(fileobj=outpath)
with catch_warnings(AstropyDeprecationWarning) as warning_lines:
with pytest.warns(AstropyDeprecationWarning, match=r'"clobber" was '

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Probably OK to remove now, but a separate issue!

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.

If you mean removing clobber from API, I cannot find an issue for it though it was a bit controversial when the deprecation happen. It was truly deprecated in #6203 (v2.0). @saimn , do you think it is safe to finally remove now? Or is this one of those we just keep around deprecated forever. This is FITS, after all.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I would vote to keep it forever ;)

Comment thread astropy/io/misc/tests/test_hdf5.py Outdated
t1 = Table()
t1.add_column(Column(name='a', data=[1, 2, 3]))
with pytest.raises(ValueError) as exc:
with pytest.warns(UserWarning, match="table path was not set via the path= argument"):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Yes, surely this was just a copy & paste paste error

Comment thread astropy/io/misc/tests/test_yaml.py
def test_oversize_unicode():
config = {'verify': 'exception'}
with catch_warnings(exceptions.W46) as w:
with pytest.raises(exceptions.W47):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Weird, how did catch_warnings manage to pass?


assert_quantity_allclose(b_fit.temperature, 2840.7438339457754 * u.K)
assert_quantity_allclose(b_fit.bolometric_flux, 6.821837075583734e-08 * u.erg / u.cm**2 / u.s)
assert_quantity_allclose(b_fit.bolometric_flux, 6.821837075583734e-08 * u.erg / u.cm**2 / u.s) # noqa

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Another weird noqa one...

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.

Line too long, but maybe I should just fix it...

Comment thread astropy/modeling/tests/test_constraints.py
Comment thread astropy/table/tests/test_table.py Outdated
assert w[0].category is table.TableReplaceWarning
assert 'test_table' in w[0].filename
# Make sure the warning points back to the user code line
assert w[0].lineno == frameinfo.lineno + 2

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think it is simply because you now inserted the with statement in between. This perhaps is one case where it makes sense to get the frame inside it, but no need unless you are editing anyway.

Comment thread astropy/utils/iers/tests/test_iers.py Outdated
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.value)
with pytest.warns(iers.IERSStaleWarning, match='IERS_Auto predictive values are older') as warns, pytest.raises(ValueError, match='interpolating from IERS_Auto using predictive values'): # noqa

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Would be nice to break the line (if you are doing another round...)

Comment thread setup.cfg
Comment thread astropy/io/votable/tests/converter_test.py
@pllim

pllim commented Jul 1, 2020

Copy link
Copy Markdown
Member Author

@mhvk , I think I applied all the code changes you asked for and hopefully answer all your questions/concerns. Please let me know if I missed anything. Thank you so much for doing the mega-review!

@pllim

pllim commented Jul 1, 2020

Copy link
Copy Markdown
Member Author

As for pytest.warns(None) vs nullcontext, these two example below should be equivalent:

with pytest.warns(None) as w:
    some_code()
assert len(w) == 0
with nullcontext():
    some_code()

Therefore, I think pytest.warns(None) should be used when you want to blindly catch any warnings and nullcontext is for when you don't want any warnings at all.

@mhvk

mhvk commented Jul 1, 2020

Copy link
Copy Markdown
Contributor

Yes, I think this can (and should!) go in, once tests have passed.

And the nullcontext vs None makes sense.

@mhvk mhvk added the zzz 💤 merge-when-ci-passes Do not use: We have auto-merge option now. label Jul 1, 2020
@pllim

pllim commented Jul 2, 2020

Copy link
Copy Markdown
Member Author

Given the approval, I'll go ahead and merge then before I need to rebase (again). Codecov failure can be ignored. Thank you so much for the review!

@pllim
pllim merged commit 1f75aa1 into astropy:master Jul 2, 2020
@pllim
pllim deleted the no-catch-warnings branch July 2, 2020 02:39
astrofrog added a commit to astrofrog/astropy that referenced this pull request Aug 3, 2020
…ng in WCSAxes tests to not be sensitive to unrelated warnings
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants