Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 3 additions & 3 deletions lib/iris/tests/_shared_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -926,19 +926,19 @@ class MyGeoTiffTests(test.IrisTest):

skip_sample_data = pytest.mark.skipif(
not SAMPLE_DATA_AVAILABLE,
('Test(s) require "iris-sample-data", ' "which is not available."),
reason=('Test(s) require "iris-sample-data", ' "which is not available."),
)


skip_nc_time_axis = pytest.mark.skipif(
not NC_TIME_AXIS_AVAILABLE,
'Test(s) require "nc_time_axis", which is not available.',
reason='Test(s) require "nc_time_axis", which is not available.',
)


skip_inet = pytest.mark.skipif(
not INET_AVAILABLE,
('Test(s) require an "internet connection", ' "which is not available."),
reason=('Test(s) require an "internet connection", ' "which is not available."),
)


Expand Down
31 changes: 15 additions & 16 deletions lib/iris/tests/unit/plot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,18 @@
# See LICENSE in the root of the repository for full licensing details.
"""Unit tests for the :mod:`iris.plot` module."""

# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests # isort:skip
import pytest

from iris.coords import AuxCoord
from iris.plot import _broadcast_2d as broadcast
from iris.tests import _shared_utils
from iris.tests.stock import lat_lon_cube, simple_2d


@tests.skip_plot
class TestGraphicStringCoord(tests.GraphicsTest):
def setUp(self):
super().setUp()
@_shared_utils.skip_plot
class TestGraphicStringCoord(_shared_utils.GraphicsTest):
@pytest.fixture(autouse=True)
def _setup(self):
self.cube = simple_2d(with_bounds=True)
self.cube.add_aux_coord(AuxCoord(list("abcd"), long_name="str_coord"), 1)
self.lat_lon_cube = lat_lon_cube()
Expand All @@ -38,7 +37,7 @@ def tick_loc_and_label(self, axis_name, axes=None):
labels = [tick.get_text() for tick in axis.get_ticklabels()]
return list(zip(locations, labels))

def assertBoundsTickLabels(self, axis, axes=None):
def assert_bounds_tick_labels(self, axis, axes=None):
actual = self.tick_loc_and_label(axis, axes)
expected = [
(-1.0, ""),
Expand All @@ -48,30 +47,30 @@ def assertBoundsTickLabels(self, axis, axes=None):
(3.0, "d"),
(4.0, ""),
]
self.assertEqual(expected, actual)
assert expected == actual

def assertPointsTickLabels(self, axis, axes=None):
def assert_points_tick_labels(self, axis, axes=None):
actual = self.tick_loc_and_label(axis, axes)
expected = [(0.0, "a"), (1.0, "b"), (2.0, "c"), (3.0, "d")]
self.assertEqual(expected, actual)
assert expected == actual


@tests.skip_plot
@_shared_utils.skip_plot
class MixinCoords:
"""Mixin class of common plotting tests providing 2-dimensional
permutations of coordinates and anonymous dimensions.

"""

def _check(self, u, v, data=None):
self.assertEqual(self.mpl_patch.call_count, 1)
assert self.mpl_patch.call_count == 1
if data is not None:
(actual_u, actual_v, actual_data), _ = self.mpl_patch.call_args
self.assertArrayEqual(actual_data, data)
_shared_utils.assert_array_equal(actual_data, data)
else:
(actual_u, actual_v), _ = self.mpl_patch.call_args
self.assertArrayEqual(actual_u, u)
self.assertArrayEqual(actual_v, v)
_shared_utils.assert_array_equal(actual_u, u)
_shared_utils.assert_array_equal(actual_v, v)

def test_foo_bar(self):
self.draw_func(self.cube, coords=("foo", "bar"))
Expand Down
63 changes: 25 additions & 38 deletions lib/iris/tests/unit/plot/_blockplot_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,8 @@
# See LICENSE in the root of the repository for full licensing details.
"""Common test code for `iris.plot.pcolor` and `iris.plot.pcolormesh`."""

# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests # isort:skip

from unittest import mock

import numpy as np
import pytest

from iris.tests.stock import simple_2d
from iris.tests.unit.plot import MixinCoords
Expand All @@ -23,11 +18,11 @@ class MixinStringCoordPlot:
# and defines "self.blockplot_func()", to return the `iris.plot` function.
def test_yaxis_labels(self):
self.blockplot_func()(self.cube, coords=("bar", "str_coord"))
self.assertBoundsTickLabels("yaxis")
self.assert_bounds_tick_labels("yaxis")

def test_xaxis_labels(self):
self.blockplot_func()(self.cube, coords=("str_coord", "bar"))
self.assertBoundsTickLabels("xaxis")
self.assert_bounds_tick_labels("xaxis")

def test_xaxis_labels_with_axes(self):
import matplotlib.pyplot as plt
Expand All @@ -37,7 +32,7 @@ def test_xaxis_labels_with_axes(self):
ax.set_xlim(0, 3)
self.blockplot_func()(self.cube, coords=("str_coord", "bar"), axes=ax)
plt.close(fig)
self.assertPointsTickLabels("xaxis", ax)
self.assert_points_tick_labels("xaxis", ax)

def test_yaxis_labels_with_axes(self):
import matplotlib.pyplot as plt
Expand All @@ -47,23 +42,23 @@ def test_yaxis_labels_with_axes(self):
ax.set_ylim(0, 3)
self.blockplot_func()(self.cube, axes=ax, coords=("bar", "str_coord"))
plt.close(fig)
self.assertPointsTickLabels("yaxis", ax)
self.assert_points_tick_labels("yaxis", ax)

def test_geoaxes_exception(self):
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
self.assertRaises(TypeError, self.blockplot_func(), self.lat_lon_cube, axes=ax)
pytest.raises(TypeError, self.blockplot_func(), self.lat_lon_cube, axes=ax)
plt.close(fig)


class Mixin2dCoordsPlot(MixinCoords):
# Mixin for common coordinate tests on pcolor/pcolormesh.
# To use, make a class that inherits from this *and*
# :class:`iris.tests.IrisTest`,
# and defines "self.blockplot_func()", to return the `iris.plot` function.
def blockplot_setup(self):
# defines "self.blockplot_func()", to return the `iris.plot` function.
@pytest.fixture(autouse=True)
def _blockplot_setup(self, mocker):
# We have a 2d cube with dimensionality (bar: 3; foo: 4)
self.cube = simple_2d(with_bounds=True)
coord = self.cube.coord("foo")
Expand All @@ -76,42 +71,34 @@ def blockplot_setup(self):
self.dataT = self.data.T
self.draw_func = self.blockplot_func()
patch_target_name = "matplotlib.pyplot." + self.draw_func.__name__
self.mpl_patch = self.patch(patch_target_name)
self.mpl_patch = mocker.patch(patch_target_name)


class Mixin2dCoordsContigTol:
# Mixin for contiguity tolerance argument to pcolor/pcolormesh.
# To use, make a class that inherits from this *and*
# :class:`iris.tests.IrisTest`,
# and defines "self.blockplot_func()", to return the `iris.plot` function,
# defines "self.blockplot_func()", to return the `iris.plot` function,
# and defines "self.additional_kwargs" for expected extra call args.
def test_contig_tol(self):
def test_contig_tol(self, mocker):
# Patch the inner call to ensure contiguity_tolerance is passed.
cube_argument = mock.sentinel.passed_arg
expected_result = mock.sentinel.returned_value
blockplot_patch = self.patch(
cube_argument = mocker.sentinel.passed_arg
expected_result = mocker.sentinel.returned_value
blockplot_patch = mocker.patch(
"iris.plot._draw_2d_from_bounds",
mock.Mock(return_value=expected_result),
mocker.Mock(return_value=expected_result),
)
# Make the call
draw_func = self.blockplot_func()
other_kwargs = self.additional_kwargs
result = draw_func(cube_argument, contiguity_tolerance=0.0123)
drawfunc_name = draw_func.__name__
# Check details of the call that was made.
self.assertEqual(
blockplot_patch.call_args_list,
[
mock.call(
drawfunc_name,
cube_argument,
contiguity_tolerance=0.0123,
**other_kwargs,
)
],
)
self.assertEqual(result, expected_result)


if __name__ == "__main__":
tests.main()
assert blockplot_patch.call_args_list == [
mocker.call(
drawfunc_name,
cube_argument,
contiguity_tolerance=0.0123,
**other_kwargs,
)
]
assert result == expected_result
36 changes: 12 additions & 24 deletions lib/iris/tests/unit/plot/test__check_bounds_contiguity_and_mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,18 @@
function.
"""

# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests # isort:skip

from unittest import mock

import numpy as np
import numpy.ma as ma
import pytest

from iris.coords import DimCoord
from iris.plot import _check_bounds_contiguity_and_mask
from iris.tests import _shared_utils
from iris.tests.stock import make_bounds_discontiguous_at_point, sample_2d_latlons


@tests.skip_plot
class Test_check_bounds_contiguity_and_mask(tests.IrisTest):
@_shared_utils.skip_plot
class Test_check_bounds_contiguity_and_mask:
def test_1d_not_checked(self):
# Test a 1D coordinate, which is not checked as atol is not set.
coord = DimCoord([1, 3, 5], bounds=[[0, 2], [2, 4], [5, 6]])
Expand Down Expand Up @@ -51,7 +47,7 @@ def test_1d_discontigous_unmasked(self):
"coordinate are not contiguous and data is not masked where "
"the discontiguity occurs"
)
with self.assertRaisesRegex(ValueError, msg):
with pytest.raises(ValueError, match=msg):
_check_bounds_contiguity_and_mask(coord, data, atol=1e-3)

def test_2d_contiguous(self):
Expand All @@ -60,18 +56,14 @@ def test_2d_contiguous(self):
cube = sample_2d_latlons()
_check_bounds_contiguity_and_mask(cube.coord("longitude"), cube.data)

def test_2d_contiguous_atol(self):
def test_2d_contiguous_atol(self, mocker):
# Check the atol is passed correctly.
cube = sample_2d_latlons()
with mock.patch(
"iris.coords.Coord._discontiguity_in_bounds"
) as discontiguity_check:
# Discontiguity returns two objects that are unpacked in
# `_check_bounds_contiguity_and_mask`.
discontiguity_check.return_value = [True, None]
_check_bounds_contiguity_and_mask(
cube.coord("longitude"), cube.data, atol=1e-3
)
discontiguity_check = mocker.patch("iris.coords.Coord._discontiguity_in_bounds")
# Discontiguity returns two objects that are unpacked in
# `_check_bounds_contiguity_and_mask`.
discontiguity_check.return_value = [True, None]
_check_bounds_contiguity_and_mask(cube.coord("longitude"), cube.data, atol=1e-3)
discontiguity_check.assert_called_with(atol=1e-3)

def test_2d_discontigous_masked(self):
Expand All @@ -88,9 +80,5 @@ def test_2d_discontigous_unmasked(self):
make_bounds_discontiguous_at_point(cube, 3, 4)
msg = "coordinate are not contiguous"
cube.data[3, 4] = ma.nomask
with self.assertRaisesRegex(ValueError, msg):
with pytest.raises(ValueError, match=msg):
_check_bounds_contiguity_and_mask(cube.coord("longitude"), cube.data)


if __name__ == "__main__":
tests.main()
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,19 @@
function.
"""

# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests # isort:skip

from unittest.mock import Mock

from cartopy.crs import Geostationary, NearsidePerspective
import numpy as np
import pytest

from iris.plot import _check_geostationary_coords_and_convert
from iris.tests import _shared_utils


class Test__check_geostationary_coords_and_convert:
@pytest.fixture(autouse=True)
def _setup(self, mocker):
self.mocker = mocker

class Test__check_geostationary_coords_and_convert(tests.IrisTest):
def setUp(self):
geostationary_altitude = 35785831.0
# proj4_params is the one attribute of the Geostationary class that
# is needed for the function.
Expand All @@ -46,15 +45,15 @@ def _test(self, geostationary=True):
projection_spec = NearsidePerspective
target_tuple = (self.x_original, self.y_original)

projection = Mock(spec=projection_spec)
projection = self.mocker.Mock(spec=projection_spec)
projection.proj4_params = self.proj4_params
# Projection is looked for within a dictionary called kwargs.
kwargs = {"transform": projection}

x, y = _check_geostationary_coords_and_convert(
self.x_original, self.y_original, kwargs
)
self.assertArrayEqual((x, y), target_tuple)
_shared_utils.assert_array_equal((x, y), target_tuple)

def test_geostationary_present(self):
self._test(geostationary=True)
Expand Down
Loading