Skip to content

Commit

Permalink
Add strict warning checks to tests
Browse files Browse the repository at this point in the history
  • Loading branch information
djhoese committed Nov 27, 2023
1 parent 50e3251 commit 114266d
Show file tree
Hide file tree
Showing 10 changed files with 73 additions and 54 deletions.
10 changes: 5 additions & 5 deletions polar2grid/add_coastlines.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@
import logging
import os
import sys
from pathlib import Path

import numpy as np
import rasterio
from aggdraw import Font
from PIL import Image, ImageFont
from pkg_resources import resource_filename as get_resource_filename
from pycoast import ContourWriterAGG
from pydecorate import DecoratorAGG
from pyresample.utils import get_area_def_from_raster
Expand Down Expand Up @@ -485,10 +485,10 @@ def find_font(font_name, size):
font = ImageFont.truetype(font_name, size)
return font.path
except IOError as err:
font_path = get_resource_filename("polar2grid.fonts", font_name)
if not os.path.exists(font_path):
raise ValueError("Font path does not exist: {}".format(font_path)) from err
return font_path
font_path = Path(__file__).parent / "fonts" / font_name
if not font_path.is_file():
raise ValueError(f"Font path does not exist: {font_path}") from err
return str(font_path)


def _process_one_image(
Expand Down
7 changes: 4 additions & 3 deletions polar2grid/filters/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
from typing import Union

from pyresample.boundary import AreaBoundary, AreaDefBoundary, Boundary
from pyresample.geometry import AreaDefinition, SwathDefinition, get_geostationary_bounding_box
from pyresample.geometry import AreaDefinition, SwathDefinition, get_geostationary_bounding_box_in_lonlats
from pyresample.spherical import SphPolygon

logger = logging.getLogger(__name__)
Expand All @@ -47,11 +47,12 @@
def boundary_for_area(area_def: PRGeometry) -> Boundary:
"""Create Boundary object representing the provided area."""
if getattr(area_def, "is_geostationary", False):
adp = Boundary(*get_geostationary_bounding_box(area_def, nb_points=100))
adp = Boundary(*get_geostationary_bounding_box_in_lonlats(area_def, nb_points=100))
else:
freq_fraction = 0.30 if isinstance(area_def, AreaDefinition) else 0.05
try:
adp = AreaDefBoundary(area_def, frequency=int(area_def.shape[0] * freq_fraction))
adp = area_def.boundary()
adp.decimate(int(freq_fraction * area_def.shape[0]))
except ValueError:
if not isinstance(area_def, SwathDefinition):
logger.error("Unable to generate bounding geolocation polygon")
Expand Down
12 changes: 7 additions & 5 deletions polar2grid/tests/test_add_coastlines.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,10 @@ def test_add_coastlines_basic(
passed_cmap = add_scale_mock.call_args.kwargs["colormap"]
_check_used_colormap(passed_cmap, has_colors, include_cmap_tag, include_scale_offset)

img = Image.open(output_fp)
arr = np.asarray(img)
with Image.open(output_fp) as img:
img.load()
arr = np.asarray(img)
out_tags = dict(img.tag_v2) if output_fp.endswith(".tif") else {}
# bottom of the image is a colorbar
image_arr = arr[:940]
_check_exp_image_colors(image_arr, colormap, 0, has_colors)
Expand All @@ -181,9 +183,9 @@ def test_add_coastlines_basic(
assert (arr[940:] != 0).any()

if output_fp.endswith(".tif"):
out_tags = dict(img.tag_v2)
in_img = Image.open(fp)
in_tags = dict(in_img.tag_v2)
with Image.open(fp) as in_img:
in_img.load()
in_tags = dict(in_img.tag_v2)
assert len(out_tags) >= 14
for key, val in out_tags.items():
if key < 30000:
Expand Down
18 changes: 2 additions & 16 deletions polar2grid/tests/test_compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@
# input into another program.
# Documentation: http://www.ssec.wisc.edu/software/polar2grid/
"""Tests for the compare.py script."""
import contextlib
import os
import warnings
from glob import glob

import numpy as np
import pytest

from polar2grid.utils.warnings import ignore_no_georef

SHAPE1 = (200, 100)
SHAPE2 = (200, 101)
IMAGE1_L_UINT8_ZEROS = np.zeros(SHAPE1, dtype=np.uint8)
Expand All @@ -44,20 +44,6 @@
IMAGE_LIST2 = [IMAGE1_L_UINT8_ZEROS, IMAGE2_L_UINT8_ZEROS, IMAGE4_RGB_UINT8_ZEROS]


@contextlib.contextmanager
def ignore_no_georef():
"""Wrap operations that we know will produce a rasterio geolocation warning."""
from rasterio.errors import NotGeoreferencedWarning

with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
"Dataset has no geotransform",
NotGeoreferencedWarning,
)
yield


def _create_geotiffs(base_dir, img_data):
import rasterio

Expand Down
3 changes: 2 additions & 1 deletion polar2grid/tests/test_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@ def pytest_generate_tests(metafunc):
"""
if "yaml_config_file" in metafunc.fixturenames:
root_dir = os.path.join(os.path.dirname(__file__), "..", "..")
root_dir = os.path.join(os.path.dirname(__file__), "..")
glob_pat = os.path.join(root_dir, "etc", "**", "*.yaml")
p2g_yaml_files = sorted(glob(glob_pat, recursive=True))
assert len(p2g_yaml_files) != 0
metafunc.parametrize("yaml_config_file", p2g_yaml_files)


Expand Down
4 changes: 3 additions & 1 deletion polar2grid/tests/test_glue.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from satpy.tests.utils import CustomScheduler

from polar2grid.utils.config import get_polar2grid_etc
from polar2grid.utils.warnings import ignore_no_georef


@contextlib.contextmanager
Expand Down Expand Up @@ -294,7 +295,8 @@ def test_viirs_sdr_scene(self, scene_fixture, product_names, num_outputs, extra_
args.extend(product_names)
if extra_flags:
args.extend(extra_flags)
ret = main(args)
with ignore_no_georef():
ret = main(args)
output_files = glob(str(chtmpdir / "*.tif"))
assert len(output_files) == num_outputs
assert ret == 0
Expand Down
21 changes: 0 additions & 21 deletions polar2grid/utils/legacy_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@

from __future__ import annotations

import contextlib
import logging
import warnings
from typing import Generator, Iterable, Optional, Union

from satpy import DataID, DataQuery, Scene
Expand Down Expand Up @@ -259,22 +257,3 @@ def get_sensor_alias(satpy_sensor):
if len(new_sensor) == 1:
return new_sensor.pop()
return new_sensor


@contextlib.contextmanager
def ignore_pyproj_proj_warnings():
"""Wrap operations that we know will produce a PROJ.4 precision warning.
Only to be used internally to Pyresample when we have no other choice but
to use PROJ.4 strings/dicts. For example, serialization to YAML or other
human-readable formats or testing the methods that produce the PROJ.4
versions of the CRS.
"""
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
"You will likely lose important projection information",
UserWarning,
)
yield
38 changes: 38 additions & 0 deletions polar2grid/utils/warnings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""Warnings or utilities for dealing with warnings."""
from __future__ import annotations

import contextlib
import warnings


@contextlib.contextmanager
def ignore_no_georef():
"""Wrap operations that we know will produce a rasterio geolocation warning."""
from rasterio.errors import NotGeoreferencedWarning

with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
"Dataset has no geotransform",
NotGeoreferencedWarning,
)
yield


@contextlib.contextmanager
def ignore_pyproj_proj_warnings():
"""Wrap operations that we know will produce a PROJ.4 precision warning.
Only to be used internally to Pyresample when we have no other choice but
to use PROJ.4 strings/dicts. For example, serialization to YAML or other
human-readable formats or testing the methods that produce the PROJ.4
versions of the CRS.
"""
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
"You will likely lose important projection information",
UserWarning,
)
yield
3 changes: 2 additions & 1 deletion polar2grid/writers/hdf5.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
from pyresample.geometry import SwathDefinition
from satpy.writers import Writer, compute_writer_results, split_results

from polar2grid.utils.legacy_compat import convert_p2g_pattern_to_satpy, ignore_pyproj_proj_warnings
from polar2grid.utils.legacy_compat import convert_p2g_pattern_to_satpy
from polar2grid.utils.warnings import ignore_pyproj_proj_warnings
from polar2grid.writers.geotiff import NUMPY_DTYPE_STRS, NumpyDtypeList, str_to_dtype

LOG = logging.getLogger(__name__)
Expand Down
11 changes: 10 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,16 @@ include-package-data = true
find = {}

[tool.pytest.ini_options]
minversion = 7.0
minversion = 6.0
addopts = ["-ra", "--showlocals", "--strict-markers", "--strict-config"]
xfail_strict = true
log_cli_level = "info"
testpaths = ["polar2grid/tests"]
filterwarnings = [
"error",
"ignore:numpy.ndarray size changed, may indicate binary incompatibility:RuntimeWarning",
"ignore:The `frequency` argument is pending deprecation:PendingDeprecationWarning"
]

[tool.coverage.run]
relative_files = true
Expand Down

0 comments on commit 114266d

Please sign in to comment.