Best Python code snippet using PyHamcrest_python
test_deprecations.py
Source:test_deprecations.py
...37 warnings.filterwarnings("always", message=self.message,38 category=self.warning_cls)39 def teardown(self):40 self.warn_ctx.__exit__()41 def assert_deprecated(self, function, num=1, ignore_others=False,42 function_fails=False,43 exceptions=np._NoValue,44 args=(), kwargs={}):45 """Test if DeprecationWarnings are given and raised.46 This first checks if the function when called gives `num`47 DeprecationWarnings, after that it tries to raise these48 DeprecationWarnings and compares them with `exceptions`.49 The exceptions can be different for cases where this code path50 is simply not anticipated and the exception is replaced.51 Parameters52 ----------53 function : callable54 The function to test55 num : int56 Number of DeprecationWarnings to expect. This should normally be 1.57 ignore_others : bool58 Whether warnings of the wrong type should be ignored (note that59 the message is not checked)60 function_fails : bool61 If the function would normally fail, setting this will check for62 warnings inside a try/except block.63 exceptions : Exception or tuple of Exceptions64 Exception to expect when turning the warnings into an error.65 The default checks for DeprecationWarnings. If exceptions is66 empty the function is expected to run successfully.67 args : tuple68 Arguments for `function`69 kwargs : dict70 Keyword arguments for `function`71 """72 __tracebackhide__ = True # Hide traceback for py.test73 # reset the log74 self.log[:] = []75 if exceptions is np._NoValue:76 exceptions = (self.warning_cls,)77 try:78 function(*args, **kwargs)79 except (Exception if function_fails else tuple()):80 pass81 # just in case, clear the registry82 num_found = 083 for warning in self.log:84 if warning.category is self.warning_cls:85 num_found += 186 elif not ignore_others:87 raise AssertionError(88 "expected %s but got: %s" %89 (self.warning_cls.__name__, warning.category))90 if num is not None and num_found != num:91 msg = "%i warnings found but %i expected." % (len(self.log), num)92 lst = [str(w) for w in self.log]93 raise AssertionError("\n".join([msg] + lst))94 with warnings.catch_warnings():95 warnings.filterwarnings("error", message=self.message,96 category=self.warning_cls)97 try:98 function(*args, **kwargs)99 if exceptions != tuple():100 raise AssertionError(101 "No error raised during function call")102 except exceptions:103 if exceptions == tuple():104 raise AssertionError(105 "Error raised during function call")106 def assert_not_deprecated(self, function, args=(), kwargs={}):107 """Test that warnings are not raised.108 This is just a shorthand for:109 self.assert_deprecated(function, num=0, ignore_others=True,110 exceptions=tuple(), args=args, kwargs=kwargs)111 """112 self.assert_deprecated(function, num=0, ignore_others=True,113 exceptions=tuple(), args=args, kwargs=kwargs)114class _VisibleDeprecationTestCase(_DeprecationTestCase):115 warning_cls = np.VisibleDeprecationWarning116class TestNonTupleNDIndexDeprecation:117 def test_basic(self):118 a = np.zeros((5, 5))119 with warnings.catch_warnings():120 warnings.filterwarnings('always')121 assert_warns(FutureWarning, a.__getitem__, [[0, 1], [0, 1]])122 assert_warns(FutureWarning, a.__getitem__, [slice(None)])123 warnings.filterwarnings('error')124 assert_raises(FutureWarning, a.__getitem__, [[0, 1], [0, 1]])125 assert_raises(FutureWarning, a.__getitem__, [slice(None)])126 # a a[[0, 1]] always was advanced indexing, so no error/warning127 a[[0, 1]]128class TestComparisonDeprecations(_DeprecationTestCase):129 """This tests the deprecation, for non-element-wise comparison logic.130 This used to mean that when an error occurred during element-wise comparison131 (i.e. broadcasting) NotImplemented was returned, but also in the comparison132 itself, False was given instead of the error.133 Also test FutureWarning for the None comparison.134 """135 message = "elementwise.* comparison failed; .*"136 def test_normal_types(self):137 for op in (operator.eq, operator.ne):138 # Broadcasting errors:139 self.assert_deprecated(op, args=(np.zeros(3), []))140 a = np.zeros(3, dtype='i,i')141 # (warning is issued a couple of times here)142 self.assert_deprecated(op, args=(a, a[:-1]), num=None)143 # ragged array comparison returns True/False144 a = np.array([1, np.array([1,2,3])], dtype=object)145 b = np.array([1, np.array([1,2,3])], dtype=object)146 self.assert_deprecated(op, args=(a, b), num=None)147 def test_string(self):148 # For two string arrays, strings always raised the broadcasting error:149 a = np.array(['a', 'b'])150 b = np.array(['a', 'b', 'c'])151 assert_raises(ValueError, lambda x, y: x == y, a, b)152 # The empty list is not cast to string, and this used to pass due153 # to dtype mismatch; now (2018-06-21) it correctly leads to a154 # FutureWarning.155 assert_warns(FutureWarning, lambda: a == [])156 def test_void_dtype_equality_failures(self):157 class NotArray:158 def __array__(self):159 raise TypeError160 # Needed so Python 3 does not raise DeprecationWarning twice.161 def __ne__(self, other):162 return NotImplemented163 self.assert_deprecated(lambda: np.arange(2) == NotArray())164 self.assert_deprecated(lambda: np.arange(2) != NotArray())165 struct1 = np.zeros(2, dtype="i4,i4")166 struct2 = np.zeros(2, dtype="i4,i4,i4")167 assert_warns(FutureWarning, lambda: struct1 == 1)168 assert_warns(FutureWarning, lambda: struct1 == struct2)169 assert_warns(FutureWarning, lambda: struct1 != 1)170 assert_warns(FutureWarning, lambda: struct1 != struct2)171 def test_array_richcompare_legacy_weirdness(self):172 # It doesn't really work to use assert_deprecated here, b/c part of173 # the point of assert_deprecated is to check that when warnings are174 # set to "error" mode then the error is propagated -- which is good!175 # But here we are testing a bunch of code that is deprecated *because*176 # it has the habit of swallowing up errors and converting them into177 # different warnings. So assert_warns will have to be sufficient.178 assert_warns(FutureWarning, lambda: np.arange(2) == "a")179 assert_warns(FutureWarning, lambda: np.arange(2) != "a")180 # No warning for scalar comparisons181 with warnings.catch_warnings():182 warnings.filterwarnings("error")183 assert_(not (np.array(0) == "a"))184 assert_(np.array(0) != "a")185 assert_(not (np.int16(0) == "a"))186 assert_(np.int16(0) != "a")187 for arg1 in [np.asarray(0), np.int16(0)]:188 struct = np.zeros(2, dtype="i4,i4")189 for arg2 in [struct, "a"]:190 for f in [operator.lt, operator.le, operator.gt, operator.ge]:191 with warnings.catch_warnings() as l:192 warnings.filterwarnings("always")193 assert_raises(TypeError, f, arg1, arg2)194 assert_(not l)195class TestDatetime64Timezone(_DeprecationTestCase):196 """Parsing of datetime64 with timezones deprecated in 1.11.0, because197 datetime64 is now timezone naive rather than UTC only.198 It will be quite a while before we can remove this, because, at the very199 least, a lot of existing code uses the 'Z' modifier to avoid conversion200 from local time to UTC, even if otherwise it handles time in a timezone201 naive fashion.202 """203 def test_string(self):204 self.assert_deprecated(np.datetime64, args=('2000-01-01T00+01',))205 self.assert_deprecated(np.datetime64, args=('2000-01-01T00Z',))206 @pytest.mark.skipif(not _has_pytz,207 reason="The pytz module is not available.")208 def test_datetime(self):209 tz = pytz.timezone('US/Eastern')210 dt = datetime.datetime(2000, 1, 1, 0, 0, tzinfo=tz)211 self.assert_deprecated(np.datetime64, args=(dt,))212class TestNonCContiguousViewDeprecation(_DeprecationTestCase):213 """View of non-C-contiguous arrays deprecated in 1.11.0.214 The deprecation will not be raised for arrays that are both C and F215 contiguous, as C contiguous is dominant. There are more such arrays216 with relaxed stride checking than without so the deprecation is not217 as visible with relaxed stride checking in force.218 """219 def test_fortran_contiguous(self):220 self.assert_deprecated(np.ones((2,2)).T.view, args=(complex,))221 self.assert_deprecated(np.ones((2,2)).T.view, args=(np.int8,))222class TestArrayDataAttributeAssignmentDeprecation(_DeprecationTestCase):223 """Assigning the 'data' attribute of an ndarray is unsafe as pointed224 out in gh-7093. Eventually, such assignment should NOT be allowed, but225 in the interests of maintaining backwards compatibility, only a Deprecation-226 Warning will be raised instead for the time being to give developers time to227 refactor relevant code.228 """229 def test_data_attr_assignment(self):230 a = np.arange(10)231 b = np.linspace(0, 1, 10)232 self.message = ("Assigning the 'data' attribute is an "233 "inherently unsafe operation and will "234 "be removed in the future.")235 self.assert_deprecated(a.__setattr__, args=('data', b.data))236class TestBinaryReprInsufficientWidthParameterForRepresentation(_DeprecationTestCase):237 """238 If a 'width' parameter is passed into ``binary_repr`` that is insufficient to239 represent the number in base 2 (positive) or 2's complement (negative) form,240 the function used to silently ignore the parameter and return a representation241 using the minimal number of bits needed for the form in question. Such behavior242 is now considered unsafe from a user perspective and will raise an error in the future.243 """244 def test_insufficient_width_positive(self):245 args = (10,)246 kwargs = {'width': 2}247 self.message = ("Insufficient bit width provided. This behavior "248 "will raise an error in the future.")249 self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)250 def test_insufficient_width_negative(self):251 args = (-5,)252 kwargs = {'width': 2}253 self.message = ("Insufficient bit width provided. This behavior "254 "will raise an error in the future.")255 self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)256class TestNumericStyleTypecodes(_DeprecationTestCase):257 """258 Most numeric style typecodes were previously deprecated (and removed)259 in 1.20. This also deprecates the remaining ones.260 """261 # 2020-06-09, NumPy 1.20262 def test_all_dtypes(self):263 deprecated_types = ['Bytes0', 'Datetime64', 'Str0']264 # Depending on intp size, either Uint32 or Uint64 is defined:265 deprecated_types.append(f"U{np.dtype(np.intp).name}")266 for dt in deprecated_types:267 self.assert_deprecated(np.dtype, exceptions=(TypeError,),268 args=(dt,))269class TestTestDeprecated:270 def test_assert_deprecated(self):271 test_case_instance = _DeprecationTestCase()272 test_case_instance.setup()273 assert_raises(AssertionError,274 test_case_instance.assert_deprecated,275 lambda: None)276 def foo():277 warnings.warn("foo", category=DeprecationWarning, stacklevel=2)278 test_case_instance.assert_deprecated(foo)279 test_case_instance.teardown()280class TestNonNumericConjugate(_DeprecationTestCase):281 """282 Deprecate no-op behavior of ndarray.conjugate on non-numeric dtypes,283 which conflicts with the error behavior of np.conjugate.284 """285 def test_conjugate(self):286 for a in np.array(5), np.array(5j):287 self.assert_not_deprecated(a.conjugate)288 for a in (np.array('s'), np.array('2016', 'M'),289 np.array((1, 2), [('a', int), ('b', int)])):290 self.assert_deprecated(a.conjugate)291class TestNPY_CHAR(_DeprecationTestCase):292 # 2017-05-03, 1.13.0293 def test_npy_char_deprecation(self):294 from numpy.core._multiarray_tests import npy_char_deprecation295 self.assert_deprecated(npy_char_deprecation)296 assert_(npy_char_deprecation() == 'S1')297class TestPyArray_AS1D(_DeprecationTestCase):298 def test_npy_pyarrayas1d_deprecation(self):299 from numpy.core._multiarray_tests import npy_pyarrayas1d_deprecation300 assert_raises(NotImplementedError, npy_pyarrayas1d_deprecation)301class TestPyArray_AS2D(_DeprecationTestCase):302 def test_npy_pyarrayas2d_deprecation(self):303 from numpy.core._multiarray_tests import npy_pyarrayas2d_deprecation304 assert_raises(NotImplementedError, npy_pyarrayas2d_deprecation)305class Test_UPDATEIFCOPY(_DeprecationTestCase):306 """307 v1.14 deprecates creating an array with the UPDATEIFCOPY flag, use308 WRITEBACKIFCOPY instead309 """310 def test_npy_updateifcopy_deprecation(self):311 from numpy.core._multiarray_tests import npy_updateifcopy_deprecation312 arr = np.arange(9).reshape(3, 3)313 v = arr.T314 self.assert_deprecated(npy_updateifcopy_deprecation, args=(v,))315class TestDatetimeEvent(_DeprecationTestCase):316 # 2017-08-11, 1.14.0317 def test_3_tuple(self):318 for cls in (np.datetime64, np.timedelta64):319 # two valid uses - (unit, num) and (unit, num, den, None)320 self.assert_not_deprecated(cls, args=(1, ('ms', 2)))321 self.assert_not_deprecated(cls, args=(1, ('ms', 2, 1, None)))322 # trying to use the event argument, removed in 1.7.0, is deprecated323 # it used to be a uint8324 self.assert_deprecated(cls, args=(1, ('ms', 2, 'event')))325 self.assert_deprecated(cls, args=(1, ('ms', 2, 63)))326 self.assert_deprecated(cls, args=(1, ('ms', 2, 1, 'event')))327 self.assert_deprecated(cls, args=(1, ('ms', 2, 1, 63)))328class TestTruthTestingEmptyArrays(_DeprecationTestCase):329 # 2017-09-25, 1.14.0330 message = '.*truth value of an empty array is ambiguous.*'331 def test_1d(self):332 self.assert_deprecated(bool, args=(np.array([]),))333 def test_2d(self):334 self.assert_deprecated(bool, args=(np.zeros((1, 0)),))335 self.assert_deprecated(bool, args=(np.zeros((0, 1)),))336 self.assert_deprecated(bool, args=(np.zeros((0, 0)),))337class TestBincount(_DeprecationTestCase):338 # 2017-06-01, 1.14.0339 def test_bincount_minlength(self):340 self.assert_deprecated(lambda: np.bincount([1, 2, 3], minlength=None))341class TestAlen(_DeprecationTestCase):342 # 2019-08-02, 1.18.0343 def test_alen(self):344 self.assert_deprecated(lambda: np.alen(np.array([1, 2, 3])))345class TestGeneratorSum(_DeprecationTestCase):346 # 2018-02-25, 1.15.0347 def test_generator_sum(self):348 self.assert_deprecated(np.sum, args=((i for i in range(5)),))349class TestPositiveOnNonNumerical(_DeprecationTestCase):350 # 2018-06-28, 1.16.0351 def test_positive_on_non_number(self):352 self.assert_deprecated(operator.pos, args=(np.array('foo'),))353class TestFromstring(_DeprecationTestCase):354 # 2017-10-19, 1.14355 def test_fromstring(self):356 self.assert_deprecated(np.fromstring, args=('\x00'*80,))357class TestFromStringAndFileInvalidData(_DeprecationTestCase):358 # 2019-06-08, 1.17.0359 # Tests should be moved to real tests when deprecation is done.360 message = "string or file could not be read to its end"361 @pytest.mark.parametrize("invalid_str", [",invalid_data", "invalid_sep"])362 def test_deprecate_unparsable_data_file(self, invalid_str):363 x = np.array([1.51, 2, 3.51, 4], dtype=float)364 with tempfile.TemporaryFile(mode="w") as f:365 x.tofile(f, sep=',', format='%.2f')366 f.write(invalid_str)367 f.seek(0)368 self.assert_deprecated(lambda: np.fromfile(f, sep=","))369 f.seek(0)370 self.assert_deprecated(lambda: np.fromfile(f, sep=",", count=5))371 # Should not raise:372 with warnings.catch_warnings():373 warnings.simplefilter("error", DeprecationWarning)374 f.seek(0)375 res = np.fromfile(f, sep=",", count=4)376 assert_array_equal(res, x)377 @pytest.mark.parametrize("invalid_str", [",invalid_data", "invalid_sep"])378 def test_deprecate_unparsable_string(self, invalid_str):379 x = np.array([1.51, 2, 3.51, 4], dtype=float)380 x_str = "1.51,2,3.51,4{}".format(invalid_str)381 self.assert_deprecated(lambda: np.fromstring(x_str, sep=","))382 self.assert_deprecated(lambda: np.fromstring(x_str, sep=",", count=5))383 # The C-level API can use not fixed size, but 0 terminated strings,384 # so test that as well:385 bytestr = x_str.encode("ascii")386 self.assert_deprecated(lambda: fromstring_null_term_c_api(bytestr))387 with assert_warns(DeprecationWarning):388 # this is slightly strange, in that fromstring leaves data389 # potentially uninitialized (would be good to error when all is390 # read, but count is larger then actual data maybe).391 res = np.fromstring(x_str, sep=",", count=5)392 assert_array_equal(res[:-1], x)393 with warnings.catch_warnings():394 warnings.simplefilter("error", DeprecationWarning)395 # Should not raise:396 res = np.fromstring(x_str, sep=",", count=4)397 assert_array_equal(res, x)398class Test_GetSet_NumericOps(_DeprecationTestCase):399 # 2018-09-20, 1.16.0400 def test_get_numeric_ops(self):401 from numpy.core._multiarray_tests import getset_numericops402 self.assert_deprecated(getset_numericops, num=2)403 # empty kwargs prevents any state actually changing which would break404 # other tests.405 self.assert_deprecated(np.set_numeric_ops, kwargs={})406 assert_raises(ValueError, np.set_numeric_ops, add='abc')407class TestShape1Fields(_DeprecationTestCase):408 warning_cls = FutureWarning409 # 2019-05-20, 1.17.0410 def test_shape_1_fields(self):411 self.assert_deprecated(np.dtype, args=([('a', int, 1)],))412class TestNonZero(_DeprecationTestCase):413 # 2019-05-26, 1.17.0414 def test_zerod(self):415 self.assert_deprecated(lambda: np.nonzero(np.array(0)))416 self.assert_deprecated(lambda: np.nonzero(np.array(1)))417def test_deprecate_ragged_arrays():418 # 2019-11-29 1.19.0419 #420 # NEP 34 deprecated automatic object dtype when creating ragged421 # arrays. Also see the "ragged" tests in `test_multiarray`422 #423 # emits a VisibleDeprecationWarning424 arg = [1, [2, 3]]425 with assert_warns(np.VisibleDeprecationWarning):426 np.array(arg)427class TestTooDeepDeprecation(_VisibleDeprecationTestCase):428 # NumPy 1.20, 2020-05-08429 # This is a bit similar to the above ragged array deprecation case.430 message = re.escape("Creating an ndarray from nested sequences exceeding")431 def test_deprecation(self):432 nested = [1]433 for i in range(np.MAXDIMS - 1):434 nested = [nested]435 self.assert_not_deprecated(np.array, args=(nested,))436 self.assert_not_deprecated(np.array,437 args=(nested,), kwargs=dict(dtype=object))438 self.assert_deprecated(np.array, args=([nested],))439class TestToString(_DeprecationTestCase):440 # 2020-03-06 1.19.0441 message = re.escape("tostring() is deprecated. Use tobytes() instead.")442 def test_tostring(self):443 arr = np.array(list(b"test\xFF"), dtype=np.uint8)444 self.assert_deprecated(arr.tostring)445 def test_tostring_matches_tobytes(self):446 arr = np.array(list(b"test\xFF"), dtype=np.uint8)447 b = arr.tobytes()448 with assert_warns(DeprecationWarning):449 s = arr.tostring()450 assert s == b451class TestDTypeCoercion(_DeprecationTestCase):452 # 2020-02-06 1.19.0453 message = "Converting .* to a dtype .*is deprecated"454 deprecated_types = [455 # The builtin scalar super types:456 np.generic, np.flexible, np.number,457 np.inexact, np.floating, np.complexfloating,458 np.integer, np.unsignedinteger, np.signedinteger,459 # character is a deprecated S1 special case:460 np.character,461 ]462 def test_dtype_coercion(self):463 for scalar_type in self.deprecated_types:464 self.assert_deprecated(np.dtype, args=(scalar_type,))465 def test_array_construction(self):466 for scalar_type in self.deprecated_types:467 self.assert_deprecated(np.array, args=([], scalar_type,))468 def test_not_deprecated(self):469 # All specific types are not deprecated:470 for group in np.sctypes.values():471 for scalar_type in group:472 self.assert_not_deprecated(np.dtype, args=(scalar_type,))473 for scalar_type in [type, dict, list, tuple]:474 # Typical python types are coerced to object currently:475 self.assert_not_deprecated(np.dtype, args=(scalar_type,))476class BuiltInRoundComplexDType(_DeprecationTestCase):477 # 2020-03-31 1.19.0478 deprecated_types = [np.csingle, np.cdouble, np.clongdouble]479 not_deprecated_types = [480 np.int8, np.int16, np.int32, np.int64,481 np.uint8, np.uint16, np.uint32, np.uint64,482 np.float16, np.float32, np.float64,483 ]484 def test_deprecated(self):485 for scalar_type in self.deprecated_types:486 scalar = scalar_type(0)487 self.assert_deprecated(round, args=(scalar,))488 self.assert_deprecated(round, args=(scalar, 0))489 self.assert_deprecated(round, args=(scalar,), kwargs={'ndigits': 0})490 def test_not_deprecated(self):491 for scalar_type in self.not_deprecated_types:492 scalar = scalar_type(0)493 self.assert_not_deprecated(round, args=(scalar,))494 self.assert_not_deprecated(round, args=(scalar, 0))495 self.assert_not_deprecated(round, args=(scalar,), kwargs={'ndigits': 0})496class TestIncorrectAdvancedIndexWithEmptyResult(_DeprecationTestCase):497 # 2020-05-27, NumPy 1.20.0498 message = "Out of bound index found. This was previously ignored.*"499 @pytest.mark.parametrize("index", [([3, 0],), ([0, 0], [3, 0])])500 def test_empty_subspace(self, index):501 # Test for both a single and two/multiple advanced indices. These502 # This will raise an IndexError in the future.503 arr = np.ones((2, 2, 0))504 self.assert_deprecated(arr.__getitem__, args=(index,))505 self.assert_deprecated(arr.__setitem__, args=(index, 0.))506 # for this array, the subspace is only empty after applying the slice507 arr2 = np.ones((2, 2, 1))508 index2 = (slice(0, 0),) + index509 self.assert_deprecated(arr2.__getitem__, args=(index2,))510 self.assert_deprecated(arr2.__setitem__, args=(index2, 0.))511 def test_empty_index_broadcast_not_deprecated(self):512 arr = np.ones((2, 2, 2))513 index = ([[3], [2]], []) # broadcast to an empty result.514 self.assert_not_deprecated(arr.__getitem__, args=(index,))515 self.assert_not_deprecated(arr.__setitem__,516 args=(index, np.empty((2, 0, 2))))517class TestNonExactMatchDeprecation(_DeprecationTestCase):518 # 2020-04-22519 def test_non_exact_match(self):520 arr = np.array([[3, 6, 6], [4, 5, 1]])521 # misspelt mode check522 self.assert_deprecated(lambda: np.ravel_multi_index(arr, (7, 6), mode='Cilp'))523 # using completely different word with first character as R524 self.assert_deprecated(lambda: np.searchsorted(arr[0], 4, side='Random'))525class TestDeprecatedGlobals(_DeprecationTestCase):526 # 2020-06-06527 @pytest.mark.skipif(528 sys.version_info < (3, 7),529 reason='module-level __getattr__ not supported')530 def test_type_aliases(self):531 # from builtins532 self.assert_deprecated(lambda: np.bool(True))533 self.assert_deprecated(lambda: np.int(1))534 self.assert_deprecated(lambda: np.float(1))535 self.assert_deprecated(lambda: np.complex(1))536 self.assert_deprecated(lambda: np.object())537 self.assert_deprecated(lambda: np.str('abc'))538 # from np.compat539 self.assert_deprecated(lambda: np.long(1))540 self.assert_deprecated(lambda: np.unicode('abc'))541class TestMatrixInOuter(_DeprecationTestCase):542 # 2020-05-13 NumPy 1.20.0543 message = (r"add.outer\(\) was passed a numpy matrix as "544 r"(first|second) argument.")545 def test_deprecated(self):546 arr = np.array([1, 2, 3])547 m = np.array([1, 2, 3]).view(np.matrix)548 self.assert_deprecated(np.add.outer, args=(m, m), num=2)549 self.assert_deprecated(np.add.outer, args=(arr, m))550 self.assert_deprecated(np.add.outer, args=(m, arr))551 self.assert_not_deprecated(np.add.outer, args=(arr, arr))552class TestRaggedArray(_DeprecationTestCase):553 # 2020-07-24, NumPy 1.20.0554 message = "setting an array element with a sequence"555 def test_deprecated(self):556 arr = np.ones((1, 1))557 # Deprecated if the array is a leave node:558 self.assert_deprecated(lambda: np.array([arr, 0], dtype=np.float64))559 self.assert_deprecated(lambda: np.array([0, arr], dtype=np.float64))560 # And when it is an assignment into a lower dimensional subarray:561 self.assert_deprecated(lambda: np.array([arr, [0]], dtype=np.float64))562 self.assert_deprecated(lambda: np.array([[0], arr], dtype=np.float64))563class FlatteningConcatenateUnsafeCast(_DeprecationTestCase):564 # NumPy 1.20, 2020-09-03565 message = "concatenate with `axis=None` will use same-kind casting"566 def test_deprecated(self):567 self.assert_deprecated(np.concatenate,568 args=(([0.], [1.]),),569 kwargs=dict(axis=None, out=np.empty(2, dtype=np.int64)))570 def test_not_deprecated(self):571 self.assert_not_deprecated(np.concatenate,572 args=(([0.], [1.]),),573 kwargs={'axis': None, 'out': np.empty(2, dtype=np.int64),574 'casting': "unsafe"})575 with assert_raises(TypeError):576 # Tests should notice if the deprecation warning is given first...577 np.concatenate(([0.], [1.]), out=np.empty(2, dtype=np.int64),578 casting="same_kind")579class TestDeprecateSubarrayDTypeDuringArrayCoercion(_DeprecationTestCase):580 warning_cls = FutureWarning581 message = "(creating|casting) an array (with|to) a subarray dtype"582 def test_deprecated_array(self):583 # Arrays are more complex, since they "broadcast" on success:584 arr = np.array([1, 2])585 self.assert_deprecated(lambda: arr.astype("(2)i,"))586 with pytest.warns(FutureWarning):587 res = arr.astype("(2)i,")588 assert_array_equal(res, [[1, 2], [1, 2]])589 self.assert_deprecated(lambda: np.array(arr, dtype="(2)i,"))590 with pytest.warns(FutureWarning):591 res = np.array(arr, dtype="(2)i,")592 assert_array_equal(res, [[1, 2], [1, 2]])593 with pytest.warns(FutureWarning):594 res = np.array([[(1,), (2,)], arr], dtype="(2)i,")595 assert_array_equal(res, [[[1, 1], [2, 2]], [[1, 2], [1, 2]]])596 def test_deprecated_and_error(self):597 # These error paths do not give a warning, but will succeed in the598 # future.599 arr = np.arange(5 * 2).reshape(5, 2)600 def check():601 with pytest.raises(ValueError):602 arr.astype("(2,2)f")603 self.assert_deprecated(check)604 def check():605 with pytest.raises(ValueError):606 np.array(arr, dtype="(2,2)f")607 self.assert_deprecated(check)608class TestFutureWarningArrayLikeNotIterable(_DeprecationTestCase):609 # Deprecated 2020-12-09, NumPy 1.20610 warning_cls = FutureWarning611 message = "The input object of type.*but not a sequence"612 @pytest.mark.parametrize("protocol",613 ["__array__", "__array_interface__", "__array_struct__"])614 def test_deprecated(self, protocol):615 """Test that these objects give a warning since they are not 0-D,616 not coerced at the top level `np.array(obj)`, but nested, and do617 *not* define the sequence protocol.618 NOTE: Tests for the versions including __len__ and __getitem__ exist619 in `test_array_coercion.py` and they can be modified or ammended620 when this deprecation expired.621 """622 blueprint = np.arange(10)623 MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol)})624 self.assert_deprecated(lambda: np.array([MyArr()], dtype=object))625 @pytest.mark.parametrize("protocol",626 ["__array__", "__array_interface__", "__array_struct__"])627 def test_0d_not_deprecated(self, protocol):628 # 0-D always worked (albeit it would use __float__ or similar for the629 # conversion, which may not happen anymore)630 blueprint = np.array(1.)631 MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol)})632 myarr = MyArr()633 self.assert_not_deprecated(lambda: np.array([myarr], dtype=object))634 res = np.array([myarr], dtype=object)635 expected = np.empty(1, dtype=object)636 expected[0] = myarr637 assert_array_equal(res, expected)638 @pytest.mark.parametrize("protocol",639 ["__array__", "__array_interface__", "__array_struct__"])640 def test_unnested_not_deprecated(self, protocol):641 blueprint = np.arange(10)642 MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol)})643 myarr = MyArr()644 self.assert_not_deprecated(lambda: np.array(myarr))645 res = np.array(myarr)646 assert_array_equal(res, blueprint)647 @pytest.mark.parametrize("protocol",648 ["__array__", "__array_interface__", "__array_struct__"])649 def test_strange_dtype_handling(self, protocol):650 """The old code would actually use the dtype from the array, but651 then end up not using the array (for dimension discovery)652 """653 blueprint = np.arange(10).astype("f4")654 MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol),655 "__float__": lambda _: 0.5})656 myarr = MyArr()657 # Make sure we warn (and capture the FutureWarning)658 with pytest.warns(FutureWarning, match=self.message):659 res = np.array([[myarr]])660 assert res.shape == (1, 1)661 assert res.dtype == "f4"662 assert res[0, 0] == 0.5663 @pytest.mark.parametrize("protocol",664 ["__array__", "__array_interface__", "__array_struct__"])665 def test_assignment_not_deprecated(self, protocol):666 # If the result is dtype=object we do not unpack a nested array or667 # array-like, if it is nested at exactly the right depth.668 # NOTE: We actually do still call __array__, etc. but ignore the result669 # in the end. For `dtype=object` we could optimize that away.670 blueprint = np.arange(10).astype("f4")671 MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol),672 "__float__": lambda _: 0.5})673 myarr = MyArr()674 res = np.empty(3, dtype=object)675 def set():676 res[:] = [myarr, myarr, myarr]677 self.assert_not_deprecated(set)678 assert res[0] is myarr679 assert res[1] is myarr680 assert res[2] is myarr681class TestDeprecatedUnpickleObjectScalar(_DeprecationTestCase):682 # Deprecated 2020-11-24, NumPy 1.20683 """684 Technically, it should be impossible to create numpy object scalars,685 but there was an unpickle path that would in theory allow it. That686 path is invalid and must lead to the warning.687 """688 message = "Unpickling a scalar with object dtype is deprecated."689 def test_deprecated(self):690 ctor = np.core.multiarray.scalar...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!