8000 Add test for unit conversion. · matplotlib/matplotlib@0925e38 · GitHub
[go: up one dir, main page]

Skip to content

Commit 0925e38

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 0925e38

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

lib/matplotlib/tests/test_units.py

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

0 commit comments

Comments
 (0)
0