Skip to content

Pep8 on many tests #2059

Merged
merged 4 commits into from Aug 17, 2013
+248 −208
View
13 lib/matplotlib/tests/__init__.py
@@ -1,28 +1,31 @@
from __future__ import print_function
-from matplotlib import rcParams, rcdefaults, use
import difflib
+from matplotlib import rcParams, rcdefaults, use
+
_multiprocess_can_split_ = True
def setup():
- use('Agg', warn=False) # use Agg backend for these tests
+ use('Agg', warn=False) # use Agg backend for these tests
# These settings *must* be hardcoded for running the comparison
# tests and are not necessarily the default values as specified in
# rcsetup.py
- rcdefaults() # Start with all defaults
+ rcdefaults() # Start with all defaults
rcParams['font.family'] = 'Bitstream Vera Sans'
rcParams['text.hinting'] = False
rcParams['text.hinting_factor'] = 8
def assert_str_equal(reference_str, test_str,
- format_str='String {str1} and {str2} do not match:\n{differences}'):
+ format_str=('String {str1} and {str2} do not '
+ 'match:\n{differences}')):
"""
- Assert the two strings are equal. If not, fail and print their diffs using difflib.
+ Assert the two strings are equal. If not, fail and print their
+ diffs using difflib.
"""
if reference_str != test_str:
View
6 lib/matplotlib/tests/test_agg.py
@@ -1,12 +1,9 @@
from __future__ import print_function
-
import os
import tempfile
-
from numpy.testing import assert_array_almost_equal
-
from matplotlib.image import imread
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
@@ -102,7 +99,8 @@ def report_memory(i):
## avgMem = (end - start) / float(N)
## print 'Average memory consumed per loop: %1.4f\n' % (avgMem)
-## #TODO: Verify the expected mem usage and approximate tolerance that should be used
+## #TODO: Verify the expected mem usage and approximate tolerance that
+## # should be used
## #self.checkClose( 0.32, avgMem, absTol = 0.1 )
## # w/o text and w/o write_png: Average memory consumed per loop: 0.02
View
8 lib/matplotlib/tests/test_animation.py
@@ -1,6 +1,9 @@
+from __future__ import print_function
import os
import tempfile
+
import numpy as np
+
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.testing.noseclasses import KnownFailureTest
@@ -13,7 +16,6 @@
imagemagick='gif', imagemagick_file='gif')
-
# Smoke test for saving animations. In the future, we should probably
# design more sophisticated tests which compare resulting frames a-la
# matplotlib.testing.image_comparison
@@ -46,6 +48,6 @@ def animate(i):
anim.save(F.name, fps=30, writer=writer)
-if __name__ == '__main__':
+if __name__ == "__main__":
import nose
- nose.runmodule()
+ nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
View
13 lib/matplotlib/tests/test_arrow_patches.py
@@ -1,20 +1,24 @@
+from __future__ import print_function
+
import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison
import matplotlib
+
def draw_arrow(ax, t, r):
- ax.annotate('', xy=(0.5, 0.5+r), xytext=(0.5, 0.5), size=30,
+ ax.annotate('', xy=(0.5, 0.5 + r), xytext=(0.5, 0.5), size=30,
arrowprops=dict(arrowstyle=t,
fc="b", ec='k'))
+
@image_comparison(baseline_images=['fancyarrow_test_image'])
def test_fancyarrow():
r = [0.4, 0.3, 0.2, 0.1]
t = ["fancy", "simple", matplotlib.patches.ArrowStyle.Fancy()]
fig, axes = plt.subplots(len(t), len(r), squeeze=False,
subplot_kw=dict(aspect=True),
- figsize=(8, 4.5))
+ figsize=(8, 4.5))
for i_r, r1 in enumerate(r):
for i_t, t1 in enumerate(t):
@@ -23,7 +27,6 @@ def test_fancyarrow():
ax.tick_params(labelleft=False, labelbottom=False)
-if __name__=='__main__':
+if __name__ == '__main__':
import nose
- nose.runmodule(argv=['-s','--with-doctest'], exit=False)
-
+ nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
View
18 lib/matplotlib/tests/test_artist.py
@@ -1,11 +1,7 @@
from __future__ import print_function
-import copy
-
-
import numpy as np
-
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.path as mpath
@@ -93,16 +89,6 @@ def test_collection_transform_of_none():
assert isinstance(c._transOffset, mtrans.IdentityTransform)
-def test_point_in_path():
@pelson
Matplotlib Developers member
pelson added a note May 24, 2013

Moved to test_path.py.

@mdboom
Matplotlib Developers member
mdboom added a note May 24, 2013

Great. Over time, I'd like to move a lot of stuff out of test_axes as well so that no one file so dominates the run time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
- # Test #1787
- verts2 = [(0,0), (0,1), (1,1), (1,0), (0,0)]
-
- path = mpath.Path(verts2, closed=True)
- points = [(0.5,0.5), (1.5,0.5)]
-
- assert np.all(path.contains_points(points) == [True, False])
-
-
@image_comparison(baseline_images=["clip_path_clipping"], remove_text=True)
def test_clipping():
exterior = mpath.Path.unit_rectangle().deepcopy()
@@ -134,6 +120,6 @@ def test_clipping():
ax1.set_ylim([-3, 3])
-if __name__=='__main__':
+if __name__ == '__main__':
import nose
- nose.runmodule(argv=['-s','--with-doctest'], exit=False)
+ nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
View
11 lib/matplotlib/tests/test_backend_pdf.py
@@ -1,9 +1,11 @@
# -*- encoding: utf-8 -*-
+import io
from matplotlib import rcParams
from matplotlib import pyplot as plt
from matplotlib.testing.decorators import image_comparison, knownfailureif
+
@image_comparison(baseline_images=['pdf_use14corefonts'], extensions=['pdf'])
def test_use14corefonts():
rcParams['pdf.use14corefonts'] = True
@@ -24,11 +26,14 @@ def test_use14corefonts():
def test_type42():
- import io
-
rcParams['pdf.fonttype'] = 42
fig = plt.figure()
ax = fig.add_subplot(111)
- ax.plot([1,2,3])
+ ax.plot([1, 2, 3])
fig.savefig(io.BytesIO())
+
+
+if __name__ == "__main__":
+ import nose
+ nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
View
24 lib/matplotlib/tests/test_backend_pgf.py
@@ -1,16 +1,18 @@
# -*- encoding: utf-8 -*-
-
import os
import shutil
+
import numpy as np
import nose
from nose.plugins.skip import SkipTest
+
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.compat import subprocess
from matplotlib.testing.compare import compare_images, ImageComparisonFailure
from matplotlib.testing.decorators import _image_directories
+
baseline_dir, result_dir = _image_directories(lambda: 'dummy func')
@@ -59,18 +61,20 @@ def compare_figure(fname):
shutil.copyfile(os.path.join(baseline_dir, fname), expected)
err = compare_images(expected, actual, tol=14)
if err:
- raise ImageComparisonFailure('images not close: %s vs. %s' % (actual, expected))
+ raise ImageComparisonFailure('images not close: %s vs. '
+ '%s' % (actual, expected))
-###############################################################################
def create_figure():
plt.figure()
x = np.linspace(0, 1, 15)
- plt.plot(x, x**2, "b-")
- plt.plot(x, 1-x**2, "g>")
+ plt.plot(x, x ** 2, "b-")
+ plt.plot(x, 1 - x**2, "g>")
plt.plot([0.9], [0.5], "ro", markersize=3)
- plt.text(0.9, 0.5, u'unicode (ü, °, µ) and math ($\\mu_i = x_i^2$)', ha='right', fontsize=20)
- plt.ylabel(u'sans-serif with math $\\frac{\\sqrt{x}}{y^2}$..', family='sans-serif')
+ plt.text(0.9, 0.5, u'unicode (ü, °, µ) and math ($\\mu_i = x_i^2$)',
+ ha='right', fontsize=20)
+ plt.ylabel(u'sans-serif with math $\\frac{\\sqrt{x}}{y^2}$..',
+ family='sans-serif')
# test compiling a figure to pdf with xelatex
@@ -80,7 +84,7 @@ def test_xelatex():
raise SkipTest('xelatex + pgf is required')
rc_xelatex = {'font.family': 'serif',
- 'pgf.rcfonts': False,}
+ 'pgf.rcfonts': False}
mpl.rcParams.update(rc_xelatex)
create_figure()
compare_figure('pgf_xelatex.pdf')
@@ -128,7 +132,7 @@ def test_rcupdate():
for i, rc_set in enumerate(rc_sets):
mpl.rcParams.update(rc_set)
create_figure()
- compare_figure('pgf_rcupdate%d.pdf' % (i+1))
+ compare_figure('pgf_rcupdate%d.pdf' % (i + 1))
# test backend-side clipping, since large numbers are not supported by TeX
@@ -147,4 +151,4 @@ def test_pathclip():
if __name__ == '__main__':
import nose
- nose.runmodule(argv=['-s','--with-doctest'], exit=False)
+ nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
View
32 lib/matplotlib/tests/test_backend_svg.py
@@ -1,43 +1,49 @@
from __future__ import print_function
-import matplotlib.pyplot as plt
-import numpy as np
-import sys
from io import BytesIO
import xml.parsers.expat
-from matplotlib.testing.decorators import knownfailureif, cleanup
+
+import numpy as np
+
+import matplotlib.pyplot as plt
+from matplotlib.testing.decorators import cleanup
from matplotlib.testing.decorators import image_comparison
+
@cleanup
def test_visibility():
- # This is SF 2856495. See
- # https://sourceforge.net/tracker/?func=detail&aid=2856495&group_id=80706&atid=560720
- fig=plt.figure()
- ax=fig.add_subplot(1,1,1)
+ fig = plt.figure()
+ ax = fig.add_subplot(111)
- x = np.linspace(0,4*np.pi,50)
+ x = np.linspace(0, 4 * np.pi, 50)
y = np.sin(x)
yerr = np.ones_like(y)
- a,b,c=ax.errorbar(x,y,yerr=yerr,fmt='ko')
+ a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko')
for artist in b:
artist.set_visible(False)
fd = BytesIO()
- fig.savefig(fd,format='svg')
+ fig.savefig(fd, format='svg')
fd.seek(0)
buf = fd.read()
fd.close()
parser = xml.parsers.expat.ParserCreate()
- parser.Parse(buf) # this will raise ExpatError if the svg is invalid
+ parser.Parse(buf) # this will raise ExpatError if the svg is invalid
+
@image_comparison(baseline_images=['noscale'], remove_text=True)
def test_noscale():
X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1))
- Z = np.sin(Y**2)
+ Z = np.sin(Y ** 2)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.imshow(Z, cmap='gray')
plt.rcParams['svg.image_noscale'] = True
+
+
+if __name__ == '__main__':
+ import nose
+ nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
View
21 lib/matplotlib/tests/test_basic.py
@@ -1,16 +1,21 @@
from __future__ import print_function
+
from nose.tools import assert_equal
+
from matplotlib.testing.decorators import knownfailureif
-import sys
+from pylab import *
+
def test_simple():
- assert_equal(1+1,2)
+ assert_equal(1 + 1, 2)
+
@knownfailureif(True)
def test_simple_knownfail():
- assert_equal(1+1,3)
+ # Test the known fail mechanism.
+ assert_equal(1 + 1, 3)
+
-from pylab import *
def test_override_builtins():
ok_to_override = set([
'__name__',
@@ -20,7 +25,6 @@ def test_override_builtins():
'all',
'sum'
])
-
if sys.version_info[0] >= 3:
builtins = sys.modules['builtins']
else:
@@ -30,8 +34,13 @@ def test_override_builtins():
for key in globals().keys():
if key in dir(builtins):
if (globals()[key] != getattr(builtins, key) and
- key not in ok_to_override):
+ key not in ok_to_override):
print("'%s' was overridden in globals()." % key)
overridden = True
assert not overridden
+
+
+if __name__ == '__main__':
+ import nose
+ nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
View
26 lib/matplotlib/tests/test_bbox_tight.py
@@ -1,22 +1,26 @@
+from __future__ import print_function
+
+import numpy as np
+
from matplotlib import rcParams, rcParamsDefault
from matplotlib.testing.decorators import image_comparison
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
from matplotlib.ticker import FuncFormatter
-import numpy as np
+
@image_comparison(baseline_images=['bbox_inches_tight'], remove_text=True,
savefig_kwarg=dict(bbox_inches='tight'), tol=15)
def test_bbox_inches_tight():
- "Test that a figure saved using bbox_inches'tight' is clipped right"
+ #: Test that a figure saved using bbox_inches='tight' is clipped right
rcParams.update(rcParamsDefault)
- data = [[ 66386, 174296, 75131, 577908, 32015],
- [ 58230, 381139, 78045, 99308, 160454],
- [ 89135, 80552, 152558, 497981, 603535],
- [ 78415, 81858, 150656, 193263, 69638],
- [ 139361, 331509, 343164, 781380, 52269]]
+ data = [[ 66386, 174296, 75131, 577908, 32015],
+ [ 58230, 381139, 78045, 99308, 160454],
+ [ 89135, 80552, 152558, 497981, 603535],
+ [ 78415, 81858, 150656, 193263, 69638],
+ [139361, 331509, 343164, 781380, 52269]]
colLabels = rowLabels = [''] * 5
@@ -26,13 +30,13 @@ def test_bbox_inches_tight():
width = 0.4 # the width of the bars
yoff = np.array([0.0] * len(colLabels))
# the bottom values for stacked bar chart
- fig, ax = plt.subplots(1,1)
+ fig, ax = plt.subplots(1, 1)
for row in xrange(rows):
plt.bar(ind, data[row], width, bottom=yoff)
yoff = yoff + data[row]
cellText.append([''])
plt.xticks([])
- plt.legend([''] * 5, loc = (1.2, 0.2))
+ plt.legend([''] * 5, loc=(1.2, 0.2))
# Add a table at the bottom of the axes
cellText.reverse()
the_table = plt.table(cellText=cellText,
@@ -71,8 +75,8 @@ def test_bbox_inches_tight_clipping():
# make a massive rectangle and clip it with a path
patch = mpatches.Rectangle([-50, -50], 100, 100,
- transform=ax.transData,
- facecolor='blue', alpha=0.5)
+ transform=ax.transData,
+ facecolor='blue', alpha=0.5)
path = mpath.Path.unit_regular_star(5).deepcopy()
path.vertices *= 0.25
View
29 lib/matplotlib/tests/test_cbook.py
@@ -1,21 +1,27 @@
from __future__ import print_function
+
+from datetime import datetime
+
+from nose.tools import assert_equal, raises
import numpy as np
from numpy.testing.utils import assert_array_equal
+
import matplotlib.cbook as cbook
import matplotlib.colors as mcolors
-from nose.tools import assert_equal, raises
-from datetime import datetime
+from matplotlib.cbook import delete_masked_points as dmp
+
def test_is_string_like():
- y = np.arange( 10 )
- assert_equal( cbook.is_string_like( y ), False )
+ y = np.arange(10)
+ assert_equal(cbook.is_string_like(y), False)
y.shape = 10, 1
- assert_equal( cbook.is_string_like( y ), False )
+ assert_equal(cbook.is_string_like(y), False)
y.shape = 1, 10
- assert_equal( cbook.is_string_like( y ), False )
+ assert_equal(cbook.is_string_like(y), False)
+
+ assert cbook.is_string_like("hello world")
+ assert_equal(cbook.is_string_like(10), False)
- assert cbook.is_string_like( "hello world" )
- assert_equal( cbook.is_string_like(10), False )
def test_restrict_dict():
d = {'foo': 'bar', 1: 2}
@@ -27,18 +33,17 @@ def test_restrict_dict():
assert_equal(d3, {'foo': 'bar'})
d4 = cbook.restrict_dict(d, {})
assert_equal(d4, {})
- d5 = cbook.restrict_dict(d, set(['foo',2]))
+ d5 = cbook.restrict_dict(d, set(['foo', 2]))
assert_equal(d5, {'foo': 'bar'})
# check that d was not modified
assert_equal(d, {'foo': 'bar', 1: 2})
-from matplotlib.cbook import delete_masked_points as dmp
class Test_delete_masked_points:
def setUp(self):
self.mask1 = [False, False, True, True, False, False]
- self.arr0 = np.arange(1.0,7.0)
- self.arr1 = [1,2,3,np.nan,np.nan,6]
+ self.arr0 = np.arange(1.0, 7.0)
+ self.arr1 = [1, 2, 3, np.nan, np.nan, 6]
self.arr2 = np.array(self.arr1)
self.arr3 = np.ma.array(self.arr2, mask=self.mask1)
self.arr_s = ['a', 'b', 'c', 'd', 'e', 'f']
View
17 lib/matplotlib/tests/test_coding_standards.py
@@ -61,32 +61,15 @@ class StandardReportWithExclusions(pep8.StandardReport):
'*/matplotlib/tri/triinterpolate.py',
'*/matplotlib/tri/tripcolor.py',
'*/matplotlib/tri/triplot.py',
- '*/matplotlib/tests/__init__.py',
- '*/matplotlib/tests/test_agg.py',
- '*/matplotlib/tests/test_animation.py',
- '*/matplotlib/tests/test_arrow_patches.py',
- '*/matplotlib/tests/test_artist.py',
'*/matplotlib/tests/test_axes.py',
- '*/matplotlib/tests/test_backend_pdf.py',
- '*/matplotlib/tests/test_backend_pgf.py',
- '*/matplotlib/tests/test_backend_svg.py',
- '*/matplotlib/tests/test_basic.py',
'*/matplotlib/tests/test_bbox_tight.py',
- '*/matplotlib/tests/test_cbook.py',
- '*/matplotlib/tests/test_colorbar.py',
- '*/matplotlib/tests/test_colors.py',
- '*/matplotlib/tests/test_compare_images.py',
- '*/matplotlib/tests/test_contour.py',
'*/matplotlib/tests/test_dates.py',
'*/matplotlib/tests/test_delaunay.py',
'*/matplotlib/tests/test_dviread.py',
'*/matplotlib/tests/test_image.py',
'*/matplotlib/tests/test_legend.py',
'*/matplotlib/tests/test_lines.py',
'*/matplotlib/tests/test_mathtext.py',
- '*/matplotlib/tests/test_patches.py',
- '*/matplotlib/tests/test_pickle.py',
- '*/matplotlib/tests/test_png.py',
'*/matplotlib/tests/test_rcparams.py',
'*/matplotlib/tests/test_simplification.py',
'*/matplotlib/tests/test_spines.py',
View
42 lib/matplotlib/tests/test_colorbar.py
@@ -22,10 +22,10 @@ def _get_cmap_norms():
clevs = [-5., -2.5, -.5, .5, 1.5, 3.5]
# Define norms for the color maps.
norms = dict()
- norms['neither'] = BoundaryNorm(clevs, len(clevs)-1)
- norms['min'] = BoundaryNorm([-10]+clevs[1:], len(clevs)-1)
- norms['max'] = BoundaryNorm(clevs[:-1]+[10], len(clevs)-1)
- norms['both'] = BoundaryNorm([-10]+clevs[1:-1]+[10], len(clevs)-1)
+ norms['neither'] = BoundaryNorm(clevs, len(clevs) - 1)
+ norms['min'] = BoundaryNorm([-10] + clevs[1:], len(clevs) - 1)
+ norms['max'] = BoundaryNorm(clevs[:-1] + [10], len(clevs) - 1)
+ norms['both'] = BoundaryNorm([-10] + clevs[1:-1] + [10], len(clevs) - 1)
return cmap, norms
@@ -46,7 +46,7 @@ def _colorbar_extension_shape(spacing):
norm = norms[extension_type]
boundaries = values = norm.boundaries
# Create a subplot.
- cax = fig.add_subplot(4, 1, i+1)
+ cax = fig.add_subplot(4, 1, i + 1)
# Turn off text and ticks.
for item in cax.get_xticklabels() + cax.get_yticklabels() +\
cax.get_xticklines() + cax.get_yticklines():
@@ -78,7 +78,7 @@ def _colorbar_extension_length(spacing):
boundaries = values = norm.boundaries
for j, extendfrac in enumerate((None, 'auto', 0.1)):
# Create a subplot.
- cax = fig.add_subplot(12, 1, i*3+j+1)
+ cax = fig.add_subplot(12, 1, i*3 + j + 1)
# Turn off text and ticks.
for item in cax.get_xticklabels() + cax.get_yticklabels() +\
cax.get_xticklines() + cax.get_yticklines():
@@ -128,19 +128,19 @@ def test_colorbar_positioning():
data = np.arange(1200).reshape(30, 40)
levels = [0, 200, 400, 600, 800, 1000, 1200]
+ # -------------------
plt.figure()
plt.contourf(data, levels=levels)
plt.colorbar(orientation='horizontal', use_gridspec=False)
-
locations = ['left', 'right', 'top', 'bottom']
plt.figure()
for i, location in enumerate(locations):
- plt.subplot(2, 2, i+1)
+ plt.subplot(2, 2, i + 1)
plt.contourf(data, levels=levels)
plt.colorbar(location=location, use_gridspec=False)
-
+ # -------------------
plt.figure()
# make some other data (random integers)
data_2nd = np.array([[2, 3, 2, 3], [1.5, 2, 2, 3], [2, 3, 3, 4]])
@@ -149,13 +149,16 @@ def test_colorbar_positioning():
color_mappable = plt.contourf(data, levels=levels, extend='both')
# test extend frac here
- hatch_mappable = plt.contourf(data_2nd, levels=[1, 2, 3], colors='none', hatches=['/', 'o', '+'], extend='max')
+ hatch_mappable = plt.contourf(data_2nd, levels=[1, 2, 3], colors='none',
+ hatches=['/', 'o', '+'], extend='max')
plt.contour(hatch_mappable, colors='black')
- plt.colorbar(color_mappable, location='left', label='variable 1', use_gridspec=False)
- plt.colorbar(hatch_mappable, location='right', label='variable 2', use_gridspec=False)
-
+ plt.colorbar(color_mappable, location='left', label='variable 1',
+ use_gridspec=False)
+ plt.colorbar(hatch_mappable, location='right', label='variable 2',
+ use_gridspec=False)
+ # -------------------
plt.figure()
ax1 = plt.subplot(211, anchor='NE', aspect='equal')
plt.contourf(data, levels=levels)
@@ -164,9 +167,12 @@ def test_colorbar_positioning():
ax3 = plt.subplot(224)
plt.contourf(data, levels=levels)
- plt.colorbar(ax=[ax2, ax3, ax1], location='right', pad=0.0, shrink=0.5, panchor=False, use_gridspec=False)
- plt.colorbar(ax=[ax2, ax3, ax1], location='left', shrink=0.5, panchor=False, use_gridspec=False)
- plt.colorbar(ax=[ax1], location='bottom', panchor=False, anchor=(0.8, 0.5), shrink=0.6, use_gridspec=False)
+ plt.colorbar(ax=[ax2, ax3, ax1], location='right', pad=0.0, shrink=0.5,
+ panchor=False, use_gridspec=False)
+ plt.colorbar(ax=[ax2, ax3, ax1], location='left', shrink=0.5,
+ panchor=False, use_gridspec=False)
+ plt.colorbar(ax=[ax1], location='bottom', panchor=False,
+ anchor=(0.8, 0.5), shrink=0.6, use_gridspec=False)
@image_comparison(baseline_images=['cbar_with_subplots_adjust'],
@@ -188,6 +194,6 @@ def test_gridspec_make_colorbar():
plt.subplots_adjust(top=0.95, right=0.95, bottom=0.2, hspace=0.25)
-if __name__=='__main__':
+if __name__ == '__main__':
import nose
- nose.runmodule(argv=['-s','--with-doctest'], exit=False)
+ nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
View
21 lib/matplotlib/tests/test_colors.py
@@ -1,13 +1,12 @@
-"""
-Tests for the colors module.
-"""
-
from __future__ import print_function
+
import numpy as np
from numpy.testing.utils import assert_array_equal, assert_array_almost_equal
+
import matplotlib.colors as mcolors
import matplotlib.cm as cm
+
def test_colormap_endian():
"""
Github issue #1005: a bug in putmask caused erroneous
@@ -23,6 +22,7 @@ def test_colormap_endian():
#print(anative.dtype.isnative, aforeign.dtype.isnative)
assert_array_equal(cmap(anative), cmap(aforeign))
+
def test_BoundaryNorm():
"""
Github issue #1258: interpolation was failing with numpy
@@ -36,7 +36,8 @@ def test_BoundaryNorm():
ncolors = len(boundaries)
bn = mcolors.BoundaryNorm(boundaries, ncolors)
assert_array_equal(bn(vals), expected)
-
+
+
def test_LogNorm():
"""
LogNorm igornoed clip, now it has the same
@@ -46,6 +47,7 @@ def test_LogNorm():
ln = mcolors.LogNorm(clip=True, vmax=5)
assert_array_equal(ln([1, 6]), [0, 1.0])
+
def test_Normalize():
norm = mcolors.Normalize()
vals = np.arange(-10, 10, 1, dtype=np.float)
@@ -61,7 +63,7 @@ def test_SymLogNorm():
norm = mcolors.SymLogNorm(3, vmax=5, linscale=1.2)
vals = np.array([-30, -1, 2, 6], dtype=np.float)
normed_vals = norm(vals)
- expected = [ 0., 0.53980074, 0.826991, 1.02758204]
+ expected = [0., 0.53980074, 0.826991, 1.02758204]
assert_array_almost_equal(normed_vals, expected)
_inverse_tester(norm, vals)
_scalar_tester(norm, vals)
@@ -74,6 +76,7 @@ def _inverse_tester(norm_instance, vals):
"""
assert_array_almost_equal(norm_instance.inverse(norm_instance(vals)), vals)
+
def _scalar_tester(norm_instance, vals):
"""
Checks if scalars and arrays are handled the same way.
@@ -82,10 +85,16 @@ def _scalar_tester(norm_instance, vals):
scalar_result = [norm_instance(float(v)) for v in vals]
assert_array_almost_equal(scalar_result, norm_instance(vals))
+
def _mask_tester(norm_instance, vals):
"""
Checks mask handling
"""
masked_array = np.ma.array(vals)
masked_array[0] = np.ma.masked
assert_array_equal(masked_array.mask, norm_instance(masked_array).mask)
+
+
+if __name__ == '__main__':
+ import nose
+ nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
View
38 lib/matplotlib/tests/test_compare_images.py
@@ -1,12 +1,16 @@
from __future__ import print_function
-from matplotlib.testing.compare import compare_images
-from matplotlib.testing.decorators import _image_directories
-from nose.tools import assert_equal, assert_not_equal, assert_almost_equal
import os
import shutil
+from nose.tools import assert_equal, assert_not_equal, assert_almost_equal
+
+from matplotlib.testing.compare import compare_images
+from matplotlib.testing.decorators import _image_directories
+
+
baseline_dir, result_dir = _image_directories(lambda: 'dummy func')
+
# Tests of the image comparison algorithm.
def image_comparison_expect_rms(im1, im2, tol, expect_rms):
"""Compare two images, expecting a particular RMS error.
@@ -34,8 +38,10 @@ def image_comparison_expect_rms(im1, im2, tol, expect_rms):
assert_not_equal(None, results)
assert_almost_equal(expect_rms, results['rms'], places=4)
+
def test_image_compare_basic():
- """Test comparison of an image and the same image with minor differences."""
+ #: Test comparison of an image and the same image with minor differences.
+
# This expects the images to compare equal under normal tolerance, and have
# a small RMS.
im1 = 'basn3p02.png'
@@ -45,23 +51,27 @@ def test_image_compare_basic():
# Now test with no tolerance.
image_comparison_expect_rms(im1, im2, tol=0, expect_rms=6.50646)
+
def test_image_compare_1px_offset():
- """Test comparison with an image that is shifted by 1px in the X axis."""
+ #: Test comparison with an image that is shifted by 1px in the X axis.
im1 = 'basn3p02.png'
im2 = 'basn3p02-1px-offset.png'
image_comparison_expect_rms(im1, im2, tol=0, expect_rms=90.15611)
+
def test_image_compare_half_1px_offset():
- """Test comparison with an image with half the pixels shifted by 1px in the
- X axis."""
+ #: Test comparison with an image with half the pixels shifted by 1px in
+ #: the X axis.
im1 = 'basn3p02.png'
im2 = 'basn3p02-half-1px-offset.png'
image_comparison_expect_rms(im1, im2, tol=0, expect_rms=63.75)
+
def test_image_compare_scrambled():
- """Test comparison of an image and the same image scrambled."""
- # This expects the images to compare completely different, with a very large
- # RMS.
+ #: Test comparison of an image and the same image scrambled.
+
+ # This expects the images to compare completely different, with a very
+ # large RMS.
# Note: The image has been scrambled in a specific way, by having each
# color component of each pixel randomly placed somewhere in the image. It
# contains exactly the same number of pixels of each color value of R, G
@@ -72,8 +82,9 @@ def test_image_compare_scrambled():
# error.
image_comparison_expect_rms(im1, im2, tol=0, expect_rms=172.63582)
+
def test_image_compare_shade_difference():
- """Test comparison of an image and a slightly brighter image."""
+ #: Test comparison of an image and a slightly brighter image.
# The two images are solid color, with the second image being exactly 1
# color value brighter.
# This expects the images to compare equal under normal tolerance, and have
@@ -84,3 +95,8 @@ def test_image_compare_shade_difference():
# Now test the reverse comparison.
image_comparison_expect_rms(im2, im1, tol=0, expect_rms=1.0)
+
+
+if __name__ == '__main__':
+ import nose
+ nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
View
18 lib/matplotlib/tests/test_contour.py
@@ -146,7 +146,7 @@ def test_contour_manual_labels():
z = np.max(np.dstack([abs(x), abs(y)]), 2)
plt.figure(figsize=(6, 2))
- cs = plt.contour(x,y,z)
+ cs = plt.contour(x, y, z)
pts = np.array([(1.5, 3.0), (1.5, 4.4), (1.5, 6.0)])
plt.clabel(cs, manual=pts)
@@ -157,23 +157,25 @@ def test_given_colors_levels_and_extends():
_, axes = plt.subplots(2, 4)
data = np.arange(12).reshape(3, 4)
-
+
colors = ['red', 'yellow', 'pink', 'blue', 'black']
levels = [2, 4, 8, 10]
-
+
for i, ax in enumerate(axes.flatten()):
plt.sca(ax)
-
+
filled = i % 2 == 0.
extend = ['neither', 'min', 'max', 'both'][i // 2]
-
+
if filled:
last_color = -1 if extend in ['min', 'max'] else None
- plt.contourf(data, colors=colors[:last_color], levels=levels, extend=extend)
+ plt.contourf(data, colors=colors[:last_color], levels=levels,
+ extend=extend)
else:
last_level = -1 if extend == 'both' else None
- plt.contour(data, colors=colors, levels=levels[:last_level], extend=extend)
-
+ plt.contour(data, colors=colors, levels=levels[:last_level],
+ extend=extend)
+
plt.colorbar()
View
55 lib/matplotlib/tests/test_patches.py
@@ -1,10 +1,7 @@
-"""
-Tests specific to the patches module.
-"""
-
import numpy as np
from numpy.testing import assert_array_equal
from numpy.testing import assert_almost_equal
+
from matplotlib.patches import Polygon
from matplotlib.patches import Rectangle
from matplotlib.testing.decorators import image_comparison
@@ -16,15 +13,14 @@
def test_Polygon_close():
- """
- Github issue #1018 identified a bug in the Polygon handling
- of the closed attribute; the path was not getting closed
- when set_xy was used to set the vertices.
- """
+ #: Github issue #1018 identified a bug in the Polygon handling
+ #: of the closed attribute; the path was not getting closed
+ #: when set_xy was used to set the vertices.
+
# open set of vertices:
- xy = [[0,0], [0,1], [1,1]]
+ xy = [[0, 0], [0, 1], [1, 1]]
# closed set:
- xyclosed = xy + [[0,0]]
+ xyclosed = xy + [[0, 0]]
# start with open path and close it:
p = Polygon(xy, closed=True)
@@ -136,13 +132,11 @@ def test_patch_alpha_coloring():
ax.set_ylim([-1, 2])
-
@image_comparison(baseline_images=['patch_alpha_override'], remove_text=True)
def test_patch_alpha_override():
- """
- Test checks that specifying an alpha attribute for a patch or collection
- will override any alpha component of the facecolor or edgecolor.
- """
+ #: Test checks that specifying an alpha attribute for a patch or
+ #: collection will override any alpha component of the facecolor
+ #: or edgecolor.
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
# concatenate the star with an internal cutout of the circle
@@ -170,13 +164,11 @@ def test_patch_alpha_override():
ax.set_ylim([-1, 2])
-
-@image_comparison(baseline_images=['patch_custom_linestyle'], remove_text=True)
+@image_comparison(baseline_images=['patch_custom_linestyle'],
+ remove_text=True)
def test_patch_custom_linestyle():
- """
- A test to check that patches and collections accept custom dash patterns
- as linestyle and that they display correctly.
- """
+ #: A test to check that patches and collections accept custom dash
+ #: patterns as linestyle and that they display correctly.
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
# concatenate the star with an internal cutout of the circle
@@ -187,24 +179,21 @@ def test_patch_custom_linestyle():
ax = plt.axes()
patch = mpatches.PathPatch(cut_star1,
- linewidth=5, linestyle=(0.0, (5.0, 7.0, 10.0, 7.0)),
- facecolor=(1, 0, 0),
- edgecolor=(0, 0, 1))
+ linewidth=5, linestyle=(0.0, (5.0, 7.0, 10.0, 7.0)),
+ facecolor=(1, 0, 0),
+ edgecolor=(0, 0, 1))
ax.add_patch(patch)
col = mcollections.PathCollection([cut_star2],
- linewidth=5, linestyles=[(0.0, (5.0, 7.0, 10.0, 7.0))],
- facecolor=(1, 0, 0),
- edgecolor=(0, 0, 1))
+ linewidth=5, linestyles=[(0.0, (5.0, 7.0, 10.0, 7.0))],
+ facecolor=(1, 0, 0),
+ edgecolor=(0, 0, 1))
ax.add_collection(col)
ax.set_xlim([-1, 2])
ax.set_ylim([-1, 2])
-
-
-
-if __name__=='__main__':
+if __name__ == '__main__':
import nose
- nose.runmodule(argv=['-s','--with-doctest'], exit=False)
+ nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
View
12 lib/matplotlib/tests/test_path.py
@@ -1,3 +1,5 @@
+import numpy as np
+
from matplotlib.path import Path
from nose.tools import assert_raises
@@ -11,6 +13,16 @@ def modify_vertices():
assert_raises(AttributeError, modify_vertices)
+def test_point_in_path():
+ # Test #1787
+ verts2 = [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]
+
+ path = Path(verts2, closed=True)
+ points = [(0.5, 0.5), (1.5, 0.5)]
+
+ assert np.all(path.contains_points(points) == [True, False])
+
+
if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
View
35 lib/matplotlib/tests/test_pickle.py
@@ -1,18 +1,15 @@
from __future__ import print_function
+# cpickle is faster, pickle gives better exceptions
+import cPickle as pickle
+#import pickle
+from io import BytesIO
+from nose.tools import assert_equal, assert_not_equal
import numpy as np
from matplotlib.testing.decorators import cleanup, image_comparison
import matplotlib.pyplot as plt
-from nose.tools import assert_equal, assert_not_equal
-
-# cpickle is faster, pickle gives better exceptions
-import cPickle as pickle
-#import pickle
-
-from io import BytesIO
-
def depth_getter(obj,
current_depth=0,
@@ -44,9 +41,10 @@ def depth_getter(obj,
if isinstance(obj, (list, tuple)):
for i, item in enumerate(obj):
- depth_getter(item, current_depth=current_depth+1,
+ depth_getter(item, current_depth=current_depth + 1,
depth_stack=depth_stack,
- nest_info='list/tuple item #%s in (%s)' % (i, nest_info))
+ nest_info=('list/tuple item #%s in '
+ '(%s)' % (i, nest_info)))
else:
if isinstance(obj, dict):
state = obj
@@ -60,13 +58,10 @@ def depth_getter(obj,
state = {}
for key, value in state.iteritems():
- depth_getter(value, current_depth=current_depth+1,
+ depth_getter(value, current_depth=current_depth + 1,
depth_stack=depth_stack,
- nest_info='attribute "%s" in (%s)' % (key, nest_info))
-
- # for instancemethod picklability (and some other issues), uncommenting
- # the following may be helpful
-# print([(name, dobj.__class__) for name, dobj in state.iteritems()], ': ', nest_info, ';', type(obj))
+ nest_info=('attribute "%s" in '
+ '(%s)' % (key, nest_info)))
return depth_stack
@@ -90,7 +85,8 @@ def recursive_pickle(top_obj):
pickle.dump(obj, BytesIO(), pickle.HIGHEST_PROTOCOL)
except Exception, err:
print(obj)
- print('Failed to pickle %s. \n Type: %s. Traceback follows:' % (location, type(obj)))
+ print('Failed to pickle %s. \n Type: %s. Traceback '
+ 'follows:' % (location, type(obj)))
raise
@@ -114,7 +110,7 @@ def test_simple():
# ax = plt.subplot(121, projection='hammer')
# recursive_pickle(ax, 'figure')
# pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)
-
+
plt.figure()
plt.bar(left=range(10), height=range(10))
pickle.dump(plt.gca(), BytesIO(), pickle.HIGHEST_PROTOCOL)
@@ -138,7 +134,7 @@ def test_complete():
data = u = v = np.linspace(0, 10, 80).reshape(10, 8)
v = np.sin(v * -0.6)
- plt.subplot(3,3,1)
+ plt.subplot(331)
plt.plot(range(10))
plt.subplot(3, 3, 2)
@@ -148,7 +144,6 @@ def test_complete():
plt.subplot(3, 3, 3)
plt.pcolormesh(data)
-
plt.subplot(3, 3, 4)
plt.imshow(data)
View
17 lib/matplotlib/tests/test_png.py
@@ -1,10 +1,13 @@
-from matplotlib.testing.decorators import image_comparison, knownfailureif
-from matplotlib import pyplot as plt
-import matplotlib.cm as cm
import glob
import os
+
import numpy as np
+from matplotlib.testing.decorators import image_comparison
+from matplotlib import pyplot as plt
+import matplotlib.cm as cm
+
+
@image_comparison(baseline_images=['pngsuite'], extensions=['png'])
def test_pngsuite():
dirname = os.path.join(
@@ -18,11 +21,11 @@ def test_pngsuite():
for i, fname in enumerate(files):
data = plt.imread(fname)
- cmap = None # use default colormap
- if data.ndim==2:
+ cmap = None # use default colormap
+ if data.ndim == 2:
# keep grayscale images gray
cmap = cm.gray
- plt.imshow(data, extent=[i,i+1,0,1], cmap=cmap)
+ plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)
plt.gca().patch.set_facecolor("#ddffff")
plt.gca().set_xlim(0, len(files))
@@ -31,7 +34,7 @@ def test_pngsuite():
def test_imread_png_uint16():
from matplotlib import _png
img = _png.read_png_int(os.path.join(os.path.dirname(__file__),
- 'baseline_images/test_png/uint16.png'))
+ 'baseline_images/test_png/uint16.png'))
assert (img.dtype == np.uint16)
assert np.sum(img.flatten()) == 134184960
Something went wrong with that request. Please try again.