Skip to content

Commit

Permalink
fix: ruff pt012 violations
Browse files Browse the repository at this point in the history
  • Loading branch information
paverett committed Mar 5, 2024
1 parent d32a06a commit fb732a3
Show file tree
Hide file tree
Showing 43 changed files with 184 additions and 152 deletions.
1 change: 0 additions & 1 deletion .ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,6 @@ lint.ignore = [
"PT006", # pytest-parametrize-names-wrong-type
"PT007", # pytest-parametrize-values-wrong-type
"PT011", # pytest-raises-too-broad
"PT012", # pytest-raises-with-multiple-statements
"PT017", # pytest-assert-in-exceptinstead
"PT018", # pytest-composite-assertion
"PT022", # pytest-useless-yield-fixture
Expand Down
4 changes: 2 additions & 2 deletions astropy/convolution/tests/test_convolve_fft.py
Original file line number Diff line number Diff line change
Expand Up @@ -787,12 +787,12 @@ def test_big_fail(self):
Test that convolve_fft raises an exception if a too-large array is passed in.
"""

# note 512**3 * 16 bytes = 2.0 GB
arr = np.empty([512, 512, 512], dtype=complex)
with pytest.raises((ValueError, MemoryError)):
# while a good idea, this approach did not work; it actually writes to disk
# arr = np.memmap('file.np', mode='w+', shape=(512, 512, 512), dtype=complex)
# this just allocates the memory but never touches it; it's better:
arr = np.empty([512, 512, 512], dtype=complex)
# note 512**3 * 16 bytes = 2.0 GB
convolve_fft(arr, arr)

def test_padding(self):
Expand Down
14 changes: 13 additions & 1 deletion astropy/convolution/tests/test_kernel_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,8 +578,8 @@ def test_kernel_normalization_mode(self):
"""
Test that an error is raised if mode is invalid.
"""
kernel = CustomKernel(np.ones(3))
with pytest.raises(ValueError):
kernel = CustomKernel(np.ones(3))
kernel.normalize(mode="invalid")

def test_kernel1d_int_size(self):
Expand Down Expand Up @@ -629,15 +629,27 @@ def test_array_keyword_not_allowed(self):
x = np.ones([10, 10])
with pytest.raises(TypeError, match=r".* allowed .*"):
AiryDisk2DKernel(2, array=x)
with pytest.raises(TypeError, match=r".* allowed .*"):
Box1DKernel(2, array=x)
with pytest.raises(TypeError, match=r".* allowed .*"):
Box2DKernel(2, array=x)
with pytest.raises(TypeError, match=r".* allowed .*"):
Gaussian1DKernel(2, array=x)
with pytest.raises(TypeError, match=r".* allowed .*"):
Gaussian2DKernel(2, array=x)
with pytest.raises(TypeError, match=r".* allowed .*"):
RickerWavelet1DKernel(2, array=x)
with pytest.raises(TypeError, match=r".* allowed .*"):
RickerWavelet2DKernel(2, array=x)
with pytest.raises(TypeError, match=r".* allowed .*"):
Model1DKernel(Gaussian1D(1, 0, 2), array=x)
with pytest.raises(TypeError, match=r".* allowed .*"):
Model2DKernel(Gaussian2D(1, 0, 0, 2, 2), array=x)
with pytest.raises(TypeError, match=r".* allowed .*"):
Ring2DKernel(9, 8, array=x)
with pytest.raises(TypeError, match=r".* allowed .*"):
Tophat2DKernel(2, array=x)
with pytest.raises(TypeError, match=r".* allowed .*"):
Trapezoid1DKernel(2, array=x)
with pytest.raises(TypeError, match=r".* allowed .*"):
Trapezoid1DKernel(2, array=x)
12 changes: 6 additions & 6 deletions astropy/coordinates/tests/test_angles.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,18 +737,18 @@ def test_latitude():
assert type(angle) is Angle
assert angle == -80 * u.deg

lon = Longitude(10, "deg")
# Test errors when trying to interoperate with longitudes.
with pytest.raises(
TypeError, match="A Latitude angle cannot be created from a Longitude angle"
):
lon = Longitude(10, "deg")
Latitude(lon)

lon = Longitude(10, "deg")
lat = Latitude([20], "deg")
with pytest.raises(
TypeError, match="A Longitude angle cannot be assigned to a Latitude angle"
):
lon = Longitude(10, "deg")
lat = Latitude([20], "deg")
lat[0] = lon

# Check we can work around the Lat vs Long checks by casting explicitly to Angle.
Expand Down Expand Up @@ -840,18 +840,18 @@ def test_longitude():
assert Longitude(0, u.deg, dtype=float).dtype == np.dtype(float)
assert Longitude(0, u.deg, dtype=int).dtype == np.dtype(int)

lat = Latitude(10, "deg")
# Test errors when trying to interoperate with latitudes.
with pytest.raises(
TypeError, match="A Longitude angle cannot be created from a Latitude angle"
):
lat = Latitude(10, "deg")
Longitude(lat)

lat = Latitude(10, "deg")
lon = Longitude([20], "deg")
with pytest.raises(
TypeError, match="A Latitude angle cannot be assigned to a Longitude angle"
):
lat = Latitude(10, "deg")
lon = Longitude([20], "deg")
lon[0] = lat

# Check we can work around the Lat vs Long checks by casting explicitly to Angle.
Expand Down
2 changes: 1 addition & 1 deletion astropy/coordinates/tests/test_arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,8 @@ def test_array_len():

assert c.shape == (length,)

c = ICRS(0 * u.deg, 0 * u.deg)
with pytest.raises(TypeError):
c = ICRS(0 * u.deg, 0 * u.deg)
len(c)

assert c.shape == ()
Expand Down
12 changes: 6 additions & 6 deletions astropy/coordinates/tests/test_earth.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,13 +393,13 @@ def test_gravitational_redshift():
with pytest.raises(KeyError):
someloc.gravitational_redshift(sometime, bodies=("saturn",))

masses = {
"sun": constants.G * constants.M_sun,
"jupiter": constants.G * constants.M_jup,
"moon": 1 * u.km, # wrong units!
"earth": constants.G * constants.M_earth,
}
with pytest.raises(u.UnitsError):
masses = {
"sun": constants.G * constants.M_sun,
"jupiter": constants.G * constants.M_jup,
"moon": 1 * u.km, # wrong units!
"earth": constants.G * constants.M_earth,
}
someloc.gravitational_redshift(sometime, masses=masses)


Expand Down
2 changes: 1 addition & 1 deletion astropy/coordinates/tests/test_frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,8 +224,8 @@ def test_create_orderered_data():
with pytest.raises(TypeError):
ICRS(1 * u.deg, 2 * u.deg, 1 * u.deg, 2 * u.deg)

sph = r.SphericalRepresentation(1 * u.deg, 2 * u.deg, 3 * u.kpc)
with pytest.raises(TypeError):
sph = r.SphericalRepresentation(1 * u.deg, 2 * u.deg, 3 * u.kpc)
ICRS(sph, 1 * u.deg, 2 * u.deg)


Expand Down
5 changes: 1 addition & 4 deletions astropy/cosmology/_io/tests/test_latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import pytest

from astropy.cosmology._io.latex import _FORMAT_TABLE, write_latex
from astropy.io.registry.base import IORegistryError
from astropy.table import QTable, Table

from .base import ReadWriteDirectTestBase, ReadWriteTestMixinBase
Expand Down Expand Up @@ -58,9 +57,7 @@ def test_write_latex_unsupported_format(self, write, tmp_path):
"""Test for unsupported format"""
fp = tmp_path / "test_write_latex_unsupported_format.tex"
invalid_format = "unsupported"
with pytest.raises((ValueError, IORegistryError)) as exc_info:
pytest.raises(ValueError, match="format must be 'ascii.latex'")
pytest.raises(IORegistryError, match="No writer defined for format")
with pytest.raises(ValueError, match="format must be 'ascii.latex'"):
write(fp, format=invalid_format)


Expand Down
2 changes: 0 additions & 2 deletions astropy/cosmology/flrw/tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1019,8 +1019,6 @@ class HASOde0SubClass(cosmo_cls):
def __init__(self, Ode0):
pass

_COSMOLOGY_CLASSES.pop(HASOde0SubClass.__qualname__, None)

# ---------------------------------------------------------------
# instance-level

Expand Down
6 changes: 3 additions & 3 deletions astropy/io/ascii/tests/test_c_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -866,22 +866,22 @@ def test_rdb(read_rdb):
assert table["B"].dtype.kind in ("S", "U")
assert_equal(table["C"].dtype.kind, "f")

text = "A\tB\tC\nN\tS\tN\n4\tb\ta" # C column contains non-numeric data
with pytest.raises(ValueError) as e:
text = "A\tB\tC\nN\tS\tN\n4\tb\ta" # C column contains non-numeric data
read_rdb(
text,
)
assert "Column C failed to convert" in str(e.value)

text = "A\tB\tC\nN\tN\n1\t2\t3" # not enough types specified
with pytest.raises(ValueError) as e:
text = "A\tB\tC\nN\tN\n1\t2\t3" # not enough types specified
read_rdb(
text,
)
assert "mismatch between number of column names and column types" in str(e.value)

text = "A\tB\tC\nN\tN\t5\n1\t2\t3" # invalid type for column C
with pytest.raises(ValueError) as e:
text = "A\tB\tC\nN\tN\t5\n1\t2\t3" # invalid type for column C
read_rdb(
text,
)
Expand Down
2 changes: 1 addition & 1 deletion astropy/io/ascii/tests/test_write.py
Original file line number Diff line number Diff line change
Expand Up @@ -703,8 +703,8 @@ def test_commented_header_comments(fast_writer):
for the commented_header writer.
"""
t = table.Table([[1, 2]])
out = StringIO()
with pytest.raises(ValueError) as err:
out = StringIO()
ascii.write(
t, out, format="commented_header", comment=False, fast_writer=fast_writer
)
Expand Down
6 changes: 5 additions & 1 deletion astropy/io/fits/scripts/fitscheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@

log = logging.getLogger("fitscheck")

PROG = "fitscheck"

DESCRIPTION = """
e.g. fitscheck example.fits
Expand All @@ -68,7 +70,9 @@ def handle_options(args):
args = ["-h"]

parser = argparse.ArgumentParser(
description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter
prog=PROG,
description=DESCRIPTION,
formatter_class=argparse.RawDescriptionHelpFormatter,
)

parser.add_argument(
Expand Down
2 changes: 2 additions & 0 deletions astropy/io/fits/scripts/fitsdiff.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

log = logging.getLogger("fitsdiff")

PROG = "fitsdiff"

DESCRIPTION = """
Compare two FITS image files and report the differences in header keywords and
Expand Down Expand Up @@ -95,6 +96,7 @@ def __call__(self, parser, namespace, values, option_string=None):

def handle_options(argv=None):
parser = argparse.ArgumentParser(
prog=PROG,
description=DESCRIPTION,
epilog=EPILOG,
formatter_class=argparse.RawDescriptionHelpFormatter,
Expand Down
6 changes: 5 additions & 1 deletion astropy/io/fits/scripts/fitsheader.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@
from astropy import __version__, log
from astropy.io import fits

PROG = "fitsheader"

DESCRIPTION = """
Print the header(s) of a FITS file. Optional arguments allow the desired
extension(s), keyword(s), and output format to be specified.
Expand Down Expand Up @@ -401,7 +403,9 @@ def print_headers_as_comparison(args):
def main(args=None):
"""This is the main function called by the `fitsheader` script."""
parser = argparse.ArgumentParser(
description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter
prog=PROG,
description=DESCRIPTION,
formatter_class=argparse.RawDescriptionHelpFormatter,
)

parser.add_argument(
Expand Down
6 changes: 5 additions & 1 deletion astropy/io/fits/scripts/fitsinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import astropy.io.fits as fits
from astropy import __version__, log

PROG = "fitsinfo"

DESCRIPTION = """
Print a summary of the HDUs in a FITS file(s).
Expand Down Expand Up @@ -55,7 +57,9 @@ def fitsinfo(filename):
def main(args=None):
"""The main function called by the `fitsinfo` script."""
parser = argparse.ArgumentParser(
description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter
prog=PROG,
description=DESCRIPTION,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"--version", action="version", version=f"%(prog)s {__version__}"
Expand Down
Loading

0 comments on commit fb732a3

Please sign in to comment.