Skip to content

Commit

Permalink
Merge pull request #2624 from mraspaud/fix-ruff
Browse files Browse the repository at this point in the history
Replace assertRaises with pytest.raises
  • Loading branch information
djhoese committed Nov 21, 2023
2 parents ace3999 + e838867 commit 6a336fa
Show file tree
Hide file tree
Showing 28 changed files with 124 additions and 92 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
exclude: '^$'
fail_fast: false
repos:
- repo: https://github.com/charliermarsh/ruff-pre-commit
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: 'v0.0.247'
rev: 'v0.1.4'
hooks:
- id: ruff
- repo: https://github.com/pre-commit/pre-commit-hooks
Expand Down
4 changes: 3 additions & 1 deletion satpy/tests/multiscene_tests/test_save_animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
from datetime import datetime
from unittest import mock

import pytest

from satpy.tests.multiscene_tests.test_utils import (
_create_test_area,
_create_test_dataset,
Expand Down Expand Up @@ -248,7 +250,7 @@ def test_save_datasets_distributed_source_target(self):
with mock.patch("satpy.multiscene._multiscene.Scene.save_datasets") as save_datasets:
save_datasets.return_value = [(source_mock, target_mock)] # some arbitrary return value
# force order of datasets by specifying them
with self.assertRaises(NotImplementedError):
with pytest.raises(NotImplementedError):
mscn.save_datasets(base_dir=self.base_dir, client=client_mock, datasets=["ds1", "ds2", "ds3"],
writer="geotiff")

Expand Down
3 changes: 2 additions & 1 deletion satpy/tests/reader_tests/test_aapp_mhs_amsub_l1c.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import unittest

import numpy as np
import pytest

from satpy.readers.aapp_mhs_amsub_l1c import _HEADERTYPE, _SCANTYPE, HEADER_LENGTH, MHS_AMSUB_AAPPL1CFile
from satpy.tests.utils import make_dataid
Expand Down Expand Up @@ -396,7 +397,7 @@ def test_sensor_name(self):
tmpfile.seek(HEADER_LENGTH, 0)
self._data.tofile(tmpfile)

with self.assertRaises(IOError):
with pytest.raises(IOError, match="Sensor neither MHS nor AMSU-B!"):
fh_ = MHS_AMSUB_AAPPL1CFile(tmpfile, self.filename_info, self.filetype_info)

def test_read(self):
Expand Down
9 changes: 5 additions & 4 deletions satpy/tests/reader_tests/test_ahi_l1b_gridded_bin.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

import dask.array as da
import numpy as np
import pytest
from pyresample.geometry import AreaDefinition

from satpy.readers.ahi_l1b_gridded_bin import AHI_LUT_NAMES, AHIGriddedFileHandler
Expand Down Expand Up @@ -90,9 +91,9 @@ def test_bad_area(self):
"""Ensure an error is raised for an usupported area."""
tmp_fh = self.make_fh("ext.01")
tmp_fh.areaname = "scanning"
with self.assertRaises(NotImplementedError):
with pytest.raises(NotImplementedError):
tmp_fh.get_area_def(None)
with self.assertRaises(NotImplementedError):
with pytest.raises(NotImplementedError):
self.make_fh("ext.01", area="scanning")


Expand Down Expand Up @@ -141,12 +142,12 @@ def test_calibrate(self, np_loadtxt, os_exist, get_luts):
np.testing.assert_allclose(refl_out, out_data)

# Check that exception is raised if bad calibration is passed
with self.assertRaises(NotImplementedError):
with pytest.raises(NotImplementedError):
self.fh.calibrate(in_data, "lasers")

# Check that exception is raised if no file is present
np_loadtxt.side_effect = FileNotFoundError
with self.assertRaises(FileNotFoundError):
with pytest.raises(FileNotFoundError):
self.fh.calibrate(in_data, "reflectance")


Expand Down
11 changes: 3 additions & 8 deletions satpy/tests/reader_tests/test_ami_l1b.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import dask.array as da
import numpy as np
import xarray as xr
from pytest import approx # noqa: PT013
from pytest import approx, raises # noqa: PT013


class FakeDataset(object):
Expand Down Expand Up @@ -198,13 +198,8 @@ def test_get_dataset(self):
def test_bad_calibration(self):
"""Test that asking for a bad calibration fails."""
from satpy.tests.utils import make_dataid
with self.assertRaises(ValueError):
ds_id = make_dataid(name="VI006", calibration="_bad_")
ds_info = {"file_key": "image_pixel_values",
"standard_name": "toa_outgoing_radiance_per_unit_wavelength",
"units": "W m-2 um-1 sr-1",
}
self.reader.get_dataset(ds_id, ds_info)
with raises(ValueError, match="_bad_ invalid value for .*"):
_ = make_dataid(name="VI006", calibration="_bad_")

@mock.patch("satpy.readers.abi_base.geometry.AreaDefinition")
def test_get_area_def(self, adef):
Expand Down
2 changes: 1 addition & 1 deletion satpy/tests/reader_tests/test_avhrr_l1b_gaclac.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def test_read_raw_data(self):
# Test exception if all data is masked
reader.mask = [1]
fh.reader = None
with self.assertRaises(ValueError):
with pytest.raises(ValueError, match="All data is masked out"):
fh.read_raw_data()

@mock.patch("satpy.readers.avhrr_l1b_gaclac.GACLACFile._update_attrs")
Expand Down
4 changes: 3 additions & 1 deletion satpy/tests/reader_tests/test_clavrx.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import dask.array as da
import numpy as np
import pytest
import xarray as xr
from pyresample.geometry import AreaDefinition, SwathDefinition

Expand Down Expand Up @@ -347,7 +348,8 @@ def test_no_nav_donor(self):
"clavrx_H08_20180806_1800.level2.hdf",
])
r.create_filehandlers(loadables)
self.assertRaises(IOError, r.load, ["variable1", "variable2", "variable3"])
with pytest.raises(IOError, match="Could not find navigation donor for"):
r.load(["variable1", "variable2", "variable3"])

def test_load_all_old_donor(self):
"""Test loading all test datasets with old donor."""
Expand Down
5 changes: 3 additions & 2 deletions satpy/tests/reader_tests/test_electrol_hrit.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import dask.array as da
import numpy as np
import pytest
from xarray import DataArray

from satpy.readers.electrol_hrit import (
Expand Down Expand Up @@ -211,8 +212,8 @@ def test_calibrate(self, *mocks):
dtype=np.uint16).reshape(5, 5))

# Test that calibration fails if given a silly mode
self.assertRaises(NotImplementedError, fh.calibrate, counts,
"nonsense")
with pytest.raises(NotImplementedError):
fh.calibrate(counts, "nonsense")

# Test that 'counts' calibration returns identical values to input
out = fh.calibrate(counts, "counts")
Expand Down
6 changes: 4 additions & 2 deletions satpy/tests/reader_tests/test_goes_imager_nc_noaa.py
Original file line number Diff line number Diff line change
Expand Up @@ -444,13 +444,15 @@ def test_get_dataset_invalid(self):
args = dict(key=make_dataid(name="00_7",
calibration="brightness_temperature"),
info={})
self.assertRaises(ValueError, self.reader.get_dataset, **args)
with pytest.raises(ValueError, match="Cannot calibrate VIS channel to 2"):
self.reader.get_dataset(**args)

# IR -> Reflectance
args = dict(key=make_dataid(name="10_7",
calibration="reflectance"),
info={})
self.assertRaises(ValueError, self.reader.get_dataset, **args)
with pytest.raises(ValueError, match="Cannot calibrate IR channel to 1"):
self.reader.get_dataset(**args)

# Unsupported calibration
with pytest.raises(ValueError, match="invalid invalid value for <enum 'calibration'>"):
Expand Down
6 changes: 4 additions & 2 deletions satpy/tests/reader_tests/test_hrit_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,12 @@ def test_xrit_cmd(self):
old_env = os.environ.get("XRIT_DECOMPRESS_PATH", None)

os.environ["XRIT_DECOMPRESS_PATH"] = "/path/to/my/bin"
self.assertRaises(IOError, get_xritdecompress_cmd)
with pytest.raises(IOError, match=".* does not exist!"):
get_xritdecompress_cmd()

os.environ["XRIT_DECOMPRESS_PATH"] = gettempdir()
self.assertRaises(IOError, get_xritdecompress_cmd)
with pytest.raises(IOError, match=".* is a directory!.*"):
get_xritdecompress_cmd()

with NamedTemporaryFile() as fd:
os.environ["XRIT_DECOMPRESS_PATH"] = fd.name
Expand Down
5 changes: 3 additions & 2 deletions satpy/tests/reader_tests/test_hy2_scat_l2b_h5.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import dask.array as da
import numpy as np
import pytest
import xarray as xr

from satpy.tests.reader_tests.test_hdf5_utils import FakeHDF5FileHandler
Expand Down Expand Up @@ -488,7 +489,7 @@ def test_reading_attrs(self):
# Make sure we have some files
res = reader.load(["wvc_lon"])
assert res["wvc_lon"].attrs["L2B_Number_WVC_cells"] == 10
with self.assertRaises(KeyError):
with pytest.raises(KeyError):
assert res["wvc_lon"].attrs["L2B_Expected_WVC_Cells"] == 10

def test_reading_attrs_nsoas(self):
Expand All @@ -502,7 +503,7 @@ def test_reading_attrs_nsoas(self):
reader.create_filehandlers(files)
# Make sure we have some files
res = reader.load(["wvc_lon"])
with self.assertRaises(KeyError):
with pytest.raises(KeyError):
assert res["wvc_lon"].attrs["L2B_Number_WVC_cells"] == 10
assert res["wvc_lon"].attrs["L2B_Expected_WVC_Cells"] == 10

Expand Down
3 changes: 2 additions & 1 deletion satpy/tests/reader_tests/test_netcdf_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import unittest

import numpy as np
import pytest

try:
from satpy.readers.netcdf_utils import NetCDF4FileHandler
Expand Down Expand Up @@ -232,7 +233,7 @@ def test_filenotfound(self):
"""Test that error is raised when file not found."""
from satpy.readers.netcdf_utils import NetCDF4FileHandler

with self.assertRaises(IOError):
with pytest.raises(IOError, match=".*No such file or directory.*"):
NetCDF4FileHandler("/thisfiledoesnotexist.nc", {}, {})

def test_get_and_cache_npxr_is_xr(self):
Expand Down
4 changes: 3 additions & 1 deletion satpy/tests/reader_tests/test_scmi.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from unittest import mock

import numpy as np
import pytest
import xarray as xr


Expand Down Expand Up @@ -273,4 +274,5 @@ def test_get_area_def_bad(self, adef):
"grid_mapping_name": "fake",
}
)
self.assertRaises(ValueError, reader.get_area_def, None)
with pytest.raises(ValueError, match="Can't handle projection 'fake'"):
reader.get_area_def(None)
4 changes: 2 additions & 2 deletions satpy/tests/reader_tests/test_seviri_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def test_pad_data_horizontally_bad_shape(self):
east_bound = 5
west_bound = 10
final_size = (1, 20)
with self.assertRaises(IndexError):
with pytest.raises(IndexError):
pad_data_horizontally(data, final_size, east_bound, west_bound)

def test_pad_data_vertically_bad_shape(self):
Expand All @@ -107,7 +107,7 @@ def test_pad_data_vertically_bad_shape(self):
south_bound = 5
north_bound = 10
final_size = (20, 1)
with self.assertRaises(IndexError):
with pytest.raises(IndexError):
pad_data_vertically(data, final_size, south_bound, north_bound)

def observation_start_time(self):
Expand Down
2 changes: 1 addition & 1 deletion satpy/tests/reader_tests/test_seviri_l1b_calibration.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def test_ir_calibrate(self):
CHANNEL_NAME, CAL_TYPE2)
xr.testing.assert_allclose(result, TBS_OUTPUT2, rtol=1E-5)

with self.assertRaises(NotImplementedError):
with pytest.raises(NotImplementedError):
self.algo.ir_calibrate(RADIANCES_OUTPUT, CHANNEL_NAME, CAL_TYPEBAD)

def test_vis_calibrate(self):
Expand Down
7 changes: 4 additions & 3 deletions satpy/tests/reader_tests/test_seviri_l1b_icare.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import dask.array as da
import numpy as np
import pytest

from satpy.readers import load_reader
from satpy.tests.reader_tests.test_hdf4_utils import FakeHDF4FileHandler
Expand Down Expand Up @@ -193,13 +194,13 @@ def _run_target():
plat, sens = _run_target()
assert plat == sat

with self.assertRaises(NameError):
file_data["/attr/Sensors"] = "BADSAT/NOSENSE"
file_data["/attr/Sensors"] = "BADSAT/NOSENSE"
with pytest.raises(NameError):
plat, sens = _run_target()

def test_bad_bandname(self):
"""Check reader raises an error if a band bandname is passed."""
with self.assertRaises(NameError):
with pytest.raises(NameError):
self.p.target(mock.MagicMock(),
mock.MagicMock(),
mock.MagicMock())._get_dsname({"name": "badband"})
Expand Down
8 changes: 5 additions & 3 deletions satpy/tests/reader_tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,10 +215,12 @@ def test_np2str(self):

# multi-element array
npbytes = np.array([npbytes, npbytes])
self.assertRaises(ValueError, hf.np2str, npbytes)
with pytest.raises(ValueError, match="Array is not a string type or is larger than 1"):
hf.np2str(npbytes)

# non-array
self.assertRaises(ValueError, hf.np2str, 5)
with pytest.raises(ValueError, match="Array is not a string type or is larger than 1"):
hf.np2str(5)

def test_get_earth_radius(self):
"""Test earth radius computation."""
Expand Down Expand Up @@ -419,7 +421,7 @@ def test_get_user_calibration_factors(self):
assert offset == 0.0

# Check that incorrect dict keys throw an error
with self.assertRaises(KeyError):
with pytest.raises(KeyError):
hf.get_user_calibration_factors("IR108", radcor_dict)


Expand Down
5 changes: 3 additions & 2 deletions satpy/tests/reader_tests/test_vii_base_nc.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from unittest import mock

import numpy as np
import pytest
import xarray as xr
from netCDF4 import Dataset

Expand Down Expand Up @@ -218,10 +219,10 @@ def test_file_reading(self):
@mock.patch("satpy.readers.vii_base_nc.tie_points_geo_interpolation")
def test_functions(self, tpgi_, tpi_):
"""Test the functions."""
with self.assertRaises(NotImplementedError):
with pytest.raises(NotImplementedError):
self.reader._perform_orthorectification(mock.Mock(), mock.Mock())

with self.assertRaises(NotImplementedError):
with pytest.raises(NotImplementedError):
self.reader._perform_calibration(mock.Mock(), mock.Mock())

# Checks that the _perform_interpolation function is correctly executed
Expand Down
3 changes: 2 additions & 1 deletion satpy/tests/reader_tests/test_vii_l1b_nc.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

import dask.array as da
import numpy as np
import pytest
import xarray as xr
from netCDF4 import Dataset

Expand Down Expand Up @@ -147,7 +148,7 @@ def test_functions(self):
assert np.all(return_variable == variable)

# invalid calibration: raises a ValueError
with self.assertRaises(ValueError):
with pytest.raises(ValueError, match="Unknown calibration invalid for dataset test"):
self.reader._perform_calibration(variable,
{"calibration": "invalid", "name": "test"})

Expand Down

0 comments on commit 6a336fa

Please sign in to comment.