Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit cdc274f

Browse files
committed
Add test for unit conversion.
This is catching the problems with pint-like libraries who wrap numpy arrays.
1 parent b9bc7d1 commit cdc274f

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

lib/matplotlib/tests/test_units.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import matplotlib.pyplot as plt
2+
import matplotlib.units as munits
3+
import numpy as np
4+
5+
try:
6+
# mock in python 3.3+
7+
from unittest.mock import MagicMock
8+
except ImportError:
9+
from mock import MagicMock
10+
11+
# Tests that the conversion machinery works properly for classes that
12+
# work as a facade over numpy arrays (like pint)
13+
def test_numpy_facade():
14+
# Basic class that wraps numpy array and has units
15+
class Quantity(object):
16+
def __init__(self, data, units):
17+
self.magnitude = data
18+
self.units = units
19+
20+
def to(self, new_units):
21+
return Quantity(self.magnitude, new_units)
22+
23+
def __getattr__(self, attr):
24+
return getattr(self.magnitude, attr)
25+
26+
def __getitem__(self, item):
27+
return self.magnitude[item]
28+
29+
# Create an instance of the conversion interface and
30+
# mock so we can check methods called
31+
qc = munits.ConversionInterface()
32+
33+
def convert(value, unit, axis):
34+
if hasattr(value, 'units'):
35+
return value.to(unit)
36+
else:
37+
return Quantity(value, axis.get_units()).to(unit).magnitude
38+
39+
qc.convert = MagicMock(side_effect=convert)
40+
qc.axisinfo = MagicMock(return_value=None)
41+
qc.default_units = MagicMock(side_effect=lambda x, a: x.units)
42+
43+
# Register the class
44+
munits.registry[Quantity] = qc
45+
46+
# Simple test
47+
t = Quantity(np.linspace(0, 10), 'sec')
48+
d = Quantity(30 * np.linspace(0, 10), 'm/s')
49+
50+
fig, ax = plt.subplots(1, 1)
51+
l, = plt.plot(t, d)
52+
ax.yaxis.set_units('inch')
53+
54+
assert qc.convert.called
55+
assert qc.axisinfo.called
56+
assert qc.default_units.called

0 commit comments

Comments
 (0)