test_cbook.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. import itertools
  2. import pickle
  3. import re
  4. from weakref import ref
  5. from unittest.mock import patch, Mock
  6. from datetime import datetime
  7. import numpy as np
  8. from numpy.testing import (assert_array_equal, assert_approx_equal,
  9. assert_array_almost_equal)
  10. import pytest
  11. import matplotlib.cbook as cbook
  12. import matplotlib.colors as mcolors
  13. from matplotlib.cbook import MatplotlibDeprecationWarning, delete_masked_points
  14. class Test_delete_masked_points:
  15. def test_bad_first_arg(self):
  16. with pytest.raises(ValueError):
  17. delete_masked_points('a string', np.arange(1.0, 7.0))
  18. def test_string_seq(self):
  19. a1 = ['a', 'b', 'c', 'd', 'e', 'f']
  20. a2 = [1, 2, 3, np.nan, np.nan, 6]
  21. result1, result2 = delete_masked_points(a1, a2)
  22. ind = [0, 1, 2, 5]
  23. assert_array_equal(result1, np.array(a1)[ind])
  24. assert_array_equal(result2, np.array(a2)[ind])
  25. def test_datetime(self):
  26. dates = [datetime(2008, 1, 1), datetime(2008, 1, 2),
  27. datetime(2008, 1, 3), datetime(2008, 1, 4),
  28. datetime(2008, 1, 5), datetime(2008, 1, 6)]
  29. a_masked = np.ma.array([1, 2, 3, np.nan, np.nan, 6],
  30. mask=[False, False, True, True, False, False])
  31. actual = delete_masked_points(dates, a_masked)
  32. ind = [0, 1, 5]
  33. assert_array_equal(actual[0], np.array(dates)[ind])
  34. assert_array_equal(actual[1], a_masked[ind].compressed())
  35. def test_rgba(self):
  36. a_masked = np.ma.array([1, 2, 3, np.nan, np.nan, 6],
  37. mask=[False, False, True, True, False, False])
  38. a_rgba = mcolors.to_rgba_array(['r', 'g', 'b', 'c', 'm', 'y'])
  39. actual = delete_masked_points(a_masked, a_rgba)
  40. ind = [0, 1, 5]
  41. assert_array_equal(actual[0], a_masked[ind].compressed())
  42. assert_array_equal(actual[1], a_rgba[ind])
  43. class Test_boxplot_stats:
  44. def setup(self):
  45. np.random.seed(937)
  46. self.nrows = 37
  47. self.ncols = 4
  48. self.data = np.random.lognormal(size=(self.nrows, self.ncols),
  49. mean=1.5, sigma=1.75)
  50. self.known_keys = sorted([
  51. 'mean', 'med', 'q1', 'q3', 'iqr',
  52. 'cilo', 'cihi', 'whislo', 'whishi',
  53. 'fliers', 'label'
  54. ])
  55. self.std_results = cbook.boxplot_stats(self.data)
  56. self.known_nonbootstrapped_res = {
  57. 'cihi': 6.8161283264444847,
  58. 'cilo': -0.1489815330368689,
  59. 'iqr': 13.492709959447094,
  60. 'mean': 13.00447442387868,
  61. 'med': 3.3335733967038079,
  62. 'fliers': np.array([
  63. 92.55467075, 87.03819018, 42.23204914, 39.29390996
  64. ]),
  65. 'q1': 1.3597529879465153,
  66. 'q3': 14.85246294739361,
  67. 'whishi': 27.899688243699629,
  68. 'whislo': 0.042143774965502923
  69. }
  70. self.known_bootstrapped_ci = {
  71. 'cihi': 8.939577523357828,
  72. 'cilo': 1.8692703958676578,
  73. }
  74. self.known_whis3_res = {
  75. 'whishi': 42.232049135969874,
  76. 'whislo': 0.042143774965502923,
  77. 'fliers': np.array([92.55467075, 87.03819018]),
  78. }
  79. self.known_res_percentiles = {
  80. 'whislo': 0.1933685896907924,
  81. 'whishi': 42.232049135969874
  82. }
  83. self.known_res_range = {
  84. 'whislo': 0.042143774965502923,
  85. 'whishi': 92.554670752188699
  86. }
  87. def test_form_main_list(self):
  88. assert isinstance(self.std_results, list)
  89. def test_form_each_dict(self):
  90. for res in self.std_results:
  91. assert isinstance(res, dict)
  92. def test_form_dict_keys(self):
  93. for res in self.std_results:
  94. assert set(res) <= set(self.known_keys)
  95. def test_results_baseline(self):
  96. res = self.std_results[0]
  97. for key, value in self.known_nonbootstrapped_res.items():
  98. assert_array_almost_equal(res[key], value)
  99. def test_results_bootstrapped(self):
  100. results = cbook.boxplot_stats(self.data, bootstrap=10000)
  101. res = results[0]
  102. for key, value in self.known_bootstrapped_ci.items():
  103. assert_approx_equal(res[key], value)
  104. def test_results_whiskers_float(self):
  105. results = cbook.boxplot_stats(self.data, whis=3)
  106. res = results[0]
  107. for key, value in self.known_whis3_res.items():
  108. assert_array_almost_equal(res[key], value)
  109. def test_results_whiskers_range(self):
  110. results = cbook.boxplot_stats(self.data, whis=[0, 100])
  111. res = results[0]
  112. for key, value in self.known_res_range.items():
  113. assert_array_almost_equal(res[key], value)
  114. def test_results_whiskers_percentiles(self):
  115. results = cbook.boxplot_stats(self.data, whis=[5, 95])
  116. res = results[0]
  117. for key, value in self.known_res_percentiles.items():
  118. assert_array_almost_equal(res[key], value)
  119. def test_results_withlabels(self):
  120. labels = ['Test1', 2, 'ardvark', 4]
  121. results = cbook.boxplot_stats(self.data, labels=labels)
  122. res = results[0]
  123. for lab, res in zip(labels, results):
  124. assert res['label'] == lab
  125. results = cbook.boxplot_stats(self.data)
  126. for res in results:
  127. assert 'label' not in res
  128. def test_label_error(self):
  129. labels = [1, 2]
  130. with pytest.raises(ValueError):
  131. cbook.boxplot_stats(self.data, labels=labels)
  132. def test_bad_dims(self):
  133. data = np.random.normal(size=(34, 34, 34))
  134. with pytest.raises(ValueError):
  135. cbook.boxplot_stats(data)
  136. def test_boxplot_stats_autorange_false(self):
  137. x = np.zeros(shape=140)
  138. x = np.hstack([-25, x, 25])
  139. bstats_false = cbook.boxplot_stats(x, autorange=False)
  140. bstats_true = cbook.boxplot_stats(x, autorange=True)
  141. assert bstats_false[0]['whislo'] == 0
  142. assert bstats_false[0]['whishi'] == 0
  143. assert_array_almost_equal(bstats_false[0]['fliers'], [-25, 25])
  144. assert bstats_true[0]['whislo'] == -25
  145. assert bstats_true[0]['whishi'] == 25
  146. assert_array_almost_equal(bstats_true[0]['fliers'], [])
  147. class Test_callback_registry:
  148. def setup(self):
  149. self.signal = 'test'
  150. self.callbacks = cbook.CallbackRegistry()
  151. def connect(self, s, func):
  152. return self.callbacks.connect(s, func)
  153. def is_empty(self):
  154. assert self.callbacks._func_cid_map == {}
  155. assert self.callbacks.callbacks == {}
  156. def is_not_empty(self):
  157. assert self.callbacks._func_cid_map != {}
  158. assert self.callbacks.callbacks != {}
  159. def test_callback_complete(self):
  160. # ensure we start with an empty registry
  161. self.is_empty()
  162. # create a class for testing
  163. mini_me = Test_callback_registry()
  164. # test that we can add a callback
  165. cid1 = self.connect(self.signal, mini_me.dummy)
  166. assert type(cid1) == int
  167. self.is_not_empty()
  168. # test that we don't add a second callback
  169. cid2 = self.connect(self.signal, mini_me.dummy)
  170. assert cid1 == cid2
  171. self.is_not_empty()
  172. assert len(self.callbacks._func_cid_map) == 1
  173. assert len(self.callbacks.callbacks) == 1
  174. del mini_me
  175. # check we now have no callbacks registered
  176. self.is_empty()
  177. def dummy(self):
  178. pass
  179. def test_pickling(self):
  180. assert hasattr(pickle.loads(pickle.dumps(cbook.CallbackRegistry())),
  181. "callbacks")
  182. def test_callbackregistry_default_exception_handler(monkeypatch):
  183. cb = cbook.CallbackRegistry()
  184. cb.connect("foo", lambda: None)
  185. monkeypatch.setattr(
  186. cbook, "_get_running_interactive_framework", lambda: None)
  187. with pytest.raises(TypeError):
  188. cb.process("foo", "argument mismatch")
  189. monkeypatch.setattr(
  190. cbook, "_get_running_interactive_framework", lambda: "not-none")
  191. cb.process("foo", "argument mismatch") # No error in that case.
  192. def raising_cb_reg(func):
  193. class TestException(Exception):
  194. pass
  195. def raising_function():
  196. raise RuntimeError
  197. def raising_function_VE():
  198. raise ValueError
  199. def transformer(excp):
  200. if isinstance(excp, RuntimeError):
  201. raise TestException
  202. raise excp
  203. # old default
  204. cb_old = cbook.CallbackRegistry(exception_handler=None)
  205. cb_old.connect('foo', raising_function)
  206. # filter
  207. cb_filt = cbook.CallbackRegistry(exception_handler=transformer)
  208. cb_filt.connect('foo', raising_function)
  209. # filter
  210. cb_filt_pass = cbook.CallbackRegistry(exception_handler=transformer)
  211. cb_filt_pass.connect('foo', raising_function_VE)
  212. return pytest.mark.parametrize('cb, excp',
  213. [[cb_old, RuntimeError],
  214. [cb_filt, TestException],
  215. [cb_filt_pass, ValueError]])(func)
  216. @raising_cb_reg
  217. def test_callbackregistry_custom_exception_handler(monkeypatch, cb, excp):
  218. monkeypatch.setattr(
  219. cbook, "_get_running_interactive_framework", lambda: None)
  220. with pytest.raises(excp):
  221. cb.process('foo')
  222. def test_sanitize_sequence():
  223. d = {'a': 1, 'b': 2, 'c': 3}
  224. k = ['a', 'b', 'c']
  225. v = [1, 2, 3]
  226. i = [('a', 1), ('b', 2), ('c', 3)]
  227. assert k == sorted(cbook.sanitize_sequence(d.keys()))
  228. assert v == sorted(cbook.sanitize_sequence(d.values()))
  229. assert i == sorted(cbook.sanitize_sequence(d.items()))
  230. assert i == cbook.sanitize_sequence(i)
  231. assert k == cbook.sanitize_sequence(k)
  232. fail_mapping = (
  233. ({'a': 1}, {'forbidden': ('a')}),
  234. ({'a': 1}, {'required': ('b')}),
  235. ({'a': 1, 'b': 2}, {'required': ('a'), 'allowed': ()}),
  236. ({'a': 1, 'b': 2}, {'alias_mapping': {'a': ['b']}}),
  237. ({'a': 1, 'b': 2}, {'alias_mapping': {'a': ['b']}, 'allowed': ('a',)}),
  238. ({'a': 1, 'b': 2}, {'alias_mapping': {'a': ['a', 'b']}}),
  239. ({'a': 1, 'b': 2, 'c': 3},
  240. {'alias_mapping': {'a': ['b']}, 'required': ('a', )}),
  241. )
  242. pass_mapping = (
  243. ({'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {}),
  244. ({'b': 2}, {'a': 2}, {'alias_mapping': {'a': ['a', 'b']}}),
  245. ({'b': 2}, {'a': 2},
  246. {'alias_mapping': {'a': ['b']}, 'forbidden': ('b', )}),
  247. ({'a': 1, 'c': 3}, {'a': 1, 'c': 3},
  248. {'required': ('a', ), 'allowed': ('c', )}),
  249. ({'a': 1, 'c': 3}, {'a': 1, 'c': 3},
  250. {'required': ('a', 'c'), 'allowed': ('c', )}),
  251. ({'a': 1, 'c': 3}, {'a': 1, 'c': 3},
  252. {'required': ('a', 'c'), 'allowed': ('a', 'c')}),
  253. ({'a': 1, 'c': 3}, {'a': 1, 'c': 3},
  254. {'required': ('a', 'c'), 'allowed': ()}),
  255. ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, {'required': ('a', 'c')}),
  256. ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, {'allowed': ('a', 'c')}),
  257. )
  258. @pytest.mark.parametrize('inp, kwargs_to_norm', fail_mapping)
  259. def test_normalize_kwargs_fail(inp, kwargs_to_norm):
  260. with pytest.raises(TypeError), \
  261. cbook._suppress_matplotlib_deprecation_warning():
  262. cbook.normalize_kwargs(inp, **kwargs_to_norm)
  263. @pytest.mark.parametrize('inp, expected, kwargs_to_norm',
  264. pass_mapping)
  265. def test_normalize_kwargs_pass(inp, expected, kwargs_to_norm):
  266. with cbook._suppress_matplotlib_deprecation_warning():
  267. # No other warning should be emitted.
  268. assert expected == cbook.normalize_kwargs(inp, **kwargs_to_norm)
  269. def test_warn_external_frame_embedded_python():
  270. with patch.object(cbook, "sys") as mock_sys:
  271. mock_sys._getframe = Mock(return_value=None)
  272. with pytest.warns(UserWarning, match=r"\Adummy\Z"):
  273. cbook._warn_external("dummy")
  274. def test_to_prestep():
  275. x = np.arange(4)
  276. y1 = np.arange(4)
  277. y2 = np.arange(4)[::-1]
  278. xs, y1s, y2s = cbook.pts_to_prestep(x, y1, y2)
  279. x_target = np.asarray([0, 0, 1, 1, 2, 2, 3], dtype=float)
  280. y1_target = np.asarray([0, 1, 1, 2, 2, 3, 3], dtype=float)
  281. y2_target = np.asarray([3, 2, 2, 1, 1, 0, 0], dtype=float)
  282. assert_array_equal(x_target, xs)
  283. assert_array_equal(y1_target, y1s)
  284. assert_array_equal(y2_target, y2s)
  285. xs, y1s = cbook.pts_to_prestep(x, y1)
  286. assert_array_equal(x_target, xs)
  287. assert_array_equal(y1_target, y1s)
  288. def test_to_prestep_empty():
  289. steps = cbook.pts_to_prestep([], [])
  290. assert steps.shape == (2, 0)
  291. def test_to_poststep():
  292. x = np.arange(4)
  293. y1 = np.arange(4)
  294. y2 = np.arange(4)[::-1]
  295. xs, y1s, y2s = cbook.pts_to_poststep(x, y1, y2)
  296. x_target = np.asarray([0, 1, 1, 2, 2, 3, 3], dtype=float)
  297. y1_target = np.asarray([0, 0, 1, 1, 2, 2, 3], dtype=float)
  298. y2_target = np.asarray([3, 3, 2, 2, 1, 1, 0], dtype=float)
  299. assert_array_equal(x_target, xs)
  300. assert_array_equal(y1_target, y1s)
  301. assert_array_equal(y2_target, y2s)
  302. xs, y1s = cbook.pts_to_poststep(x, y1)
  303. assert_array_equal(x_target, xs)
  304. assert_array_equal(y1_target, y1s)
  305. def test_to_poststep_empty():
  306. steps = cbook.pts_to_poststep([], [])
  307. assert steps.shape == (2, 0)
  308. def test_to_midstep():
  309. x = np.arange(4)
  310. y1 = np.arange(4)
  311. y2 = np.arange(4)[::-1]
  312. xs, y1s, y2s = cbook.pts_to_midstep(x, y1, y2)
  313. x_target = np.asarray([0, .5, .5, 1.5, 1.5, 2.5, 2.5, 3], dtype=float)
  314. y1_target = np.asarray([0, 0, 1, 1, 2, 2, 3, 3], dtype=float)
  315. y2_target = np.asarray([3, 3, 2, 2, 1, 1, 0, 0], dtype=float)
  316. assert_array_equal(x_target, xs)
  317. assert_array_equal(y1_target, y1s)
  318. assert_array_equal(y2_target, y2s)
  319. xs, y1s = cbook.pts_to_midstep(x, y1)
  320. assert_array_equal(x_target, xs)
  321. assert_array_equal(y1_target, y1s)
  322. def test_to_midstep_empty():
  323. steps = cbook.pts_to_midstep([], [])
  324. assert steps.shape == (2, 0)
  325. @pytest.mark.parametrize(
  326. "args",
  327. [(np.arange(12).reshape(3, 4), 'a'),
  328. (np.arange(12), 'a'),
  329. (np.arange(12), np.arange(3))])
  330. def test_step_fails(args):
  331. with pytest.raises(ValueError):
  332. cbook.pts_to_prestep(*args)
  333. def test_grouper():
  334. class dummy:
  335. pass
  336. a, b, c, d, e = objs = [dummy() for j in range(5)]
  337. g = cbook.Grouper()
  338. g.join(*objs)
  339. assert set(list(g)[0]) == set(objs)
  340. assert set(g.get_siblings(a)) == set(objs)
  341. for other in objs[1:]:
  342. assert g.joined(a, other)
  343. g.remove(a)
  344. for other in objs[1:]:
  345. assert not g.joined(a, other)
  346. for A, B in itertools.product(objs[1:], objs[1:]):
  347. assert g.joined(A, B)
  348. def test_grouper_private():
  349. class dummy:
  350. pass
  351. objs = [dummy() for j in range(5)]
  352. g = cbook.Grouper()
  353. g.join(*objs)
  354. # reach in and touch the internals !
  355. mapping = g._mapping
  356. for o in objs:
  357. assert ref(o) in mapping
  358. base_set = mapping[ref(objs[0])]
  359. for o in objs[1:]:
  360. assert mapping[ref(o)] is base_set
  361. def test_flatiter():
  362. x = np.arange(5)
  363. it = x.flat
  364. assert 0 == next(it)
  365. assert 1 == next(it)
  366. ret = cbook.safe_first_element(it)
  367. assert ret == 0
  368. assert 0 == next(it)
  369. assert 1 == next(it)
  370. def test_reshape2d():
  371. class dummy:
  372. pass
  373. xnew = cbook._reshape_2D([], 'x')
  374. assert np.shape(xnew) == (1, 0)
  375. x = [dummy() for j in range(5)]
  376. xnew = cbook._reshape_2D(x, 'x')
  377. assert np.shape(xnew) == (1, 5)
  378. x = np.arange(5)
  379. xnew = cbook._reshape_2D(x, 'x')
  380. assert np.shape(xnew) == (1, 5)
  381. x = [[dummy() for j in range(5)] for i in range(3)]
  382. xnew = cbook._reshape_2D(x, 'x')
  383. assert np.shape(xnew) == (3, 5)
  384. # this is strange behaviour, but...
  385. x = np.random.rand(3, 5)
  386. xnew = cbook._reshape_2D(x, 'x')
  387. assert np.shape(xnew) == (5, 3)
  388. # Test a list of lists which are all of length 1
  389. x = [[1], [2], [3]]
  390. xnew = cbook._reshape_2D(x, 'x')
  391. assert isinstance(xnew, list)
  392. assert isinstance(xnew[0], np.ndarray) and xnew[0].shape == (1,)
  393. assert isinstance(xnew[1], np.ndarray) and xnew[1].shape == (1,)
  394. assert isinstance(xnew[2], np.ndarray) and xnew[2].shape == (1,)
  395. # Now test with a list of lists with different lengths, which means the
  396. # array will internally be converted to a 1D object array of lists
  397. x = [[1, 2, 3], [3, 4], [2]]
  398. xnew = cbook._reshape_2D(x, 'x')
  399. assert isinstance(xnew, list)
  400. assert isinstance(xnew[0], np.ndarray) and xnew[0].shape == (3,)
  401. assert isinstance(xnew[1], np.ndarray) and xnew[1].shape == (2,)
  402. assert isinstance(xnew[2], np.ndarray) and xnew[2].shape == (1,)
  403. # We now need to make sure that this works correctly for Numpy subclasses
  404. # where iterating over items can return subclasses too, which may be
  405. # iterable even if they are scalars. To emulate this, we make a Numpy
  406. # array subclass that returns Numpy 'scalars' when iterating or accessing
  407. # values, and these are technically iterable if checking for example
  408. # isinstance(x, collections.abc.Iterable).
  409. class ArraySubclass(np.ndarray):
  410. def __iter__(self):
  411. for value in super().__iter__():
  412. yield np.array(value)
  413. def __getitem__(self, item):
  414. return np.array(super().__getitem__(item))
  415. v = np.arange(10, dtype=float)
  416. x = ArraySubclass((10,), dtype=float, buffer=v.data)
  417. xnew = cbook._reshape_2D(x, 'x')
  418. # We check here that the array wasn't split up into many individual
  419. # ArraySubclass, which is what used to happen due to a bug in _reshape_2D
  420. assert len(xnew) == 1
  421. assert isinstance(xnew[0], ArraySubclass)
  422. # check list of strings:
  423. x = ['a', 'b', 'c', 'c', 'dd', 'e', 'f', 'ff', 'f']
  424. xnew = cbook._reshape_2D(x, 'x')
  425. assert len(xnew[0]) == len(x)
  426. assert isinstance(xnew[0], np.ndarray)
  427. def test_reshape2d_pandas(pd):
  428. # seperate to allow the rest of the tests to run if no pandas...
  429. X = np.arange(30).reshape(10, 3)
  430. x = pd.DataFrame(X, columns=["a", "b", "c"])
  431. Xnew = cbook._reshape_2D(x, 'x')
  432. # Need to check each row because _reshape_2D returns a list of arrays:
  433. for x, xnew in zip(X.T, Xnew):
  434. np.testing.assert_array_equal(x, xnew)
  435. X = np.arange(30).reshape(10, 3)
  436. x = pd.DataFrame(X, columns=["a", "b", "c"])
  437. Xnew = cbook._reshape_2D(x, 'x')
  438. # Need to check each row because _reshape_2D returns a list of arrays:
  439. for x, xnew in zip(X.T, Xnew):
  440. np.testing.assert_array_equal(x, xnew)
  441. def test_contiguous_regions():
  442. a, b, c = 3, 4, 5
  443. # Starts and ends with True
  444. mask = [True]*a + [False]*b + [True]*c
  445. expected = [(0, a), (a+b, a+b+c)]
  446. assert cbook.contiguous_regions(mask) == expected
  447. d, e = 6, 7
  448. # Starts with True ends with False
  449. mask = mask + [False]*e
  450. assert cbook.contiguous_regions(mask) == expected
  451. # Starts with False ends with True
  452. mask = [False]*d + mask[:-e]
  453. expected = [(d, d+a), (d+a+b, d+a+b+c)]
  454. assert cbook.contiguous_regions(mask) == expected
  455. # Starts and ends with False
  456. mask = mask + [False]*e
  457. assert cbook.contiguous_regions(mask) == expected
  458. # No True in mask
  459. assert cbook.contiguous_regions([False]*5) == []
  460. # Empty mask
  461. assert cbook.contiguous_regions([]) == []
  462. def test_safe_first_element_pandas_series(pd):
  463. # deliberately create a pandas series with index not starting from 0
  464. s = pd.Series(range(5), index=range(10, 15))
  465. actual = cbook.safe_first_element(s)
  466. assert actual == 0
  467. def test_delete_parameter():
  468. @cbook._delete_parameter("3.0", "foo")
  469. def func1(foo=None):
  470. pass
  471. @cbook._delete_parameter("3.0", "foo")
  472. def func2(**kwargs):
  473. pass
  474. for func in [func1, func2]:
  475. func() # No warning.
  476. with pytest.warns(MatplotlibDeprecationWarning):
  477. func(foo="bar")
  478. def pyplot_wrapper(foo=cbook.deprecation._deprecated_parameter):
  479. func1(foo)
  480. pyplot_wrapper() # No warning.
  481. with pytest.warns(MatplotlibDeprecationWarning):
  482. func(foo="bar")
  483. def test_make_keyword_only():
  484. @cbook._make_keyword_only("3.0", "arg")
  485. def func(pre, arg, post=None):
  486. pass
  487. func(1, arg=2) # Check that no warning is emitted.
  488. with pytest.warns(MatplotlibDeprecationWarning):
  489. func(1, 2)
  490. with pytest.warns(MatplotlibDeprecationWarning):
  491. func(1, 2, 3)
  492. def test_warn_external(recwarn):
  493. cbook._warn_external("oops")
  494. assert len(recwarn) == 1
  495. assert recwarn[0].filename == __file__
  496. def test_array_patch_perimeters():
  497. # This compares the old implementation as a reference for the
  498. # vectorized one.
  499. def check(x, rstride, cstride):
  500. rows, cols = x.shape
  501. row_inds = [*range(0, rows-1, rstride), rows-1]
  502. col_inds = [*range(0, cols-1, cstride), cols-1]
  503. polys = []
  504. for rs, rs_next in zip(row_inds[:-1], row_inds[1:]):
  505. for cs, cs_next in zip(col_inds[:-1], col_inds[1:]):
  506. # +1 ensures we share edges between polygons
  507. ps = cbook._array_perimeter(x[rs:rs_next+1, cs:cs_next+1]).T
  508. polys.append(ps)
  509. polys = np.asarray(polys)
  510. assert np.array_equal(polys,
  511. cbook._array_patch_perimeters(
  512. x, rstride=rstride, cstride=cstride))
  513. def divisors(n):
  514. return [i for i in range(1, n + 1) if n % i == 0]
  515. for rows, cols in [(5, 5), (7, 14), (13, 9)]:
  516. x = np.arange(rows * cols).reshape(rows, cols)
  517. for rstride, cstride in itertools.product(divisors(rows - 1),
  518. divisors(cols - 1)):
  519. check(x, rstride=rstride, cstride=cstride)
  520. @pytest.mark.parametrize('target,test_shape',
  521. [((None, ), (1, 3)),
  522. ((None, 3), (1,)),
  523. ((None, 3), (1, 2)),
  524. ((1, 5), (1, 9)),
  525. ((None, 2, None), (1, 3, 1))
  526. ])
  527. def test_check_shape(target, test_shape):
  528. error_pattern = (f"^'aardvark' must be {len(target)}D.*" +
  529. re.escape(f'has shape {test_shape}'))
  530. data = np.zeros(test_shape)
  531. with pytest.raises(ValueError,
  532. match=error_pattern):
  533. cbook._check_shape(target, aardvark=data)
  534. def test_setattr_cm():
  535. class A:
  536. cls_level = object()
  537. override = object()
  538. def __init__(self):
  539. self.aardvark = 'aardvark'
  540. self.override = 'override'
  541. self._p = 'p'
  542. def meth(self):
  543. ...
  544. @classmethod
  545. def classy(klass):
  546. ...
  547. @staticmethod
  548. def static():
  549. ...
  550. @property
  551. def prop(self):
  552. return self._p
  553. @prop.setter
  554. def prop(self, val):
  555. self._p = val
  556. class B(A):
  557. ...
  558. other = A()
  559. def verify_pre_post_state(obj):
  560. # When you access a Python method the function is bound
  561. # to the object at access time so you get a new instance
  562. # of MethodType every time.
  563. #
  564. # https://docs.python.org/3/howto/descriptor.html#functions-and-methods
  565. assert obj.meth is not obj.meth
  566. # normal attribute should give you back the same instance every time
  567. assert obj.aardvark is obj.aardvark
  568. assert a.aardvark == 'aardvark'
  569. # and our property happens to give the same instance every time
  570. assert obj.prop is obj.prop
  571. assert obj.cls_level is A.cls_level
  572. assert obj.override == 'override'
  573. assert not hasattr(obj, 'extra')
  574. assert obj.prop == 'p'
  575. assert obj.monkey == other.meth
  576. assert obj.cls_level is A.cls_level
  577. assert 'cls_level' not in obj.__dict__
  578. assert 'classy' not in obj.__dict__
  579. assert 'static' not in obj.__dict__
  580. a = B()
  581. a.monkey = other.meth
  582. verify_pre_post_state(a)
  583. with cbook._setattr_cm(
  584. a, prop='squirrel',
  585. aardvark='moose', meth=lambda: None,
  586. override='boo', extra='extra',
  587. monkey=lambda: None, cls_level='bob',
  588. classy='classy', static='static'):
  589. # because we have set a lambda, it is normal attribute access
  590. # and the same every time
  591. assert a.meth is a.meth
  592. assert a.aardvark is a.aardvark
  593. assert a.aardvark == 'moose'
  594. assert a.override == 'boo'
  595. assert a.extra == 'extra'
  596. assert a.prop == 'squirrel'
  597. assert a.monkey != other.meth
  598. assert a.cls_level == 'bob'
  599. assert a.classy == 'classy'
  600. assert a.static == 'static'
  601. verify_pre_post_state(a)