From 220894fbc094bc3946be61c0fe5e30daa396385b Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Fri, 25 Sep 2020 03:19:47 +0200 Subject: [PATCH] Random test cleanups Mostly suggestions by a code checker and readability improvements. --- lib/matplotlib/tests/test_afm.py | 4 +- lib/matplotlib/tests/test_agg.py | 20 +++--- lib/matplotlib/tests/test_axes.py | 85 ++++++++++++------------- lib/matplotlib/tests/test_bbox_tight.py | 14 ++-- lib/matplotlib/tests/test_cbook.py | 29 ++++----- lib/matplotlib/tests/test_text.py | 22 +++---- 6 files changed, 85 insertions(+), 89 deletions(-) diff --git a/lib/matplotlib/tests/test_afm.py b/lib/matplotlib/tests/test_afm.py index 2bbbe1f454a5..2d54c16cb402 100644 --- a/lib/matplotlib/tests/test_afm.py +++ b/lib/matplotlib/tests/test_afm.py @@ -107,7 +107,7 @@ def test_font_manager_weight_normalization(): def test_bad_afm(afm_data): fh = BytesIO(afm_data) with pytest.raises(RuntimeError): - header = afm._parse_header(fh) + afm._parse_header(fh) @pytest.mark.parametrize( @@ -132,6 +132,6 @@ def test_bad_afm(afm_data): def test_malformed_header(afm_data, caplog): fh = BytesIO(afm_data) with caplog.at_level(logging.ERROR): - header = afm._parse_header(fh) + afm._parse_header(fh) assert len(caplog.records) == 1 diff --git a/lib/matplotlib/tests/test_agg.py b/lib/matplotlib/tests/test_agg.py index b425887e91b0..4d34ef3ccd4a 100644 --- a/lib/matplotlib/tests/test_agg.py +++ b/lib/matplotlib/tests/test_agg.py @@ -161,30 +161,30 @@ def process_image(self, padded_src, dpi): fig, ax = plt.subplots() # draw lines - l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-", - mec="b", mfc="w", lw=5, mew=3, ms=10, label="Line 1") - l2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "ro-", - mec="r", mfc="w", lw=5, mew=3, ms=10, label="Line 1") + line1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-", + mec="b", mfc="w", lw=5, mew=3, ms=10, label="Line 1") + line2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "ro-", + mec="r", mfc="w", lw=5, mew=3, ms=10, label="Line 1") gauss = DropShadowFilter(4) - for l in [l1, l2]: + for line in [line1, line2]: # draw shadows with same lines with slight offset. - xx = l.get_xdata() - yy = l.get_ydata() + xx = line.get_xdata() + yy = line.get_ydata() shadow, = ax.plot(xx, yy) - shadow.update_from(l) + shadow.update_from(line) # offset transform - ot = mtransforms.offset_copy(l.get_transform(), ax.figure, + ot = mtransforms.offset_copy(line.get_transform(), ax.figure, x=4.0, y=-6.0, units='points') shadow.set_transform(ot) # adjust zorder of the shadow lines so that it is drawn below the # original lines - shadow.set_zorder(l.get_zorder() - 0.5) + shadow.set_zorder(line.get_zorder() - 0.5) shadow.set_agg_filter(gauss) shadow.set_rasterized(True) # to support mixed-mode renderers diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 063fe8f186c6..b0bd982bc27c 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -2961,7 +2961,7 @@ def test_boxplot_mod_artist_after_plotting(): def test_vert_violinplot_baseline(): # First 9 digits of frac(sqrt(2)) np.random.seed(414213562) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax = plt.axes() ax.violinplot(data, positions=range(4), showmeans=0, showextrema=0, showmedians=0) @@ -2969,7 +2969,6 @@ def test_vert_violinplot_baseline(): # Reuse testcase from above for a labeled data test data = {"d": data} fig, ax = plt.subplots() - ax = plt.axes() ax.violinplot("d", positions=range(4), showmeans=0, showextrema=0, showmedians=0, data=data) @@ -2979,7 +2978,7 @@ def test_vert_violinplot_showmeans(): ax = plt.axes() # First 9 digits of frac(sqrt(3)) np.random.seed(732050807) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax.violinplot(data, positions=range(4), showmeans=1, showextrema=0, showmedians=0) @@ -2989,7 +2988,7 @@ def test_vert_violinplot_showextrema(): ax = plt.axes() # First 9 digits of frac(sqrt(5)) np.random.seed(236067977) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax.violinplot(data, positions=range(4), showmeans=0, showextrema=1, showmedians=0) @@ -2999,7 +2998,7 @@ def test_vert_violinplot_showmedians(): ax = plt.axes() # First 9 digits of frac(sqrt(7)) np.random.seed(645751311) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax.violinplot(data, positions=range(4), showmeans=0, showextrema=0, showmedians=1) @@ -3009,7 +3008,7 @@ def test_vert_violinplot_showall(): ax = plt.axes() # First 9 digits of frac(sqrt(11)) np.random.seed(316624790) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax.violinplot(data, positions=range(4), showmeans=1, showextrema=1, showmedians=1, quantiles=[[0.1, 0.9], [0.2, 0.8], [0.3, 0.7], [0.4, 0.6]]) @@ -3020,7 +3019,7 @@ def test_vert_violinplot_custompoints_10(): ax = plt.axes() # First 9 digits of frac(sqrt(13)) np.random.seed(605551275) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax.violinplot(data, positions=range(4), showmeans=0, showextrema=0, showmedians=0, points=10) @@ -3030,7 +3029,7 @@ def test_vert_violinplot_custompoints_200(): ax = plt.axes() # First 9 digits of frac(sqrt(17)) np.random.seed(123105625) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax.violinplot(data, positions=range(4), showmeans=0, showextrema=0, showmedians=0, points=200) @@ -3040,7 +3039,7 @@ def test_horiz_violinplot_baseline(): ax = plt.axes() # First 9 digits of frac(sqrt(19)) np.random.seed(358898943) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=0, showextrema=0, showmedians=0) @@ -3050,7 +3049,7 @@ def test_horiz_violinplot_showmedians(): ax = plt.axes() # First 9 digits of frac(sqrt(23)) np.random.seed(795831523) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=0, showextrema=0, showmedians=1) @@ -3060,7 +3059,7 @@ def test_horiz_violinplot_showmeans(): ax = plt.axes() # First 9 digits of frac(sqrt(29)) np.random.seed(385164807) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=1, showextrema=0, showmedians=0) @@ -3070,7 +3069,7 @@ def test_horiz_violinplot_showextrema(): ax = plt.axes() # First 9 digits of frac(sqrt(31)) np.random.seed(567764362) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=0, showextrema=1, showmedians=0) @@ -3080,7 +3079,7 @@ def test_horiz_violinplot_showall(): ax = plt.axes() # First 9 digits of frac(sqrt(37)) np.random.seed(82762530) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=1, showextrema=1, showmedians=1, quantiles=[[0.1, 0.9], [0.2, 0.8], [0.3, 0.7], [0.4, 0.6]]) @@ -3091,7 +3090,7 @@ def test_horiz_violinplot_custompoints_10(): ax = plt.axes() # First 9 digits of frac(sqrt(41)) np.random.seed(403124237) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=0, showextrema=0, showmedians=0, points=10) @@ -3101,7 +3100,7 @@ def test_horiz_violinplot_custompoints_200(): ax = plt.axes() # First 9 digits of frac(sqrt(43)) np.random.seed(557438524) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] ax.violinplot(data, positions=range(4), vert=False, showmeans=0, showextrema=0, showmedians=0, points=200) @@ -3110,7 +3109,7 @@ def test_violinplot_bad_positions(): ax = plt.axes() # First 9 digits of frac(sqrt(47)) np.random.seed(855654600) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] with pytest.raises(ValueError): ax.violinplot(data, positions=range(5)) @@ -3119,7 +3118,7 @@ def test_violinplot_bad_widths(): ax = plt.axes() # First 9 digits of frac(sqrt(53)) np.random.seed(280109889) - data = [np.random.normal(size=100) for i in range(4)] + data = [np.random.normal(size=100) for _ in range(4)] with pytest.raises(ValueError): ax.violinplot(data, positions=range(4), widths=[1, 2, 3]) @@ -3718,16 +3717,16 @@ def test_hist_emptydata(): def test_hist_labels(): # test singleton labels OK fig, ax = plt.subplots() - l = ax.hist([0, 1], label=0) - assert l[2][0].get_label() == '0' - l = ax.hist([0, 1], label=[0]) - assert l[2][0].get_label() == '0' - l = ax.hist([0, 1], label=None) - assert l[2][0].get_label() == '_nolegend_' - l = ax.hist([0, 1], label='0') - assert l[2][0].get_label() == '0' - l = ax.hist([0, 1], label='00') - assert l[2][0].get_label() == '00' + _, _, bars = ax.hist([0, 1], label=0) + assert bars[0].get_label() == '0' + _, _, bars = ax.hist([0, 1], label=[0]) + assert bars[0].get_label() == '0' + _, _, bars = ax.hist([0, 1], label=None) + assert bars[0].get_label() == '_nolegend_' + _, _, bars = ax.hist([0, 1], label='0') + assert bars[0].get_label() == '0' + _, _, bars = ax.hist([0, 1], label='00') + assert bars[0].get_label() == '00' @image_comparison(['transparent_markers'], remove_text=True) @@ -3908,7 +3907,7 @@ def test_eventplot_defaults(): ]) def test_eventplot_colors(colors): """Test the *colors* parameter of eventplot. Inspired by issue #8193.""" - data = [[i] for i in range(4)] # 4 successive events of different nature + data = [[0], [1], [2], [3]] # 4 successive events of different nature # Build the list of the expected colors expected = [c if c is not None else 'C0' for c in colors] @@ -4557,9 +4556,9 @@ def test_rcparam_grid_minor(): matplotlib.rcParams['axes.grid'] = True values = ( - (('both'), (True, True)), - (('major'), (True, False)), - (('minor'), (False, True)) + ('both', (True, True)), + ('major', (True, False)), + ('minor', (False, True)) ) for locator, result in values: @@ -4576,7 +4575,6 @@ def test_vline_limit(): ax = fig.gca() ax.axvline(0.5) ax.plot([-0.1, 0, 0.2, 0.1]) - (ymin, ymax) = ax.get_ylim() assert_allclose(ax.get_ylim(), (-.1, .2)) @@ -4674,10 +4672,10 @@ def test_relim_visible_only(): ax.plot(x1, y1) assert ax.get_xlim() == x1 assert ax.get_ylim() == y1 - l = ax.plot(x2, y2) + line, = ax.plot(x2, y2) assert ax.get_xlim() == x2 assert ax.get_ylim() == y2 - l[0].set_visible(False) + line.set_visible(False) assert ax.get_xlim() == x2 assert ax.get_ylim() == y2 @@ -5109,7 +5107,7 @@ def test_rc_spines(): 'axes.spines.top': False, 'axes.spines.bottom': False} with matplotlib.rc_context(rc_dict): - fig, ax = plt.subplots() + plt.subplots() # create a figure and axes with the spine properties @image_comparison(['rc_grid.png'], savefig_kwarg={'dpi': 40}) @@ -5484,7 +5482,7 @@ def test_adjust_numtick_aspect(): @image_comparison(["auto_numticks.png"], style='default') def test_auto_numticks(): # Make tiny, empty subplots, verify that there are only 3 ticks. - fig, axs = plt.subplots(4, 4) + plt.subplots(4, 4) @image_comparison(["auto_numticks_log.png"], style='default') @@ -6121,7 +6119,7 @@ class DummySubplot(matplotlib.axes.SubplotBase, Dummy): assert DummySubplot is FactoryDummySubplot -def test_gettightbbox_ignoreNaN(): +def test_gettightbbox_ignore_nan(): fig, ax = plt.subplots() remove_ticks_and_titles(fig) ax.text(np.NaN, 1, 'Boo') @@ -6196,6 +6194,7 @@ def test_secondary_fail(): def test_secondary_resize(): fig, ax = plt.subplots(figsize=(10, 5)) ax.plot(np.arange(2, 11), np.arange(2, 11)) + def invert(x): with np.errstate(divide='ignore'): return 1 / x @@ -6209,6 +6208,7 @@ def invert(x): def test_secondary_minorloc(): fig, ax = plt.subplots(figsize=(10, 5)) ax.plot(np.arange(2, 11), np.arange(2, 11)) + def invert(x): with np.errstate(divide='ignore'): return 1 / x @@ -6332,10 +6332,6 @@ def test_nodecorator(): bbaxis, bbspines, bbax, bbtb = color_boxes(fig, ax) # test the axis bboxes - target = [ - None, - None - ] for nn, b in enumerate(bbaxis): assert b is None @@ -6366,14 +6362,15 @@ def test_displaced_spine(): fig.canvas.draw() bbaxis, bbspines, bbax, bbtb = color_boxes(fig, ax) - target = [ + targets = [ [150., 24., 930., 11.111111], [150.0, 1080.0, 930.0, 0.0], [150.0, 119.9999, 11.111, 960.0], [1068.8888, 119.9999, 11.111, 960.0] ] - for nn, b in enumerate(bbspines): - targetbb = mtransforms.Bbox.from_bounds(*target[nn]) + for target, bbspine in zip(targets, bbspines): + targetbb = mtransforms.Bbox.from_bounds(*target) + assert_allclose(bbspine.bounds, targetbb.bounds, atol=1e-2) target = [150.0, 119.99999999999997, 930.0, 960.0] targetbb = mtransforms.Bbox.from_bounds(*target) diff --git a/lib/matplotlib/tests/test_bbox_tight.py b/lib/matplotlib/tests/test_bbox_tight.py index dfe1ac7da8bc..c8277a0f2694 100644 --- a/lib/matplotlib/tests/test_bbox_tight.py +++ b/lib/matplotlib/tests/test_bbox_tight.py @@ -19,26 +19,26 @@ def test_bbox_inches_tight(): [78415, 81858, 150656, 193263, 69638], [139361, 331509, 343164, 781380, 52269]] - colLabels = rowLabels = [''] * 5 + col_labels = row_labels = [''] * 5 rows = len(data) - ind = np.arange(len(colLabels)) + 0.3 # the x locations for the groups - cellText = [] + ind = np.arange(len(col_labels)) + 0.3 # the x locations for the groups + cell_text = [] width = 0.4 # the width of the bars - yoff = np.zeros(len(colLabels)) + yoff = np.zeros(len(col_labels)) # the bottom values for stacked bar chart fig, ax = plt.subplots(1, 1) for row in range(rows): ax.bar(ind, data[row], width, bottom=yoff, align='edge', color='b') yoff = yoff + data[row] - cellText.append(['']) + cell_text.append(['']) plt.xticks([]) plt.xlim(0, 5) plt.legend([''] * 5, loc=(1.2, 0.2)) fig.legend([''] * 5, bbox_to_anchor=(0, 0.2), loc='lower left') # Add a table at the bottom of the axes - cellText.reverse() - plt.table(cellText=cellText, rowLabels=rowLabels, colLabels=colLabels, + cell_text.reverse() + plt.table(cellText=cell_text, rowLabels=row_labels, colLabels=col_labels, loc='bottom') diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index f4671c75b4aa..357fc2bb50c6 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -144,7 +144,6 @@ def test_results_whiskers_percentiles(self): def test_results_withlabels(self): labels = ['Test1', 2, 'ardvark', 4] results = cbook.boxplot_stats(self.data, labels=labels) - res = results[0] for lab, res in zip(labels, results): assert res['label'] == lab @@ -248,10 +247,10 @@ def raising_cb_reg(func): class TestException(Exception): pass - def raising_function(): + def raise_runtime_error(): raise RuntimeError - def raising_function_VE(): + def raise_value_error(): raise ValueError def transformer(excp): @@ -261,15 +260,15 @@ def transformer(excp): # old default cb_old = cbook.CallbackRegistry(exception_handler=None) - cb_old.connect('foo', raising_function) + cb_old.connect('foo', raise_runtime_error) # filter cb_filt = cbook.CallbackRegistry(exception_handler=transformer) - cb_filt.connect('foo', raising_function) + cb_filt.connect('foo', raise_runtime_error) # filter cb_filt_pass = cbook.CallbackRegistry(exception_handler=transformer) - cb_filt_pass.connect('foo', raising_function_VE) + cb_filt_pass.connect('foo', raise_value_error) return pytest.mark.parametrize('cb, excp', [[cb_old, RuntimeError], @@ -434,9 +433,9 @@ def test_step_fails(args): def test_grouper(): - class dummy: + class Dummy: pass - a, b, c, d, e = objs = [dummy() for j in range(5)] + a, b, c, d, e = objs = [Dummy() for _ in range(5)] g = cbook.Grouper() g.join(*objs) assert set(list(g)[0]) == set(objs) @@ -454,9 +453,9 @@ class dummy: def test_grouper_private(): - class dummy: + class Dummy: pass - objs = [dummy() for j in range(5)] + objs = [Dummy() for _ in range(5)] g = cbook.Grouper() g.join(*objs) # reach in and touch the internals ! @@ -484,13 +483,13 @@ def test_flatiter(): def test_reshape2d(): - class dummy: + class Dummy: pass xnew = cbook._reshape_2D([], 'x') assert np.shape(xnew) == (1, 0) - x = [dummy() for j in range(5)] + x = [Dummy() for _ in range(5)] xnew = cbook._reshape_2D(x, 'x') assert np.shape(xnew) == (1, 5) @@ -499,7 +498,7 @@ class dummy: xnew = cbook._reshape_2D(x, 'x') assert np.shape(xnew) == (1, 5) - x = [[dummy() for j in range(5)] for i in range(3)] + x = [[Dummy() for _ in range(5)] for _ in range(3)] xnew = cbook._reshape_2D(x, 'x') assert np.shape(xnew) == (3, 5) @@ -676,9 +675,9 @@ def divisors(n): def test_setattr_cm(): class A: - cls_level = object() override = object() + def __init__(self): self.aardvark = 'aardvark' self.override = 'override' @@ -688,7 +687,7 @@ def meth(self): ... @classmethod - def classy(klass): + def classy(cls): ... @staticmethod diff --git a/lib/matplotlib/tests/test_text.py b/lib/matplotlib/tests/test_text.py index 22f06728a808..38331a35762a 100644 --- a/lib/matplotlib/tests/test_text.py +++ b/lib/matplotlib/tests/test_text.py @@ -37,7 +37,7 @@ def find_matplotlib_font(**kw): plt.figure() ax = plt.subplot(1, 1, 1) - normalFont = find_matplotlib_font( + normal_font = find_matplotlib_font( family="sans-serif", style="normal", variant="normal", @@ -46,9 +46,9 @@ def find_matplotlib_font(**kw): "Normal Font", (0.1, 0.1), xycoords='axes fraction', - fontproperties=normalFont) + fontproperties=normal_font) - boldFont = find_matplotlib_font( + bold_font = find_matplotlib_font( family="Foo", style="normal", variant="normal", @@ -59,9 +59,9 @@ def find_matplotlib_font(**kw): "Bold Font", (0.1, 0.2), xycoords='axes fraction', - fontproperties=boldFont) + fontproperties=bold_font) - boldItemFont = find_matplotlib_font( + bold_italic_font = find_matplotlib_font( family="sans serif", style="italic", variant="normal", @@ -72,9 +72,9 @@ def find_matplotlib_font(**kw): "Bold Italic Font", (0.1, 0.3), xycoords='axes fraction', - fontproperties=boldItemFont) + fontproperties=bold_italic_font) - lightFont = find_matplotlib_font( + light_font = find_matplotlib_font( family="sans-serif", style="normal", variant="normal", @@ -85,9 +85,9 @@ def find_matplotlib_font(**kw): "Light Font", (0.1, 0.4), xycoords='axes fraction', - fontproperties=lightFont) + fontproperties=light_font) - condensedFont = find_matplotlib_font( + condensed_font = find_matplotlib_font( family="sans-serif", style="normal", variant="normal", @@ -98,7 +98,7 @@ def find_matplotlib_font(**kw): "Condensed Font", (0.1, 0.5), xycoords='axes fraction', - fontproperties=condensedFont) + fontproperties=condensed_font) ax.set_xticks([]) ax.set_yticks([]) @@ -638,7 +638,7 @@ def test_large_subscript_title(): ax.set_xticklabels('') ax = axs[1] - tt = ax.set_title(r'$\sum_{i} x_i$', y=1.01) + ax.set_title(r'$\sum_{i} x_i$', y=1.01) ax.set_title('Old Way', loc='left') ax.set_xticklabels('')