Skip to content

Commit

Permalink
Sometimes, 5 coffees is not a good idea
Browse files Browse the repository at this point in the history
  • Loading branch information
nabobalis committed Mar 29, 2024
1 parent 2baee1a commit 4fbd20b
Show file tree
Hide file tree
Showing 17 changed files with 68 additions and 49 deletions.
2 changes: 2 additions & 0 deletions sunpy/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,9 @@ def pytest_runtest_teardown(item):

@pytest.fixture(scope="session")
def aia171_test_map():
pytest.importorskip("sunpy.map")
from sunpy.map import Map

return Map(get_test_filepath('aia_171_level1.fits'))


Expand Down
2 changes: 2 additions & 0 deletions sunpy/coordinates/tests/test_spice.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import numpy as np
import pytest

pytest.importorskip('spiceypy')
import spiceypy

import astropy.units as u
Expand Down
1 change: 1 addition & 0 deletions sunpy/coordinates/tests/test_transformations.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import numpy as np
import pytest

pytest.importorskip('matplotlib')
import astropy.units as u
from astropy.constants import c as speed_of_light
from astropy.coordinates import (
Expand Down
3 changes: 2 additions & 1 deletion sunpy/coordinates/tests/test_wcs_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from astropy.time import Time
from astropy.wcs import WCS

import sunpy.map
from sunpy.coordinates.frames import (
Heliocentric,
HeliographicCarrington,
Expand Down Expand Up @@ -93,6 +92,8 @@ def test_wcs_aux():
Make sure auxiliary information round trips properly from coordinate frames
to WCS and back.
"""
pytest.importorskip('sunpy.map')
import sunpy.map
data = np.ones([6, 6], dtype=np.float64)
header = {'CRVAL1': 0,
'CRVAL2': 0,
Expand Down
4 changes: 3 additions & 1 deletion sunpy/data/test/_generate_asdf_test.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
"""
This file will generate an asdf file in the test data, using the newest schema version.
"""
import asdf
import astropy.units as u

from sunpy.data.test import rootdir


def generate_asdf_tree(obj, filename):
import asdf

tree = {"object": obj}
with asdf.AsdfFile(tree) as af:
# TODO: Automatically determine filename based on tag used
Expand All @@ -16,6 +17,7 @@ def generate_asdf_tree(obj, filename):

if __name__ == "__main__":
import sunpy.map

test_map = rootdir / "aia_171_level1.fits"
obj = sunpy.map.Map(test_map)
obj = obj.resample((2, 2)*u.pix)
Expand Down
3 changes: 2 additions & 1 deletion sunpy/io/special/asdf/tests/test_coordinate_frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import numpy as np
import pytest

import asdf
import astropy.units as u
from astropy.coordinates import CartesianRepresentation

Expand Down Expand Up @@ -54,6 +53,8 @@ def coordframe_array(request):
@pytest.mark.filterwarnings('ignore:.*was created with extension.*')
@asdf_entry_points
def test_hgc_100():
import asdf

# Test that HeliographicCarrington is populated with Earth as the
# observer when loading a older schema (1.0.0)
test_file = os.path.join(os.path.dirname(__file__), "hgc_100.asdf")
Expand Down
20 changes: 10 additions & 10 deletions sunpy/io/special/asdf/tests/test_genericmap.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import numpy as np
import pytest

import asdf
import astropy.units as u

import sunpy.map
from sunpy.data.test import get_test_filepath
from sunpy.tests.helpers import asdf_entry_points
from .helpers import roundtrip_object
Expand All @@ -25,19 +23,13 @@ def assert_roundtrip_map(old):
assert old.unit == new.unit


@pytest.fixture
def aia171_test_map():
aia_path = get_test_filepath("aia_171_level1.fits")
return sunpy.map.Map(aia_path)


@asdf_entry_points
def test_genericmap_basic(aia171_test_map, tmpdir):
def test_genericmap_basic(aia171_test_map):
assert_roundtrip_map(aia171_test_map)


@asdf_entry_points
def test_genericmap_mask(aia171_test_map, tmpdir):
def test_genericmap_mask(aia171_test_map):
mask = np.zeros_like(aia171_test_map.data)
mask[10, 10] = 1
aia171_test_map.mask = mask
Expand All @@ -47,6 +39,10 @@ def test_genericmap_mask(aia171_test_map, tmpdir):

@asdf_entry_points
def test_load_100_file_with_shift():
import asdf
pytest.importorskip("sunpy.map")
import sunpy.map

fname = get_test_filepath("aiamap_shift_genericmap_1.0.0.asdf")
with asdf.open(fname, copy_arrays=True) as af:
aiamap = af['object']
Expand All @@ -58,6 +54,10 @@ def test_load_100_file_with_shift():

@asdf_entry_points
def test_load_100_file_with_no_shift():
import asdf
pytest.importorskip("sunpy.map")
import sunpy.map

fname = get_test_filepath("aiamap_genericmap_1.0.0.asdf")
with asdf.open(fname, copy_arrays=True) as af:
aiamap = af['object']
Expand Down
3 changes: 2 additions & 1 deletion sunpy/io/tests/test_cdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
import astropy.units as u

from sunpy.data.test import get_test_filepath
from sunpy.io._cdf import read_cdf
from sunpy.timeseries import GenericTimeSeries

filepath = get_test_filepath('solo_L2_epd-ept-north-hcad_20200713_V02.cdf')


def test_read_cdf():
from sunpy.io._cdf import read_cdf

all_ts = read_cdf(filepath)
assert isinstance(all_ts, list)
assert len(all_ts) == 3
Expand Down
25 changes: 14 additions & 11 deletions sunpy/map/mapbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,7 @@
from tempfile import NamedTemporaryFile
from collections import namedtuple

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backend_bases import FigureCanvasBase
from matplotlib.figure import Figure

try:
from dask.array import Array as DaskArray
Expand Down Expand Up @@ -313,6 +309,9 @@ def _repr_html_(self, compute_dask=False):
"""
Produce an HTML summary with plots for use in Jupyter notebooks.
"""
import matplotlib.pyplot as plt
from matplotlib.backend_bases import FigureCanvasBase

# Convert the text repr to an HTML table
partial_html = self._text_summary()[20:].replace('\n', '</td></tr><tr><th>')\
.replace(':\t', '</th><td>')
Expand Down Expand Up @@ -357,14 +356,12 @@ def _repr_html_(self, compute_dask=False):
bad_pixel_text += ", ".join(text_list)

# Use a grayscale colormap with histogram equalization (and red for bad values)
# Make a copy of the colormap to avoid modifying the matplotlib instance when
# doing set_bad() (copy not needed when min mpl is 3.5, as already a copy)
cmap = copy.copy(matplotlib.colormaps['gray'])
cmap = plt.get_cmap('gray')
cmap.set_bad(color='red')
norm = ImageNormalize(stretch=HistEqStretch(finite_data))

# Plot the image in pixel space
fig = Figure(figsize=(5.2, 4.8))
fig = plt.Figure(figsize=(5.2, 4.8))
# Figure instances in matplotlib<3.1 do not create a canvas by default
if fig.canvas is None:
FigureCanvasBase(fig)
Expand All @@ -377,7 +374,7 @@ def _repr_html_(self, compute_dask=False):
bounds = ax.get_position().bounds # save these axes bounds for later use

# Plot the image using WCS information, with the same axes bounds as above
fig = Figure(figsize=(5.2, 4.8))
fig = plt.Figure(figsize=(5.2, 4.8))
# Figure instances in matplotlib<3.1 do not create a canvas by default
if fig.canvas is None:
FigureCanvasBase(fig)
Expand All @@ -389,7 +386,7 @@ def _repr_html_(self, compute_dask=False):
wcs_src = _figure_to_base64(fig)

# Plot the histogram of pixel values
fig = Figure(figsize=(4.8, 2.4), constrained_layout=True)
fig = plt.Figure(figsize=(4.8, 2.4), constrained_layout=True)
# Figure instances in matplotlib<3.1 do not create a canvas by default
if fig.canvas is None:
FigureCanvasBase(fig)
Expand All @@ -410,7 +407,7 @@ def _repr_html_(self, compute_dask=False):
hist_src = _figure_to_base64(fig)

# Plot the CDF of the pixel values using a symmetric-log horizontal scale
fig = Figure(figsize=(4.8, 2.4), constrained_layout=True)
fig = plt.Figure(figsize=(4.8, 2.4), constrained_layout=True)
# TODO: Figure instances in matplotlib<3.1 do not create a canvas by default
if fig.canvas is None:
FigureCanvasBase(fig)
Expand Down Expand Up @@ -2115,6 +2112,8 @@ def cmap(self):
"""
Return the `matplotlib.colors.Colormap` instance this map uses.
"""
import matplotlib.pyplot as plt

cmap = self.plot_settings['cmap']
if isinstance(cmap, str):
cmap = plt.get_cmap(cmap)
Expand Down Expand Up @@ -2405,6 +2404,8 @@ def peek(self, draw_limb=False, draw_grid=False,
Matplotlib Any additional imshow arguments that should be used
when plotting.
"""
import matplotlib.pyplot as plt

figure = plt.figure()
axes = wcsaxes_compat.gca_wcs(self.wcs)

Expand Down Expand Up @@ -2492,6 +2493,8 @@ def plot(self, annotate=True, axes=None, title=True, autoalign=False,
:meth:`~sunpy.coordinates.Helioprojective.assume_spherical_screen` context
manager may be appropriate.
"""
import matplotlib.pyplot as plt

# Users sometimes assume that the first argument is `axes` instead of `annotate`
if not isinstance(annotate, bool):
raise TypeError("You have provided a non-boolean value for the `annotate` parameter. "
Expand Down
9 changes: 0 additions & 9 deletions sunpy/map/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,6 @@ def hmi_test_map():
return sunpy.map.Map((data, header))


@pytest.fixture
def aia171_test_map():
(data, header), = sunpy.io.read_file(get_test_filepath('aia_171_level1.fits'))

# Get rid of the blank keyword to prevent some astropy fits fixing warnings
header.pop('BLANK')
return sunpy.map.Map((data, header))


@pytest.fixture
def aia171_roll_map(aia171_test_map):
return aia171_test_map.rotate(-45*u.deg)
Expand Down
4 changes: 2 additions & 2 deletions sunpy/physics/differential_rotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@
get_earth,
transform_with_sun_center,
)
from sunpy.map import (
from sunpy.map.header_helper import get_observer_meta
from sunpy.map.maputils import (
contains_full_disk,
coordinate_is_on_solar_disk,
is_all_off_disk,
is_all_on_disk,
map_edges,
on_disk_bounding_coordinates,
)
from sunpy.map.header_helper import get_observer_meta
from sunpy.sun.constants import sidereal_rotation_rate
from sunpy.time import parse_time
from sunpy.util import expand_list
Expand Down
1 change: 1 addition & 0 deletions sunpy/physics/tests/test_differential_rotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import numpy as np
import pytest

pytest.importorskip('matplotlib')
import astropy.units as u
from astropy.coordinates import Longitude, SkyCoord
from astropy.tests.helper import assert_quantity_allclose
Expand Down
10 changes: 9 additions & 1 deletion sunpy/tests/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# NOTE: Do not import sunpy subpackages which have optional dependencies here,
# this module should be importable with no extra dependencies installed.

__all__ = ['skip_windows', 'skip_glymur', 'skip_ana', 'warnings_as_errors', 'asdf_entry_points']
__all__ = ['skip_windows', 'skip_glymur', 'skip_ana', 'skip_cdf', 'warnings_as_errors', 'asdf_entry_points']

# SunPy's JPEG2000 capabilities rely on the glymur library.
# First we check to make sure that glymur imports correctly before proceeding.
Expand All @@ -35,6 +35,13 @@
else:
SKIP_ANA = False

try:
import cdflib # NOQA
except ImportError:
SKIP_CDF = True
else:
SKIP_CDF = False

if sys.maxsize > 2**32:
SKIP_32 = False
else:
Expand All @@ -43,6 +50,7 @@
skip_windows = pytest.mark.skipif(platform.system() == "Windows", reason="Windows.")
skip_glymur = pytest.mark.skipif(SKIP_GLYMUR, reason="Glymur can not be imported.")
skip_ana = pytest.mark.skipif(SKIP_ANA, reason="ANA is not available.")
skip_cdf = pytest.mark.skipif(SKIP_CDF, reason="cdflib is not installed.")
asdf_entry_points = pytest.mark.skipif(
not entry_points().select(group="asdf.resource_mappings", name="sunpy"),
reason="No SunPy ASDF entry points.",
Expand Down
6 changes: 4 additions & 2 deletions sunpy/tests/self_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

__all__ = ['self_test', '_test_base_deps']
__all__ = ['self_test']

def _print_missing_dependencies_report(missing, package="sunpy"):
printed = False
Expand Down Expand Up @@ -75,9 +75,11 @@ def self_test(*, package=None, online=False, online_only=False, figure_only=Fals
return pytest.main(test_args)

def _test_base_deps():
# Provide a way to test the base dependencies without running the full test suite.
import pytest

module_names = ["coordinates", "data", "io", "physics", "sun", "time", "util"]
# While we can import io and data, they need actual dependencies to test.
module_names = ["coordinates", "physics", "sun", "time", "util"]
test_args = ["-c", "/dev/null", "--pyargs"] + [f"sunpy.{name}" for name in module_names]
return pytest.main(test_args)

Expand Down
10 changes: 5 additions & 5 deletions sunpy/time/tests/test_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def test_parse_time_int():


def test_parse_time_pandas_timestamp():
import pandas
pandas = pytest.importorskip('pandas')

ts = pandas.Timestamp(LANDING.datetime)

Expand All @@ -82,7 +82,7 @@ def test_parse_time_pandas_timestamp():


def test_parse_time_nanoseconds():
import pandas
pandas = pytest.importorskip('pandas')

# Check that nanosecon precision is retained when parsing pandas timestamps
ts = pandas.Timestamp('2020-07-31 00:00:26.166196864')
Expand All @@ -93,7 +93,7 @@ def test_parse_time_nanoseconds():


def test_parse_time_pandas_series():
import pandas
pandas = pytest.importorskip('pandas')

inputs = [datetime(2012, 1, i) for i in range(1, 13)]
ind = pandas.Series(inputs)
Expand All @@ -106,7 +106,7 @@ def test_parse_time_pandas_series():


def test_parse_time_pandas_series_2():
import pandas
pandas = pytest.importorskip('pandas')

inputs = [[datetime(2012, 1, 1, 0, 0), datetime(2012, 1, 2, 0, 0)],
[datetime(2012, 1, 3, 0, 0), datetime(2012, 1, 4, 0, 0)]]
Expand All @@ -121,7 +121,7 @@ def test_parse_time_pandas_series_2():


def test_parse_time_pandas_index():
import pandas
pandas = pytest.importorskip('pandas')

inputs = [datetime(2012, 1, i) for i in range(1, 13)]
ind = pandas.DatetimeIndex(inputs)
Expand Down

0 comments on commit 4fbd20b

Please sign in to comment.