test_deprecations.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  1. """
  2. Tests related to deprecation warnings. Also a convenient place
  3. to document how deprecations should eventually be turned into errors.
  4. """
  5. import datetime
  6. import operator
  7. import warnings
  8. import pytest
  9. import tempfile
  10. import re
  11. import sys
  12. import numpy as np
  13. from numpy.testing import (
  14. assert_raises, assert_warns, assert_, assert_array_equal, SkipTest,
  15. KnownFailureException, break_cycles,
  16. )
  17. from numpy.core._multiarray_tests import fromstring_null_term_c_api
  18. try:
  19. import pytz
  20. _has_pytz = True
  21. except ImportError:
  22. _has_pytz = False
  23. class _DeprecationTestCase:
  24. # Just as warning: warnings uses re.match, so the start of this message
  25. # must match.
  26. message = ''
  27. warning_cls = DeprecationWarning
  28. def setup_method(self):
  29. self.warn_ctx = warnings.catch_warnings(record=True)
  30. self.log = self.warn_ctx.__enter__()
  31. # Do *not* ignore other DeprecationWarnings. Ignoring warnings
  32. # can give very confusing results because of
  33. # https://bugs.python.org/issue4180 and it is probably simplest to
  34. # try to keep the tests cleanly giving only the right warning type.
  35. # (While checking them set to "error" those are ignored anyway)
  36. # We still have them show up, because otherwise they would be raised
  37. warnings.filterwarnings("always", category=self.warning_cls)
  38. warnings.filterwarnings("always", message=self.message,
  39. category=self.warning_cls)
  40. def teardown_method(self):
  41. self.warn_ctx.__exit__()
  42. def assert_deprecated(self, function, num=1, ignore_others=False,
  43. function_fails=False,
  44. exceptions=np._NoValue,
  45. args=(), kwargs={}):
  46. """Test if DeprecationWarnings are given and raised.
  47. This first checks if the function when called gives `num`
  48. DeprecationWarnings, after that it tries to raise these
  49. DeprecationWarnings and compares them with `exceptions`.
  50. The exceptions can be different for cases where this code path
  51. is simply not anticipated and the exception is replaced.
  52. Parameters
  53. ----------
  54. function : callable
  55. The function to test
  56. num : int
  57. Number of DeprecationWarnings to expect. This should normally be 1.
  58. ignore_others : bool
  59. Whether warnings of the wrong type should be ignored (note that
  60. the message is not checked)
  61. function_fails : bool
  62. If the function would normally fail, setting this will check for
  63. warnings inside a try/except block.
  64. exceptions : Exception or tuple of Exceptions
  65. Exception to expect when turning the warnings into an error.
  66. The default checks for DeprecationWarnings. If exceptions is
  67. empty the function is expected to run successfully.
  68. args : tuple
  69. Arguments for `function`
  70. kwargs : dict
  71. Keyword arguments for `function`
  72. """
  73. __tracebackhide__ = True # Hide traceback for py.test
  74. # reset the log
  75. self.log[:] = []
  76. if exceptions is np._NoValue:
  77. exceptions = (self.warning_cls,)
  78. try:
  79. function(*args, **kwargs)
  80. except (Exception if function_fails else tuple()):
  81. pass
  82. # just in case, clear the registry
  83. num_found = 0
  84. for warning in self.log:
  85. if warning.category is self.warning_cls:
  86. num_found += 1
  87. elif not ignore_others:
  88. raise AssertionError(
  89. "expected %s but got: %s" %
  90. (self.warning_cls.__name__, warning.category))
  91. if num is not None and num_found != num:
  92. msg = "%i warnings found but %i expected." % (len(self.log), num)
  93. lst = [str(w) for w in self.log]
  94. raise AssertionError("\n".join([msg] + lst))
  95. with warnings.catch_warnings():
  96. warnings.filterwarnings("error", message=self.message,
  97. category=self.warning_cls)
  98. try:
  99. function(*args, **kwargs)
  100. if exceptions != tuple():
  101. raise AssertionError(
  102. "No error raised during function call")
  103. except exceptions:
  104. if exceptions == tuple():
  105. raise AssertionError(
  106. "Error raised during function call")
  107. def assert_not_deprecated(self, function, args=(), kwargs={}):
  108. """Test that warnings are not raised.
  109. This is just a shorthand for:
  110. self.assert_deprecated(function, num=0, ignore_others=True,
  111. exceptions=tuple(), args=args, kwargs=kwargs)
  112. """
  113. self.assert_deprecated(function, num=0, ignore_others=True,
  114. exceptions=tuple(), args=args, kwargs=kwargs)
  115. class _VisibleDeprecationTestCase(_DeprecationTestCase):
  116. warning_cls = np.VisibleDeprecationWarning
  117. class TestComparisonDeprecations(_DeprecationTestCase):
  118. """This tests the deprecation, for non-element-wise comparison logic.
  119. This used to mean that when an error occurred during element-wise comparison
  120. (i.e. broadcasting) NotImplemented was returned, but also in the comparison
  121. itself, False was given instead of the error.
  122. Also test FutureWarning for the None comparison.
  123. """
  124. message = "elementwise.* comparison failed; .*"
  125. def test_normal_types(self):
  126. for op in (operator.eq, operator.ne):
  127. # Broadcasting errors:
  128. self.assert_deprecated(op, args=(np.zeros(3), []))
  129. a = np.zeros(3, dtype='i,i')
  130. # (warning is issued a couple of times here)
  131. self.assert_deprecated(op, args=(a, a[:-1]), num=None)
  132. # ragged array comparison returns True/False
  133. a = np.array([1, np.array([1,2,3])], dtype=object)
  134. b = np.array([1, np.array([1,2,3])], dtype=object)
  135. self.assert_deprecated(op, args=(a, b), num=None)
  136. def test_string(self):
  137. # For two string arrays, strings always raised the broadcasting error:
  138. a = np.array(['a', 'b'])
  139. b = np.array(['a', 'b', 'c'])
  140. assert_warns(FutureWarning, lambda x, y: x == y, a, b)
  141. # The empty list is not cast to string, and this used to pass due
  142. # to dtype mismatch; now (2018-06-21) it correctly leads to a
  143. # FutureWarning.
  144. assert_warns(FutureWarning, lambda: a == [])
  145. def test_void_dtype_equality_failures(self):
  146. class NotArray:
  147. def __array__(self):
  148. raise TypeError
  149. # Needed so Python 3 does not raise DeprecationWarning twice.
  150. def __ne__(self, other):
  151. return NotImplemented
  152. self.assert_deprecated(lambda: np.arange(2) == NotArray())
  153. self.assert_deprecated(lambda: np.arange(2) != NotArray())
  154. def test_array_richcompare_legacy_weirdness(self):
  155. # It doesn't really work to use assert_deprecated here, b/c part of
  156. # the point of assert_deprecated is to check that when warnings are
  157. # set to "error" mode then the error is propagated -- which is good!
  158. # But here we are testing a bunch of code that is deprecated *because*
  159. # it has the habit of swallowing up errors and converting them into
  160. # different warnings. So assert_warns will have to be sufficient.
  161. assert_warns(FutureWarning, lambda: np.arange(2) == "a")
  162. assert_warns(FutureWarning, lambda: np.arange(2) != "a")
  163. # No warning for scalar comparisons
  164. with warnings.catch_warnings():
  165. warnings.filterwarnings("error")
  166. assert_(not (np.array(0) == "a"))
  167. assert_(np.array(0) != "a")
  168. assert_(not (np.int16(0) == "a"))
  169. assert_(np.int16(0) != "a")
  170. for arg1 in [np.asarray(0), np.int16(0)]:
  171. struct = np.zeros(2, dtype="i4,i4")
  172. for arg2 in [struct, "a"]:
  173. for f in [operator.lt, operator.le, operator.gt, operator.ge]:
  174. with warnings.catch_warnings() as l:
  175. warnings.filterwarnings("always")
  176. assert_raises(TypeError, f, arg1, arg2)
  177. assert_(not l)
  178. class TestDatetime64Timezone(_DeprecationTestCase):
  179. """Parsing of datetime64 with timezones deprecated in 1.11.0, because
  180. datetime64 is now timezone naive rather than UTC only.
  181. It will be quite a while before we can remove this, because, at the very
  182. least, a lot of existing code uses the 'Z' modifier to avoid conversion
  183. from local time to UTC, even if otherwise it handles time in a timezone
  184. naive fashion.
  185. """
  186. def test_string(self):
  187. self.assert_deprecated(np.datetime64, args=('2000-01-01T00+01',))
  188. self.assert_deprecated(np.datetime64, args=('2000-01-01T00Z',))
  189. @pytest.mark.skipif(not _has_pytz,
  190. reason="The pytz module is not available.")
  191. def test_datetime(self):
  192. tz = pytz.timezone('US/Eastern')
  193. dt = datetime.datetime(2000, 1, 1, 0, 0, tzinfo=tz)
  194. self.assert_deprecated(np.datetime64, args=(dt,))
  195. class TestArrayDataAttributeAssignmentDeprecation(_DeprecationTestCase):
  196. """Assigning the 'data' attribute of an ndarray is unsafe as pointed
  197. out in gh-7093. Eventually, such assignment should NOT be allowed, but
  198. in the interests of maintaining backwards compatibility, only a Deprecation-
  199. Warning will be raised instead for the time being to give developers time to
  200. refactor relevant code.
  201. """
  202. def test_data_attr_assignment(self):
  203. a = np.arange(10)
  204. b = np.linspace(0, 1, 10)
  205. self.message = ("Assigning the 'data' attribute is an "
  206. "inherently unsafe operation and will "
  207. "be removed in the future.")
  208. self.assert_deprecated(a.__setattr__, args=('data', b.data))
  209. class TestBinaryReprInsufficientWidthParameterForRepresentation(_DeprecationTestCase):
  210. """
  211. If a 'width' parameter is passed into ``binary_repr`` that is insufficient to
  212. represent the number in base 2 (positive) or 2's complement (negative) form,
  213. the function used to silently ignore the parameter and return a representation
  214. using the minimal number of bits needed for the form in question. Such behavior
  215. is now considered unsafe from a user perspective and will raise an error in the future.
  216. """
  217. def test_insufficient_width_positive(self):
  218. args = (10,)
  219. kwargs = {'width': 2}
  220. self.message = ("Insufficient bit width provided. This behavior "
  221. "will raise an error in the future.")
  222. self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)
  223. def test_insufficient_width_negative(self):
  224. args = (-5,)
  225. kwargs = {'width': 2}
  226. self.message = ("Insufficient bit width provided. This behavior "
  227. "will raise an error in the future.")
  228. self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)
  229. class TestDTypeAttributeIsDTypeDeprecation(_DeprecationTestCase):
  230. # Deprecated 2021-01-05, NumPy 1.21
  231. message = r".*`.dtype` attribute"
  232. def test_deprecation_dtype_attribute_is_dtype(self):
  233. class dt:
  234. dtype = "f8"
  235. class vdt(np.void):
  236. dtype = "f,f"
  237. self.assert_deprecated(lambda: np.dtype(dt))
  238. self.assert_deprecated(lambda: np.dtype(dt()))
  239. self.assert_deprecated(lambda: np.dtype(vdt))
  240. self.assert_deprecated(lambda: np.dtype(vdt(1)))
  241. class TestTestDeprecated:
  242. def test_assert_deprecated(self):
  243. test_case_instance = _DeprecationTestCase()
  244. test_case_instance.setup_method()
  245. assert_raises(AssertionError,
  246. test_case_instance.assert_deprecated,
  247. lambda: None)
  248. def foo():
  249. warnings.warn("foo", category=DeprecationWarning, stacklevel=2)
  250. test_case_instance.assert_deprecated(foo)
  251. test_case_instance.teardown_method()
  252. class TestNonNumericConjugate(_DeprecationTestCase):
  253. """
  254. Deprecate no-op behavior of ndarray.conjugate on non-numeric dtypes,
  255. which conflicts with the error behavior of np.conjugate.
  256. """
  257. def test_conjugate(self):
  258. for a in np.array(5), np.array(5j):
  259. self.assert_not_deprecated(a.conjugate)
  260. for a in (np.array('s'), np.array('2016', 'M'),
  261. np.array((1, 2), [('a', int), ('b', int)])):
  262. self.assert_deprecated(a.conjugate)
  263. class TestNPY_CHAR(_DeprecationTestCase):
  264. # 2017-05-03, 1.13.0
  265. def test_npy_char_deprecation(self):
  266. from numpy.core._multiarray_tests import npy_char_deprecation
  267. self.assert_deprecated(npy_char_deprecation)
  268. assert_(npy_char_deprecation() == 'S1')
  269. class TestPyArray_AS1D(_DeprecationTestCase):
  270. def test_npy_pyarrayas1d_deprecation(self):
  271. from numpy.core._multiarray_tests import npy_pyarrayas1d_deprecation
  272. assert_raises(NotImplementedError, npy_pyarrayas1d_deprecation)
  273. class TestPyArray_AS2D(_DeprecationTestCase):
  274. def test_npy_pyarrayas2d_deprecation(self):
  275. from numpy.core._multiarray_tests import npy_pyarrayas2d_deprecation
  276. assert_raises(NotImplementedError, npy_pyarrayas2d_deprecation)
  277. class TestDatetimeEvent(_DeprecationTestCase):
  278. # 2017-08-11, 1.14.0
  279. def test_3_tuple(self):
  280. for cls in (np.datetime64, np.timedelta64):
  281. # two valid uses - (unit, num) and (unit, num, den, None)
  282. self.assert_not_deprecated(cls, args=(1, ('ms', 2)))
  283. self.assert_not_deprecated(cls, args=(1, ('ms', 2, 1, None)))
  284. # trying to use the event argument, removed in 1.7.0, is deprecated
  285. # it used to be a uint8
  286. self.assert_deprecated(cls, args=(1, ('ms', 2, 'event')))
  287. self.assert_deprecated(cls, args=(1, ('ms', 2, 63)))
  288. self.assert_deprecated(cls, args=(1, ('ms', 2, 1, 'event')))
  289. self.assert_deprecated(cls, args=(1, ('ms', 2, 1, 63)))
  290. class TestTruthTestingEmptyArrays(_DeprecationTestCase):
  291. # 2017-09-25, 1.14.0
  292. message = '.*truth value of an empty array is ambiguous.*'
  293. def test_1d(self):
  294. self.assert_deprecated(bool, args=(np.array([]),))
  295. def test_2d(self):
  296. self.assert_deprecated(bool, args=(np.zeros((1, 0)),))
  297. self.assert_deprecated(bool, args=(np.zeros((0, 1)),))
  298. self.assert_deprecated(bool, args=(np.zeros((0, 0)),))
  299. class TestBincount(_DeprecationTestCase):
  300. # 2017-06-01, 1.14.0
  301. def test_bincount_minlength(self):
  302. self.assert_deprecated(lambda: np.bincount([1, 2, 3], minlength=None))
  303. class TestGeneratorSum(_DeprecationTestCase):
  304. # 2018-02-25, 1.15.0
  305. def test_generator_sum(self):
  306. self.assert_deprecated(np.sum, args=((i for i in range(5)),))
  307. class TestPositiveOnNonNumerical(_DeprecationTestCase):
  308. # 2018-06-28, 1.16.0
  309. def test_positive_on_non_number(self):
  310. self.assert_deprecated(operator.pos, args=(np.array('foo'),))
  311. class TestFromstring(_DeprecationTestCase):
  312. # 2017-10-19, 1.14
  313. def test_fromstring(self):
  314. self.assert_deprecated(np.fromstring, args=('\x00'*80,))
  315. class TestFromStringAndFileInvalidData(_DeprecationTestCase):
  316. # 2019-06-08, 1.17.0
  317. # Tests should be moved to real tests when deprecation is done.
  318. message = "string or file could not be read to its end"
  319. @pytest.mark.parametrize("invalid_str", [",invalid_data", "invalid_sep"])
  320. def test_deprecate_unparsable_data_file(self, invalid_str):
  321. x = np.array([1.51, 2, 3.51, 4], dtype=float)
  322. with tempfile.TemporaryFile(mode="w") as f:
  323. x.tofile(f, sep=',', format='%.2f')
  324. f.write(invalid_str)
  325. f.seek(0)
  326. self.assert_deprecated(lambda: np.fromfile(f, sep=","))
  327. f.seek(0)
  328. self.assert_deprecated(lambda: np.fromfile(f, sep=",", count=5))
  329. # Should not raise:
  330. with warnings.catch_warnings():
  331. warnings.simplefilter("error", DeprecationWarning)
  332. f.seek(0)
  333. res = np.fromfile(f, sep=",", count=4)
  334. assert_array_equal(res, x)
  335. @pytest.mark.parametrize("invalid_str", [",invalid_data", "invalid_sep"])
  336. def test_deprecate_unparsable_string(self, invalid_str):
  337. x = np.array([1.51, 2, 3.51, 4], dtype=float)
  338. x_str = "1.51,2,3.51,4{}".format(invalid_str)
  339. self.assert_deprecated(lambda: np.fromstring(x_str, sep=","))
  340. self.assert_deprecated(lambda: np.fromstring(x_str, sep=",", count=5))
  341. # The C-level API can use not fixed size, but 0 terminated strings,
  342. # so test that as well:
  343. bytestr = x_str.encode("ascii")
  344. self.assert_deprecated(lambda: fromstring_null_term_c_api(bytestr))
  345. with assert_warns(DeprecationWarning):
  346. # this is slightly strange, in that fromstring leaves data
  347. # potentially uninitialized (would be good to error when all is
  348. # read, but count is larger then actual data maybe).
  349. res = np.fromstring(x_str, sep=",", count=5)
  350. assert_array_equal(res[:-1], x)
  351. with warnings.catch_warnings():
  352. warnings.simplefilter("error", DeprecationWarning)
  353. # Should not raise:
  354. res = np.fromstring(x_str, sep=",", count=4)
  355. assert_array_equal(res, x)
  356. class Test_GetSet_NumericOps(_DeprecationTestCase):
  357. # 2018-09-20, 1.16.0
  358. def test_get_numeric_ops(self):
  359. from numpy.core._multiarray_tests import getset_numericops
  360. self.assert_deprecated(getset_numericops, num=2)
  361. # empty kwargs prevents any state actually changing which would break
  362. # other tests.
  363. self.assert_deprecated(np.set_numeric_ops, kwargs={})
  364. assert_raises(ValueError, np.set_numeric_ops, add='abc')
  365. class TestShape1Fields(_DeprecationTestCase):
  366. warning_cls = FutureWarning
  367. # 2019-05-20, 1.17.0
  368. def test_shape_1_fields(self):
  369. self.assert_deprecated(np.dtype, args=([('a', int, 1)],))
  370. class TestNonZero(_DeprecationTestCase):
  371. # 2019-05-26, 1.17.0
  372. def test_zerod(self):
  373. self.assert_deprecated(lambda: np.nonzero(np.array(0)))
  374. self.assert_deprecated(lambda: np.nonzero(np.array(1)))
  375. class TestToString(_DeprecationTestCase):
  376. # 2020-03-06 1.19.0
  377. message = re.escape("tostring() is deprecated. Use tobytes() instead.")
  378. def test_tostring(self):
  379. arr = np.array(list(b"test\xFF"), dtype=np.uint8)
  380. self.assert_deprecated(arr.tostring)
  381. def test_tostring_matches_tobytes(self):
  382. arr = np.array(list(b"test\xFF"), dtype=np.uint8)
  383. b = arr.tobytes()
  384. with assert_warns(DeprecationWarning):
  385. s = arr.tostring()
  386. assert s == b
  387. class TestDTypeCoercion(_DeprecationTestCase):
  388. # 2020-02-06 1.19.0
  389. message = "Converting .* to a dtype .*is deprecated"
  390. deprecated_types = [
  391. # The builtin scalar super types:
  392. np.generic, np.flexible, np.number,
  393. np.inexact, np.floating, np.complexfloating,
  394. np.integer, np.unsignedinteger, np.signedinteger,
  395. # character is a deprecated S1 special case:
  396. np.character,
  397. ]
  398. def test_dtype_coercion(self):
  399. for scalar_type in self.deprecated_types:
  400. self.assert_deprecated(np.dtype, args=(scalar_type,))
  401. def test_array_construction(self):
  402. for scalar_type in self.deprecated_types:
  403. self.assert_deprecated(np.array, args=([], scalar_type,))
  404. def test_not_deprecated(self):
  405. # All specific types are not deprecated:
  406. for group in np.sctypes.values():
  407. for scalar_type in group:
  408. self.assert_not_deprecated(np.dtype, args=(scalar_type,))
  409. for scalar_type in [type, dict, list, tuple]:
  410. # Typical python types are coerced to object currently:
  411. self.assert_not_deprecated(np.dtype, args=(scalar_type,))
  412. class BuiltInRoundComplexDType(_DeprecationTestCase):
  413. # 2020-03-31 1.19.0
  414. deprecated_types = [np.csingle, np.cdouble, np.clongdouble]
  415. not_deprecated_types = [
  416. np.int8, np.int16, np.int32, np.int64,
  417. np.uint8, np.uint16, np.uint32, np.uint64,
  418. np.float16, np.float32, np.float64,
  419. ]
  420. def test_deprecated(self):
  421. for scalar_type in self.deprecated_types:
  422. scalar = scalar_type(0)
  423. self.assert_deprecated(round, args=(scalar,))
  424. self.assert_deprecated(round, args=(scalar, 0))
  425. self.assert_deprecated(round, args=(scalar,), kwargs={'ndigits': 0})
  426. def test_not_deprecated(self):
  427. for scalar_type in self.not_deprecated_types:
  428. scalar = scalar_type(0)
  429. self.assert_not_deprecated(round, args=(scalar,))
  430. self.assert_not_deprecated(round, args=(scalar, 0))
  431. self.assert_not_deprecated(round, args=(scalar,), kwargs={'ndigits': 0})
  432. class TestIncorrectAdvancedIndexWithEmptyResult(_DeprecationTestCase):
  433. # 2020-05-27, NumPy 1.20.0
  434. message = "Out of bound index found. This was previously ignored.*"
  435. @pytest.mark.parametrize("index", [([3, 0],), ([0, 0], [3, 0])])
  436. def test_empty_subspace(self, index):
  437. # Test for both a single and two/multiple advanced indices. These
  438. # This will raise an IndexError in the future.
  439. arr = np.ones((2, 2, 0))
  440. self.assert_deprecated(arr.__getitem__, args=(index,))
  441. self.assert_deprecated(arr.__setitem__, args=(index, 0.))
  442. # for this array, the subspace is only empty after applying the slice
  443. arr2 = np.ones((2, 2, 1))
  444. index2 = (slice(0, 0),) + index
  445. self.assert_deprecated(arr2.__getitem__, args=(index2,))
  446. self.assert_deprecated(arr2.__setitem__, args=(index2, 0.))
  447. def test_empty_index_broadcast_not_deprecated(self):
  448. arr = np.ones((2, 2, 2))
  449. index = ([[3], [2]], []) # broadcast to an empty result.
  450. self.assert_not_deprecated(arr.__getitem__, args=(index,))
  451. self.assert_not_deprecated(arr.__setitem__,
  452. args=(index, np.empty((2, 0, 2))))
  453. class TestNonExactMatchDeprecation(_DeprecationTestCase):
  454. # 2020-04-22
  455. def test_non_exact_match(self):
  456. arr = np.array([[3, 6, 6], [4, 5, 1]])
  457. # misspelt mode check
  458. self.assert_deprecated(lambda: np.ravel_multi_index(arr, (7, 6), mode='Cilp'))
  459. # using completely different word with first character as R
  460. self.assert_deprecated(lambda: np.searchsorted(arr[0], 4, side='Random'))
  461. class TestMatrixInOuter(_DeprecationTestCase):
  462. # 2020-05-13 NumPy 1.20.0
  463. message = (r"add.outer\(\) was passed a numpy matrix as "
  464. r"(first|second) argument.")
  465. def test_deprecated(self):
  466. arr = np.array([1, 2, 3])
  467. m = np.array([1, 2, 3]).view(np.matrix)
  468. self.assert_deprecated(np.add.outer, args=(m, m), num=2)
  469. self.assert_deprecated(np.add.outer, args=(arr, m))
  470. self.assert_deprecated(np.add.outer, args=(m, arr))
  471. self.assert_not_deprecated(np.add.outer, args=(arr, arr))
  472. class FlatteningConcatenateUnsafeCast(_DeprecationTestCase):
  473. # NumPy 1.20, 2020-09-03
  474. message = "concatenate with `axis=None` will use same-kind casting"
  475. def test_deprecated(self):
  476. self.assert_deprecated(np.concatenate,
  477. args=(([0.], [1.]),),
  478. kwargs=dict(axis=None, out=np.empty(2, dtype=np.int64)))
  479. def test_not_deprecated(self):
  480. self.assert_not_deprecated(np.concatenate,
  481. args=(([0.], [1.]),),
  482. kwargs={'axis': None, 'out': np.empty(2, dtype=np.int64),
  483. 'casting': "unsafe"})
  484. with assert_raises(TypeError):
  485. # Tests should notice if the deprecation warning is given first...
  486. np.concatenate(([0.], [1.]), out=np.empty(2, dtype=np.int64),
  487. casting="same_kind")
  488. class TestDeprecateSubarrayDTypeDuringArrayCoercion(_DeprecationTestCase):
  489. warning_cls = FutureWarning
  490. message = "(creating|casting) an array (with|to) a subarray dtype"
  491. def test_deprecated_array(self):
  492. # Arrays are more complex, since they "broadcast" on success:
  493. arr = np.array([1, 2])
  494. self.assert_deprecated(lambda: arr.astype("(2)i,"))
  495. with pytest.warns(FutureWarning):
  496. res = arr.astype("(2)i,")
  497. assert_array_equal(res, [[1, 2], [1, 2]])
  498. self.assert_deprecated(lambda: np.array(arr, dtype="(2)i,"))
  499. with pytest.warns(FutureWarning):
  500. res = np.array(arr, dtype="(2)i,")
  501. assert_array_equal(res, [[1, 2], [1, 2]])
  502. with pytest.warns(FutureWarning):
  503. res = np.array([[(1,), (2,)], arr], dtype="(2)i,")
  504. assert_array_equal(res, [[[1, 1], [2, 2]], [[1, 2], [1, 2]]])
  505. def test_deprecated_and_error(self):
  506. # These error paths do not give a warning, but will succeed in the
  507. # future.
  508. arr = np.arange(5 * 2).reshape(5, 2)
  509. def check():
  510. with pytest.raises(ValueError):
  511. arr.astype("(2,2)f")
  512. self.assert_deprecated(check)
  513. def check():
  514. with pytest.raises(ValueError):
  515. np.array(arr, dtype="(2,2)f")
  516. self.assert_deprecated(check)
  517. class TestFutureWarningArrayLikeNotIterable(_DeprecationTestCase):
  518. # Deprecated 2020-12-09, NumPy 1.20
  519. warning_cls = FutureWarning
  520. message = "The input object of type.*but not a sequence"
  521. @pytest.mark.parametrize("protocol",
  522. ["__array__", "__array_interface__", "__array_struct__"])
  523. def test_deprecated(self, protocol):
  524. """Test that these objects give a warning since they are not 0-D,
  525. not coerced at the top level `np.array(obj)`, but nested, and do
  526. *not* define the sequence protocol.
  527. NOTE: Tests for the versions including __len__ and __getitem__ exist
  528. in `test_array_coercion.py` and they can be modified or amended
  529. when this deprecation expired.
  530. """
  531. blueprint = np.arange(10)
  532. MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol)})
  533. self.assert_deprecated(lambda: np.array([MyArr()], dtype=object))
  534. @pytest.mark.parametrize("protocol",
  535. ["__array__", "__array_interface__", "__array_struct__"])
  536. def test_0d_not_deprecated(self, protocol):
  537. # 0-D always worked (albeit it would use __float__ or similar for the
  538. # conversion, which may not happen anymore)
  539. blueprint = np.array(1.)
  540. MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol)})
  541. myarr = MyArr()
  542. self.assert_not_deprecated(lambda: np.array([myarr], dtype=object))
  543. res = np.array([myarr], dtype=object)
  544. expected = np.empty(1, dtype=object)
  545. expected[0] = myarr
  546. assert_array_equal(res, expected)
  547. @pytest.mark.parametrize("protocol",
  548. ["__array__", "__array_interface__", "__array_struct__"])
  549. def test_unnested_not_deprecated(self, protocol):
  550. blueprint = np.arange(10)
  551. MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol)})
  552. myarr = MyArr()
  553. self.assert_not_deprecated(lambda: np.array(myarr))
  554. res = np.array(myarr)
  555. assert_array_equal(res, blueprint)
  556. @pytest.mark.parametrize("protocol",
  557. ["__array__", "__array_interface__", "__array_struct__"])
  558. def test_strange_dtype_handling(self, protocol):
  559. """The old code would actually use the dtype from the array, but
  560. then end up not using the array (for dimension discovery)
  561. """
  562. blueprint = np.arange(10).astype("f4")
  563. MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol),
  564. "__float__": lambda _: 0.5})
  565. myarr = MyArr()
  566. # Make sure we warn (and capture the FutureWarning)
  567. with pytest.warns(FutureWarning, match=self.message):
  568. res = np.array([[myarr]])
  569. assert res.shape == (1, 1)
  570. assert res.dtype == "f4"
  571. assert res[0, 0] == 0.5
  572. @pytest.mark.parametrize("protocol",
  573. ["__array__", "__array_interface__", "__array_struct__"])
  574. def test_assignment_not_deprecated(self, protocol):
  575. # If the result is dtype=object we do not unpack a nested array or
  576. # array-like, if it is nested at exactly the right depth.
  577. # NOTE: We actually do still call __array__, etc. but ignore the result
  578. # in the end. For `dtype=object` we could optimize that away.
  579. blueprint = np.arange(10).astype("f4")
  580. MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol),
  581. "__float__": lambda _: 0.5})
  582. myarr = MyArr()
  583. res = np.empty(3, dtype=object)
  584. def set():
  585. res[:] = [myarr, myarr, myarr]
  586. self.assert_not_deprecated(set)
  587. assert res[0] is myarr
  588. assert res[1] is myarr
  589. assert res[2] is myarr
  590. class TestDeprecatedUnpickleObjectScalar(_DeprecationTestCase):
  591. # Deprecated 2020-11-24, NumPy 1.20
  592. """
  593. Technically, it should be impossible to create numpy object scalars,
  594. but there was an unpickle path that would in theory allow it. That
  595. path is invalid and must lead to the warning.
  596. """
  597. message = "Unpickling a scalar with object dtype is deprecated."
  598. def test_deprecated(self):
  599. ctor = np.core.multiarray.scalar
  600. self.assert_deprecated(lambda: ctor(np.dtype("O"), 1))
  601. try:
  602. with warnings.catch_warnings():
  603. warnings.simplefilter("always")
  604. import nose # noqa: F401
  605. except ImportError:
  606. HAVE_NOSE = False
  607. else:
  608. HAVE_NOSE = True
  609. @pytest.mark.skipif(not HAVE_NOSE, reason="Needs nose")
  610. class TestNoseDecoratorsDeprecated(_DeprecationTestCase):
  611. class DidntSkipException(Exception):
  612. pass
  613. def test_slow(self):
  614. def _test_slow():
  615. @np.testing.dec.slow
  616. def slow_func(x, y, z):
  617. pass
  618. assert_(slow_func.slow)
  619. self.assert_deprecated(_test_slow)
  620. def test_setastest(self):
  621. def _test_setastest():
  622. @np.testing.dec.setastest()
  623. def f_default(a):
  624. pass
  625. @np.testing.dec.setastest(True)
  626. def f_istest(a):
  627. pass
  628. @np.testing.dec.setastest(False)
  629. def f_isnottest(a):
  630. pass
  631. assert_(f_default.__test__)
  632. assert_(f_istest.__test__)
  633. assert_(not f_isnottest.__test__)
  634. self.assert_deprecated(_test_setastest, num=3)
  635. def test_skip_functions_hardcoded(self):
  636. def _test_skip_functions_hardcoded():
  637. @np.testing.dec.skipif(True)
  638. def f1(x):
  639. raise self.DidntSkipException
  640. try:
  641. f1('a')
  642. except self.DidntSkipException:
  643. raise Exception('Failed to skip')
  644. except SkipTest().__class__:
  645. pass
  646. @np.testing.dec.skipif(False)
  647. def f2(x):
  648. raise self.DidntSkipException
  649. try:
  650. f2('a')
  651. except self.DidntSkipException:
  652. pass
  653. except SkipTest().__class__:
  654. raise Exception('Skipped when not expected to')
  655. self.assert_deprecated(_test_skip_functions_hardcoded, num=2)
  656. def test_skip_functions_callable(self):
  657. def _test_skip_functions_callable():
  658. def skip_tester():
  659. return skip_flag == 'skip me!'
  660. @np.testing.dec.skipif(skip_tester)
  661. def f1(x):
  662. raise self.DidntSkipException
  663. try:
  664. skip_flag = 'skip me!'
  665. f1('a')
  666. except self.DidntSkipException:
  667. raise Exception('Failed to skip')
  668. except SkipTest().__class__:
  669. pass
  670. @np.testing.dec.skipif(skip_tester)
  671. def f2(x):
  672. raise self.DidntSkipException
  673. try:
  674. skip_flag = 'five is right out!'
  675. f2('a')
  676. except self.DidntSkipException:
  677. pass
  678. except SkipTest().__class__:
  679. raise Exception('Skipped when not expected to')
  680. self.assert_deprecated(_test_skip_functions_callable, num=2)
  681. def test_skip_generators_hardcoded(self):
  682. def _test_skip_generators_hardcoded():
  683. @np.testing.dec.knownfailureif(True, "This test is known to fail")
  684. def g1(x):
  685. yield from range(x)
  686. try:
  687. for j in g1(10):
  688. pass
  689. except KnownFailureException().__class__:
  690. pass
  691. else:
  692. raise Exception('Failed to mark as known failure')
  693. @np.testing.dec.knownfailureif(False, "This test is NOT known to fail")
  694. def g2(x):
  695. yield from range(x)
  696. raise self.DidntSkipException('FAIL')
  697. try:
  698. for j in g2(10):
  699. pass
  700. except KnownFailureException().__class__:
  701. raise Exception('Marked incorrectly as known failure')
  702. except self.DidntSkipException:
  703. pass
  704. self.assert_deprecated(_test_skip_generators_hardcoded, num=2)
  705. def test_skip_generators_callable(self):
  706. def _test_skip_generators_callable():
  707. def skip_tester():
  708. return skip_flag == 'skip me!'
  709. @np.testing.dec.knownfailureif(skip_tester, "This test is known to fail")
  710. def g1(x):
  711. yield from range(x)
  712. try:
  713. skip_flag = 'skip me!'
  714. for j in g1(10):
  715. pass
  716. except KnownFailureException().__class__:
  717. pass
  718. else:
  719. raise Exception('Failed to mark as known failure')
  720. @np.testing.dec.knownfailureif(skip_tester, "This test is NOT known to fail")
  721. def g2(x):
  722. yield from range(x)
  723. raise self.DidntSkipException('FAIL')
  724. try:
  725. skip_flag = 'do not skip'
  726. for j in g2(10):
  727. pass
  728. except KnownFailureException().__class__:
  729. raise Exception('Marked incorrectly as known failure')
  730. except self.DidntSkipException:
  731. pass
  732. self.assert_deprecated(_test_skip_generators_callable, num=2)
  733. def test_deprecated(self):
  734. def _test_deprecated():
  735. @np.testing.dec.deprecated(True)
  736. def non_deprecated_func():
  737. pass
  738. @np.testing.dec.deprecated()
  739. def deprecated_func():
  740. import warnings
  741. warnings.warn("TEST: deprecated func", DeprecationWarning, stacklevel=1)
  742. @np.testing.dec.deprecated()
  743. def deprecated_func2():
  744. import warnings
  745. warnings.warn("AHHHH", stacklevel=1)
  746. raise ValueError
  747. @np.testing.dec.deprecated()
  748. def deprecated_func3():
  749. import warnings
  750. warnings.warn("AHHHH", stacklevel=1)
  751. # marked as deprecated, but does not raise DeprecationWarning
  752. assert_raises(AssertionError, non_deprecated_func)
  753. # should be silent
  754. deprecated_func()
  755. with warnings.catch_warnings(record=True):
  756. warnings.simplefilter("always") # do not propagate unrelated warnings
  757. # fails if deprecated decorator just disables test. See #1453.
  758. assert_raises(ValueError, deprecated_func2)
  759. # warning is not a DeprecationWarning
  760. assert_raises(AssertionError, deprecated_func3)
  761. self.assert_deprecated(_test_deprecated, num=4)
  762. def test_parametrize(self):
  763. def _test_parametrize():
  764. # dec.parametrize assumes that it is being run by nose. Because
  765. # we are running under pytest, we need to explicitly check the
  766. # results.
  767. @np.testing.dec.parametrize('base, power, expected',
  768. [(1, 1, 1),
  769. (2, 1, 2),
  770. (2, 2, 4)])
  771. def check_parametrize(base, power, expected):
  772. assert_(base**power == expected)
  773. count = 0
  774. for test in check_parametrize():
  775. test[0](*test[1:])
  776. count += 1
  777. assert_(count == 3)
  778. self.assert_deprecated(_test_parametrize)
  779. class TestSingleElementSignature(_DeprecationTestCase):
  780. # Deprecated 2021-04-01, NumPy 1.21
  781. message = r"The use of a length 1"
  782. def test_deprecated(self):
  783. self.assert_deprecated(lambda: np.add(1, 2, signature="d"))
  784. self.assert_deprecated(lambda: np.add(1, 2, sig=(np.dtype("l"),)))
  785. class TestCtypesGetter(_DeprecationTestCase):
  786. # Deprecated 2021-05-18, Numpy 1.21.0
  787. warning_cls = DeprecationWarning
  788. ctypes = np.array([1]).ctypes
  789. @pytest.mark.parametrize(
  790. "name", ["get_data", "get_shape", "get_strides", "get_as_parameter"]
  791. )
  792. def test_deprecated(self, name: str) -> None:
  793. func = getattr(self.ctypes, name)
  794. self.assert_deprecated(lambda: func())
  795. @pytest.mark.parametrize(
  796. "name", ["data", "shape", "strides", "_as_parameter_"]
  797. )
  798. def test_not_deprecated(self, name: str) -> None:
  799. self.assert_not_deprecated(lambda: getattr(self.ctypes, name))
  800. PARTITION_DICT = {
  801. "partition method": np.arange(10).partition,
  802. "argpartition method": np.arange(10).argpartition,
  803. "partition function": lambda kth: np.partition(np.arange(10), kth),
  804. "argpartition function": lambda kth: np.argpartition(np.arange(10), kth),
  805. }
  806. @pytest.mark.parametrize("func", PARTITION_DICT.values(), ids=PARTITION_DICT)
  807. class TestPartitionBoolIndex(_DeprecationTestCase):
  808. # Deprecated 2021-09-29, NumPy 1.22
  809. warning_cls = DeprecationWarning
  810. message = "Passing booleans as partition index is deprecated"
  811. def test_deprecated(self, func):
  812. self.assert_deprecated(lambda: func(True))
  813. self.assert_deprecated(lambda: func([False, True]))
  814. def test_not_deprecated(self, func):
  815. self.assert_not_deprecated(lambda: func(1))
  816. self.assert_not_deprecated(lambda: func([0, 1]))
  817. class TestMachAr(_DeprecationTestCase):
  818. # Deprecated 2021-10-19, NumPy 1.22
  819. warning_cls = DeprecationWarning
  820. def test_deprecated_module(self):
  821. self.assert_deprecated(lambda: getattr(np.core, "machar"))
  822. def test_deprecated_attr(self):
  823. finfo = np.finfo(float)
  824. self.assert_deprecated(lambda: getattr(finfo, "machar"))
  825. class TestQuantileInterpolationDeprecation(_DeprecationTestCase):
  826. # Deprecated 2021-11-08, NumPy 1.22
  827. @pytest.mark.parametrize("func",
  828. [np.percentile, np.quantile, np.nanpercentile, np.nanquantile])
  829. def test_deprecated(self, func):
  830. self.assert_deprecated(
  831. lambda: func([0., 1.], 0., interpolation="linear"))
  832. self.assert_deprecated(
  833. lambda: func([0., 1.], 0., interpolation="nearest"))
  834. @pytest.mark.parametrize("func",
  835. [np.percentile, np.quantile, np.nanpercentile, np.nanquantile])
  836. def test_both_passed(self, func):
  837. with warnings.catch_warnings():
  838. # catch the DeprecationWarning so that it does not raise:
  839. warnings.simplefilter("always", DeprecationWarning)
  840. with pytest.raises(TypeError):
  841. func([0., 1.], 0., interpolation="nearest", method="nearest")
  842. class TestMemEventHook(_DeprecationTestCase):
  843. # Deprecated 2021-11-18, NumPy 1.23
  844. def test_mem_seteventhook(self):
  845. # The actual tests are within the C code in
  846. # multiarray/_multiarray_tests.c.src
  847. import numpy.core._multiarray_tests as ma_tests
  848. with pytest.warns(DeprecationWarning,
  849. match='PyDataMem_SetEventHook is deprecated'):
  850. ma_tests.test_pydatamem_seteventhook_start()
  851. # force an allocation and free of a numpy array
  852. # needs to be larger then limit of small memory cacher in ctors.c
  853. a = np.zeros(1000)
  854. del a
  855. break_cycles()
  856. with pytest.warns(DeprecationWarning,
  857. match='PyDataMem_SetEventHook is deprecated'):
  858. ma_tests.test_pydatamem_seteventhook_end()
  859. class TestArrayFinalizeNone(_DeprecationTestCase):
  860. message = "Setting __array_finalize__ = None"
  861. def test_use_none_is_deprecated(self):
  862. # Deprecated way that ndarray itself showed nothing needs finalizing.
  863. class NoFinalize(np.ndarray):
  864. __array_finalize__ = None
  865. self.assert_deprecated(lambda: np.array(1).view(NoFinalize))
  866. class TestAxisNotMAXDIMS(_DeprecationTestCase):
  867. # Deprecated 2022-01-08, NumPy 1.23
  868. message = r"Using `axis=32` \(MAXDIMS\) is deprecated"
  869. def test_deprecated(self):
  870. a = np.zeros((1,)*32)
  871. self.assert_deprecated(lambda: np.repeat(a, 1, axis=np.MAXDIMS))
  872. class TestLoadtxtParseIntsViaFloat(_DeprecationTestCase):
  873. # Deprecated 2022-07-03, NumPy 1.23
  874. # This test can be removed without replacement after the deprecation.
  875. # The tests:
  876. # * numpy/lib/tests/test_loadtxt.py::test_integer_signs
  877. # * lib/tests/test_loadtxt.py::test_implicit_cast_float_to_int_fails
  878. # Have a warning filter that needs to be removed.
  879. message = r"loadtxt\(\): Parsing an integer via a float is deprecated.*"
  880. @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
  881. def test_deprecated_warning(self, dtype):
  882. with pytest.warns(DeprecationWarning, match=self.message):
  883. np.loadtxt(["10.5"], dtype=dtype)
  884. @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
  885. def test_deprecated_raised(self, dtype):
  886. # The DeprecationWarning is chained when raised, so test manually:
  887. with warnings.catch_warnings():
  888. warnings.simplefilter("error", DeprecationWarning)
  889. try:
  890. np.loadtxt(["10.5"], dtype=dtype)
  891. except ValueError as e:
  892. assert isinstance(e.__cause__, DeprecationWarning)
  893. class TestPyIntConversion(_DeprecationTestCase):
  894. message = r".*stop allowing conversion of out-of-bound.*"
  895. @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
  896. def test_deprecated_scalar(self, dtype):
  897. dtype = np.dtype(dtype)
  898. info = np.iinfo(dtype)
  899. # Cover the most common creation paths (all end up in the
  900. # same place):
  901. def scalar(value, dtype):
  902. dtype.type(value)
  903. def assign(value, dtype):
  904. arr = np.array([0, 0, 0], dtype=dtype)
  905. arr[2] = value
  906. def create(value, dtype):
  907. np.array([value], dtype=dtype)
  908. for creation_func in [scalar, assign, create]:
  909. try:
  910. self.assert_deprecated(
  911. lambda: creation_func(info.min - 1, dtype))
  912. except OverflowError:
  913. pass # OverflowErrors always happened also before and are OK.
  914. try:
  915. self.assert_deprecated(
  916. lambda: creation_func(info.max + 1, dtype))
  917. except OverflowError:
  918. pass # OverflowErrors always happened also before and are OK.
  919. class TestDeprecatedGlobals(_DeprecationTestCase):
  920. # Deprecated 2022-11-17, NumPy 1.24
  921. def test_type_aliases(self):
  922. # from builtins
  923. self.assert_deprecated(lambda: np.bool8)
  924. self.assert_deprecated(lambda: np.int0)
  925. self.assert_deprecated(lambda: np.uint0)
  926. self.assert_deprecated(lambda: np.bytes0)
  927. self.assert_deprecated(lambda: np.str0)
  928. self.assert_deprecated(lambda: np.object0)
  929. @pytest.mark.parametrize("name",
  930. ["bool", "long", "ulong", "str", "bytes", "object"])
  931. def test_future_scalar_attributes(name):
  932. # FutureWarning added 2022-11-17, NumPy 1.24,
  933. assert name not in dir(np) # we may want to not add them
  934. with pytest.warns(FutureWarning,
  935. match=f"In the future .*{name}"):
  936. assert not hasattr(np, name)
  937. # Unfortunately, they are currently still valid via `np.dtype()`
  938. np.dtype(name)
  939. name in np.sctypeDict
  940. # Ignore the above future attribute warning for this test.
  941. @pytest.mark.filterwarnings("ignore:In the future:FutureWarning")
  942. class TestRemovedGlobals:
  943. # Removed 2023-01-12, NumPy 1.24.0
  944. # Not a deprecation, but the large error was added to aid those who missed
  945. # the previous deprecation, and should be removed similarly to one
  946. # (or faster).
  947. @pytest.mark.parametrize("name",
  948. ["object", "bool", "float", "complex", "str", "int"])
  949. def test_attributeerror_includes_info(self, name):
  950. msg = f".*\n`np.{name}` was a deprecated alias for the builtin"
  951. with pytest.raises(AttributeError, match=msg):
  952. getattr(np, name)