8000 Merge pull request #16445 from anntzer/testimports · matplotlib/matplotlib@119fcbd · GitHub
[go: up one dir, main page]

Skip to content

Commit 119fcbd

Browse files
authored
Merge pull request #16445 from anntzer/testimports
MNT: Remove a bunch of imports-within-tests.
2 parents 6f83061 + 280f4c3 commit 119fcbd

16 files changed

+103
-172
lines changed

lib/matplotlib/tests/test_arrow_patches.py

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -95,24 +95,21 @@ def test_fancyarrow_dpi_cor_200dpi():
9595

9696
@image_comparison(['fancyarrow_dash.png'], remove_text=True, style='default')
9797
def test_fancyarrow_dash():
98-
from matplotlib.patches import FancyArrowPatch
9998
fig, ax = plt.subplots()
100-
101-
e = FancyArrowPatch((0, 0), (0.5, 0.5),
102-
arrowstyle='-|>',
103-
connectionstyle='angle3,angleA=0,angleB=90',
104-
mutation_scale=10.0,
105-
linewidth=2,
106-
linestyle='dashed',
107-
color='k')
108-
109-
e2 = FancyArrowPatch((0, 0), (0.5, 0.5),
110-
arrowstyle='-|>',
111-
connectionstyle='angle3',
112-
mutation_scale=10.0,
113-
linewidth=2,
114-
linestyle='dotted',
115-
color='k')
99+
e = mpatches.FancyArrowPatch((0, 0), (0.5, 0.5),
100+
arrowstyle='-|>',
101+
connectionstyle='angle3,angleA=0,angleB=90',
102+
mutation_scale=10.0,
103+
linewidth=2,
104+
linestyle='dashed',
105+
color='k')
106+
e2 = mpatches.FancyArrowPatch((0, 0), (0.5, 0.5),
107+
arrowstyle='-|>',
108+
connectionstyle='angle3',
109+
mutation_scale=10.0,
110+
linewidth=2,
111+
linestyle='dotted',
112+
color='k')
116113
ax.add_patch(e)
117114
ax.add_patch(e2)
118115

lib/matplotlib/tests/test_axes.py

Lines changed: 33 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import datetime
77

8-
import dateutil.tz as dutz
8+
import dateutil.tz
99

1010
import numpy as np
1111
from numpy import ma
@@ -498,8 +498,7 @@ def test_polar_coord_annotations():
498498
# native coordinate system ('data') is cartesian, so you need to
499499
# specify the xycoords and textcoords as 'polar' if you want to
500500
# use (theta, radius)
501-
from matplotlib.patches import Ellipse
502-
el = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5)
501+
el = mpatches.Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5)
503502

504503
fig = plt.figure()
505504
ax = fig.add_subplot(111, aspect='equal')
@@ -548,12 +547,11 @@ def test_polar_alignment():
548547

549548
@image_comparison(['fill_units.png'], savefig_kwarg={'dpi': 60})
550549
def test_fill_units():
551-
from datetime import datetime
552550
import matplotlib.testing.jpl_units as units
553551
units.register()
554552

555553
# generate some data
556-
t = units.Epoch("ET", dt=datetime(2009, 4, 27))
554+
t = units.Epoch("ET", dt=datetime.datetime(2009, 4, 27))
557555
value = 10.0 * units.deg
558556
day = units.Duration("ET", 24.0 * 60.0 * 60.0)
559557

@@ -854,13 +852,12 @@ def test_aitoff_proj():
854852

855853
@image_comparison(['axvspan_epoch'])
856854
def test_axvspan_epoch():
857-
from datetime import datetime
858855
import matplotlib.testing.jpl_units as units
859856
units.register()
860857

861858
# generate some data
862-
t0 = units.Epoch("ET", dt=datetime(2009, 1, 20))
863-
tf = units.Epoch("ET", dt=datetime(2009, 1, 21))
859+
t0 = units.Epoch("ET", dt=datetime.datetime(2009, 1, 20))
860+
tf = units.Epoch("ET", dt=datetime.datetime(2009, 1, 21))
864861
dt = units.Duration("ET", units.day.convert("sec"))
865862

866863
ax = plt.gca()
@@ -870,13 +867,12 @@ def test_axvspan_epoch():
870867

871868
@image_comparison(['axhspan_epoch'])
872869
def test_axhspan_epoch():
873-
from datetime import datetime
874870
import matplotlib.testing.jpl_units as units
875871
units.register()
876872

877873
# generate some data
878-
t0 = units.Epoch("ET", dt=datetime(2009, 1, 20))
879-
tf = units.Epoch("ET", dt=datetime(2009, 1, 21))
874+
t0 = units.Epoch("ET", dt=datetime.datetime(2009, 1, 20))
875+
tf = units.Epoch("ET", dt=datetime.datetime(2009, 1, 21))
880876
dt = units.Duration("ET", units.day.convert("sec"))
881877

882878
ax = plt.gca()
@@ -1013,11 +1009,10 @@ def test_imshow_clip():
10131009

10141010
c = ax.contour(r, [N/4])
10151011
x = c.collections[0]
1016-
clipPath = x.get_paths()[0]
1017-
clipTransform = x.get_transform()
1012+
clip_path = x.get_paths()[0]
1013+
clip_transform = x.get_transform()
10181014

1019-
from matplotlib.transforms import TransformedPath
1020-
clip_path = TransformedPath(clipPath, clipTransform)
1015+
clip_path = mtransforms.TransformedPath(clip_path, clip_transform)
10211016

10221017
# Plot the image clipped by the contour
10231018
ax.imshow(r, clip_path=clip_path)
@@ -1039,12 +1034,9 @@ def test_imshow_norm_vminvmax(fig_test, fig_ref):
10391034
@image_comparison(['polycollection_joinstyle'], remove_text=True)
10401035
def test_polycollection_joinstyle():
10411036
# Bug #2890979 reported by Matthew West
1042-
1043-
from matplotlib import collections as mcoll
1044-
10451037
fig, ax = plt.subplots()
10461038
verts = np.array([[1, 1], [1, 2], [2, 2], [2, 1]])
1047-
c = mcoll.PolyCollection([verts], linewidths=40)
1039+
c = mpl.collections.PolyCollection([verts], linewidths=40)
10481040
ax.add_collection(c)
10491041
ax.set_xbound(0, 3)
10501042
ax.set_ybound(0, 3)
@@ -1308,7 +1300,6 @@ def test_canonical():
13081300

13091301
@image_comparison(['arc_angles.png'], remove_text=True, style='default')
13101302
def test_arc_angles():
1311-
from matplotlib import patches
13121303
# Ellipse parameters
13131304
w = 2
13141305
h = 1
@@ -1320,8 +1311,8 @@ def test_arc_angles():
13201311
theta2 = i * 360 / 9
13211312
theta1 = theta2 - 45
13221313

1323-
ax.add_patch(patches.Ellipse(centre, w, h, alpha=0.3))
1324-
ax.add_patch(patches.Arc(centre, w, h, theta1=theta1, theta2=theta2))
1314+
ax.add_patch(mpatches.Ellipse(centre, w, h, alpha=0.3))
1315+
ax.add_patch(mpatches.Arc(centre, w, h, theta1=theta1, theta2=theta2))
13251316
# Straight lines intersecting start and end of arc
13261317
ax.plot([scale * np.cos(np.deg2rad(theta1)) + centre[0],
13271318
centre[0],
@@ -1343,7 +1334,6 @@ def test_arc_angles():
13431334

13441335
@image_comparison(['arc_ellipse'], remove_text=True)
13451336
def test_arc_ellipse():
1346-
from matplotlib import patches
13471337
xcenter, ycenter = 0.38, 0.52
13481338
width, height = 1e-1, 3e-1
13491339
angle = -30
@@ -1366,15 +1356,15 @@ def test_arc_ellipse():
13661356
ax.fill(x, y, alpha=0.2, facecolor='yellow', edgecolor='yellow',
13671357
linewidth=1, zorder=1)
13681358

1369-
e1 = patches.Arc((xcenter, ycenter), width, height,
1370-
angle=angle, linewidth=2, fill=False, zorder=2)
1359+
e1 = mpatches.Arc((xcenter, ycenter), width, height,
1360+
angle=angle, linewidth=2, fill=False, zorder=2)
13711361

13721362
ax.add_patch(e1)
13731363

13741364
ax = fig.add_subplot(212, aspect='equal')
13751365
ax.fill(x, y, alpha=0.2, facecolor='green', edgecolor='green', zorder=1)
1376-
e2 = patches.Arc((xcenter, ycenter), width, height,
1377-
angle=angle, linewidth=2, fill=False, zorder=2)
1366+
e2 = mpatches.Arc((xcenter, ycenter), width, height,
1367+
angle=angle, linewidth=2, fill=False, zorder=2)
13781368

13791369
ax.add_patch(e2)
13801370

@@ -2093,23 +2083,20 @@ def test_scatter_c(self, c_case, re_key):
20932083
def get_next_color():
20942084
return 'blue' # currently unused
20952085

2096-
from matplotlib.axes import Axes
2097-
20982086
xsize = 4
2099-
21002087
# Additional checking of *c* (introduced in #11383).
21012088
REGEXP = {
21022089
"shape": "^'c' argument has [0-9]+ elements", # shape mismatch
21032090
"conversion": "^'c' argument must be a color", # bad vals
21042091
}
21052092

21062093
if re_key is None:
2107-
Axes._parse_scatter_color_args(
2094+
mpl.axes.Axes._parse_scatter_color_args(
21082095
c=c_case, edgecolors="black", kwargs={}, xsize=xsize,
21092096
get_next_color_func=get_next_color)
21102097
else:
21112098
with pytest.raises(ValueError, match=REGEXP[re_key]):
2112-
Axes._parse_scatter_color_args(
2099+
mpl.axes.Axes._parse_scatter_color_args(
21132100
c=c_case, edgecolors="black", kwargs={}, xsize=xsize,
21142101
get_next_color_func=get_next_color)
21152102

@@ -2137,8 +2124,7 @@ def test_parse_scatter_color_args(params, expected_result):
21372124
def get_next_color():
21382125
return 'blue' # currently unused
21392126

2140-
from matplotlib.axes import Axes
2141-
c, colors, _edgecolors = Axes._parse_scatter_color_args(
2127+
c, colors, _edgecolors = mpl.axes.Axes._parse_scatter_color_args(
21422128
*params, get_next_color_func=get_next_color)
21432129
assert c == expected_result.c
21442130
assert_allclose(colors, expected_result.colors)
@@ -2164,19 +2150,17 @@ def test_parse_scatter_color_args_edgecolors(kwargs, expected_edgecolors):
21642150
def get_next_color():
21652151
return 'blue' # currently unused
21662152

2167-
from matplotlib.axes import Axes
21682153
c = kwargs.pop('c', None)
21692154
edgecolors = kwargs.pop('edgecolors', None)
21702155
_, _, result_edgecolors = \
2171-
Axes._parse_scatter_color_args(c, edgecolors, kwargs, xsize=2,
2172-
get_next_color_func=get_next_color)
2156+
mpl.axes.Axes._parse_scatter_color_args(
2157+
c, edgecolors, kwargs, xsize=2, get_next_color_func=get_next_color)
21732158
assert result_edgecolors == expected_edgecolors
21742159

21752160

21762161
def test_as_mpl_axes_api():
21772162
# tests the _as_mpl_axes api
21782163
from matplotlib.projections.polar import PolarAxes
2179-
import matplotlib.axes as maxes
21802164

21812165
class Polar:
21822166
def __init__(self):
@@ -2200,7 +2184,7 @@ def _as_mpl_axes(self):
22002184

22012185
# testing axes creation with gca
22022186
ax = plt.gca(projection=prj)
2203-
assert type(ax) == maxes._subplots.subplot_class_factory(PolarAxes)
2187+
assert type(ax) == mpl.axes._subplots.subplot_class_factory(PolarAxes)
22042188
ax_via_gca = plt.gca(projection=prj)
22052189
assert ax_via_gca is ax
22062190
# try getting the axes given a different polar projection
@@ -2221,7 +2205,7 @@ def _as_mpl_axes(self):
22212205

22222206
# testing axes creation with subplot
22232207
ax = plt.subplot(121, projection=prj)
2224-
assert type(ax) == maxes._subplots.subplot_class_factory(PolarAxes)
2208+
assert type(ax) == mpl.axes._subplots.subplot_class_factory(PolarAxes)
22252209
plt.close()
22262210

22272211

@@ -3324,14 +3308,10 @@ def test_stem_args():
33243308

33253309
def test_stem_dates():
33263310
fig, ax = plt.subplots(1, 1)
3327-
from dateutil import parser
3328-
x = parser.parse("2013-9-28 11:00:00")
3329-
y = 100
3330-
3331-
x1 = parser.parse("2013-9-28 12:00:00")
3332-
y1 = 200
3333-
3334-
ax.stem([x, x1], [y, y1], "*-", use_line_collection=True)
3311+
xs = [dateutil.parser.parse("2013-9-28 11:00:00"),
3312+
dateutil.parser.parse("2013-9-28 12:00:00")]
3313+
ys = [100, 200]
3314+
ax.stem(xs, ys, "*-", use_line_collection=True)
33353315

33363316

33373317
@image_comparison(['hist_stacked_stepfilled_alpha'])
@@ -3977,22 +3957,19 @@ def test_step_linestyle():
39773957

39783958
@image_comparison(['mixed_collection'], remove_text=True)
39793959
def test_mixed_collection():
3980-
from matplotlib import patches
3981-
from matplotlib import collections
3982-
39833960
# First illustrate basic pyplot interface, using defaults where possible.
39843961
fig = plt.figure()
39853962
ax = fig.add_subplot(1, 1, 1)
39863963

3987-
c = patches.Circle((8, 8), radius=4, facecolor='none', edgecolor='green')
3964+
c = mpatches.Circle((8, 8), radius=4, facecolor='none', edgecolor='green')
39883965

39893966
# PDF can optimize this one
3990-
p1 = collections.PatchCollection([c], match_original=True)
3967+
p1 = mpl.collections.PatchCollection([c], match_original=True)
39913968
p1.set_offsets([[0, 0], [24, 24]])
39923969
p1.set_linewidths([1, 5])
39933970

39943971
# PDF can't optimize this one, because the alpha of the edge changes
3995-
p2 = collections.PatchCollection([c], match_original=True)
3972+
p2 = mpl.collections.PatchCollection([c], match_original=True)
39963973
p2.set_offsets([[48, 0], [-32, -16]])
39973974
p2.set_linewidths([1, 5])
39983975
p2.set_edgecolors([[0, 0, 0.1, 1.0], [0, 0, 0.1, 0.5]])
@@ -5960,7 +5937,7 @@ def test_bar_uint8():
59605937
def test_date_timezone_x():
59615938
# Tests issue 5575
59625939
time_index = [datetime.datetime(2016, 2, 22, hour=x,
5963-
tzinfo=dutz.gettz('Canada/Eastern'))
5940+
tzinfo=dateutil.tz.gettz('Canada/Eastern'))
59645941
for x in range(3)]
59655942

59665943
# Same Timezone
@@ -5977,7 +5954,7 @@ def test_date_timezone_x():
59775954
def test_date_timezone_y():
59785955
# Tests issue 5575
59795956
time_index = [datetime.datetime(2016, 2, 22, hour=x,
5980-
tzinfo=dutz.gettz('Canada/Eastern'))
5957+
tzinfo=dateutil.tz.gettz('Canada/Eastern'))
59815958
for x in range(3)]
59825959

59835960
# Same Timezone
@@ -6416,9 +6393,6 @@ def test_spines_properbbox_after_zoom():
64166393

64176394

64186395
def test_cartopy_backcompat():
6419-
import matplotlib
6420-
import matplotlib.axes
6421-
import matplotlib.axes._subplots
64226396

64236397
class Dummy(matplotlib.axes.Axes):
64246398
...

lib/matplotlib/tests/test_backend_pdf.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import os
33
from pathlib import Path
44
import sys
5-
import tempfile
5+
from tempfile import NamedTemporaryFile
66

77
import numpy as np
88
import pytest
@@ -74,8 +74,6 @@ def test_multipage_properfinalize():
7474

7575

7676
def test_multipage_keep_empty():
77-
from matplotlib.backends.backend_pdf import PdfPages
78-
from tempfile import NamedTemporaryFile
7977
# test empty pdf files
8078
# test that an empty pdf is left behind with keep_empty=True (default)
8179
with NamedTemporaryFile(delete=False) as tmp:
@@ -168,7 +166,7 @@ def psfont(*args, **kwargs):
168166
rcParams['text.usetex'] = True
169167
fig, ax = plt.subplots()
170168
ax.text(0.5, 0.5, 'hello')
171-
with tempfile.TemporaryFile() as tmpfile, pytest.raises(ValueError):
169+
with NamedTemporaryFile() as tmpfile, pytest.raises(ValueError):
172170
fig.savefig(tmpfile, format='pdf')
173171

174172

lib/matplotlib/tests/test_backend_qt.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import copy
2+
import signal
23
import sys
34
from unittest import mock
45

@@ -54,7 +55,6 @@ def test_fig_signals(qt_core):
5455
plt.figure()
5556

5657
# Access signals
57-
import signal
5858
event_loop_signal = None
5959

6060
# Callback to fire during event loop: save SIGINT handler, then exit
@@ -259,7 +259,6 @@ def test_double_resize():
259259

260260
@pytest.mark.backend("Qt5Agg")
261261
def test_canvas_reinit():
262-
import matplotlib.pyplot as plt
263262
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
264263

265264
called = False

lib/matplotlib/tests/test_collections.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from numpy.testing import assert_array_equal, assert_array_almost_equal
99
import pytest
1010

11+
import matplotlib as mpl
1112
import matplotlib.pyplot as plt
1213
import matplotlib.collections as mcollections
1314
import matplotlib.transforms as mtransforms
@@ -591,9 +592,8 @@ def test_pathcollection_legend_elements():
591592
assert_array_almost_equal(actsizes, labeledsizes)
592593
l4 = ax.legend(h, l, loc=3)
593594

594-
import matplotlib.ticker as mticker
595-
loc = mticker.MaxNLocator(nbins=9, min_n_ticks=9-1,
596-
steps=[1, 2, 2.5, 3, 5, 6, 8, 10])
595+
loc = mpl.ticker.MaxNLocator(nbins=9, min_n_ticks=9-1,
596+
steps=[1, 2, 2.5, 3, 5, 6, 8, 10])
597597
h5, lab5 = sc.legend_elements(num=loc)
598598
assert len(h2) == len(h5)
599599

0 commit comments

Comments
 (0)
0