asserters.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  1. from __future__ import annotations
  2. import operator
  3. from typing import (
  4. Literal,
  5. cast,
  6. )
  7. import numpy as np
  8. from pandas._libs.missing import is_matching_na
  9. from pandas._libs.sparse import SparseIndex
  10. import pandas._libs.testing as _testing
  11. from pandas._libs.tslibs.np_datetime import compare_mismatched_resolutions
  12. from pandas.core.dtypes.common import (
  13. is_bool,
  14. is_categorical_dtype,
  15. is_extension_array_dtype,
  16. is_integer_dtype,
  17. is_interval_dtype,
  18. is_number,
  19. is_numeric_dtype,
  20. needs_i8_conversion,
  21. )
  22. from pandas.core.dtypes.dtypes import (
  23. CategoricalDtype,
  24. DatetimeTZDtype,
  25. PandasDtype,
  26. )
  27. from pandas.core.dtypes.missing import array_equivalent
  28. import pandas as pd
  29. from pandas import (
  30. Categorical,
  31. DataFrame,
  32. DatetimeIndex,
  33. Index,
  34. IntervalIndex,
  35. MultiIndex,
  36. PeriodIndex,
  37. RangeIndex,
  38. Series,
  39. TimedeltaIndex,
  40. )
  41. from pandas.core.algorithms import take_nd
  42. from pandas.core.arrays import (
  43. DatetimeArray,
  44. ExtensionArray,
  45. IntervalArray,
  46. PeriodArray,
  47. TimedeltaArray,
  48. )
  49. from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin
  50. from pandas.core.arrays.string_ import StringDtype
  51. from pandas.core.indexes.api import safe_sort_index
  52. from pandas.io.formats.printing import pprint_thing
  53. def assert_almost_equal(
  54. left,
  55. right,
  56. check_dtype: bool | Literal["equiv"] = "equiv",
  57. rtol: float = 1.0e-5,
  58. atol: float = 1.0e-8,
  59. **kwargs,
  60. ) -> None:
  61. """
  62. Check that the left and right objects are approximately equal.
  63. By approximately equal, we refer to objects that are numbers or that
  64. contain numbers which may be equivalent to specific levels of precision.
  65. Parameters
  66. ----------
  67. left : object
  68. right : object
  69. check_dtype : bool or {'equiv'}, default 'equiv'
  70. Check dtype if both a and b are the same type. If 'equiv' is passed in,
  71. then `RangeIndex` and `Index` with int64 dtype are also considered
  72. equivalent when doing type checking.
  73. rtol : float, default 1e-5
  74. Relative tolerance.
  75. .. versionadded:: 1.1.0
  76. atol : float, default 1e-8
  77. Absolute tolerance.
  78. .. versionadded:: 1.1.0
  79. """
  80. if isinstance(left, Index):
  81. assert_index_equal(
  82. left,
  83. right,
  84. check_exact=False,
  85. exact=check_dtype,
  86. rtol=rtol,
  87. atol=atol,
  88. **kwargs,
  89. )
  90. elif isinstance(left, Series):
  91. assert_series_equal(
  92. left,
  93. right,
  94. check_exact=False,
  95. check_dtype=check_dtype,
  96. rtol=rtol,
  97. atol=atol,
  98. **kwargs,
  99. )
  100. elif isinstance(left, DataFrame):
  101. assert_frame_equal(
  102. left,
  103. right,
  104. check_exact=False,
  105. check_dtype=check_dtype,
  106. rtol=rtol,
  107. atol=atol,
  108. **kwargs,
  109. )
  110. else:
  111. # Other sequences.
  112. if check_dtype:
  113. if is_number(left) and is_number(right):
  114. # Do not compare numeric classes, like np.float64 and float.
  115. pass
  116. elif is_bool(left) and is_bool(right):
  117. # Do not compare bool classes, like np.bool_ and bool.
  118. pass
  119. else:
  120. if isinstance(left, np.ndarray) or isinstance(right, np.ndarray):
  121. obj = "numpy array"
  122. else:
  123. obj = "Input"
  124. assert_class_equal(left, right, obj=obj)
  125. # if we have "equiv", this becomes True
  126. _testing.assert_almost_equal(
  127. left, right, check_dtype=bool(check_dtype), rtol=rtol, atol=atol, **kwargs
  128. )
  129. def _check_isinstance(left, right, cls):
  130. """
  131. Helper method for our assert_* methods that ensures that
  132. the two objects being compared have the right type before
  133. proceeding with the comparison.
  134. Parameters
  135. ----------
  136. left : The first object being compared.
  137. right : The second object being compared.
  138. cls : The class type to check against.
  139. Raises
  140. ------
  141. AssertionError : Either `left` or `right` is not an instance of `cls`.
  142. """
  143. cls_name = cls.__name__
  144. if not isinstance(left, cls):
  145. raise AssertionError(
  146. f"{cls_name} Expected type {cls}, found {type(left)} instead"
  147. )
  148. if not isinstance(right, cls):
  149. raise AssertionError(
  150. f"{cls_name} Expected type {cls}, found {type(right)} instead"
  151. )
  152. def assert_dict_equal(left, right, compare_keys: bool = True) -> None:
  153. _check_isinstance(left, right, dict)
  154. _testing.assert_dict_equal(left, right, compare_keys=compare_keys)
  155. def assert_index_equal(
  156. left: Index,
  157. right: Index,
  158. exact: bool | str = "equiv",
  159. check_names: bool = True,
  160. check_exact: bool = True,
  161. check_categorical: bool = True,
  162. check_order: bool = True,
  163. rtol: float = 1.0e-5,
  164. atol: float = 1.0e-8,
  165. obj: str = "Index",
  166. ) -> None:
  167. """
  168. Check that left and right Index are equal.
  169. Parameters
  170. ----------
  171. left : Index
  172. right : Index
  173. exact : bool or {'equiv'}, default 'equiv'
  174. Whether to check the Index class, dtype and inferred_type
  175. are identical. If 'equiv', then RangeIndex can be substituted for
  176. Index with an int64 dtype as well.
  177. check_names : bool, default True
  178. Whether to check the names attribute.
  179. check_exact : bool, default True
  180. Whether to compare number exactly.
  181. check_categorical : bool, default True
  182. Whether to compare internal Categorical exactly.
  183. check_order : bool, default True
  184. Whether to compare the order of index entries as well as their values.
  185. If True, both indexes must contain the same elements, in the same order.
  186. If False, both indexes must contain the same elements, but in any order.
  187. .. versionadded:: 1.2.0
  188. rtol : float, default 1e-5
  189. Relative tolerance. Only used when check_exact is False.
  190. .. versionadded:: 1.1.0
  191. atol : float, default 1e-8
  192. Absolute tolerance. Only used when check_exact is False.
  193. .. versionadded:: 1.1.0
  194. obj : str, default 'Index'
  195. Specify object name being compared, internally used to show appropriate
  196. assertion message.
  197. Examples
  198. --------
  199. >>> from pandas import testing as tm
  200. >>> a = pd.Index([1, 2, 3])
  201. >>> b = pd.Index([1, 2, 3])
  202. >>> tm.assert_index_equal(a, b)
  203. """
  204. __tracebackhide__ = True
  205. def _check_types(left, right, obj: str = "Index") -> None:
  206. if not exact:
  207. return
  208. assert_class_equal(left, right, exact=exact, obj=obj)
  209. assert_attr_equal("inferred_type", left, right, obj=obj)
  210. # Skip exact dtype checking when `check_categorical` is False
  211. if is_categorical_dtype(left.dtype) and is_categorical_dtype(right.dtype):
  212. if check_categorical:
  213. assert_attr_equal("dtype", left, right, obj=obj)
  214. assert_index_equal(left.categories, right.categories, exact=exact)
  215. return
  216. assert_attr_equal("dtype", left, right, obj=obj)
  217. def _get_ilevel_values(index, level):
  218. # accept level number only
  219. unique = index.levels[level]
  220. level_codes = index.codes[level]
  221. filled = take_nd(unique._values, level_codes, fill_value=unique._na_value)
  222. return unique._shallow_copy(filled, name=index.names[level])
  223. # instance validation
  224. _check_isinstance(left, right, Index)
  225. # class / dtype comparison
  226. _check_types(left, right, obj=obj)
  227. # level comparison
  228. if left.nlevels != right.nlevels:
  229. msg1 = f"{obj} levels are different"
  230. msg2 = f"{left.nlevels}, {left}"
  231. msg3 = f"{right.nlevels}, {right}"
  232. raise_assert_detail(obj, msg1, msg2, msg3)
  233. # length comparison
  234. if len(left) != len(right):
  235. msg1 = f"{obj} length are different"
  236. msg2 = f"{len(left)}, {left}"
  237. msg3 = f"{len(right)}, {right}"
  238. raise_assert_detail(obj, msg1, msg2, msg3)
  239. # If order doesn't matter then sort the index entries
  240. if not check_order:
  241. left = safe_sort_index(left)
  242. right = safe_sort_index(right)
  243. # MultiIndex special comparison for little-friendly error messages
  244. if left.nlevels > 1:
  245. left = cast(MultiIndex, left)
  246. right = cast(MultiIndex, right)
  247. for level in range(left.nlevels):
  248. # cannot use get_level_values here because it can change dtype
  249. llevel = _get_ilevel_values(left, level)
  250. rlevel = _get_ilevel_values(right, level)
  251. lobj = f"MultiIndex level [{level}]"
  252. assert_index_equal(
  253. llevel,
  254. rlevel,
  255. exact=exact,
  256. check_names=check_names,
  257. check_exact=check_exact,
  258. rtol=rtol,
  259. atol=atol,
  260. obj=lobj,
  261. )
  262. # get_level_values may change dtype
  263. _check_types(left.levels[level], right.levels[level], obj=obj)
  264. # skip exact index checking when `check_categorical` is False
  265. if check_exact and check_categorical:
  266. if not left.equals(right):
  267. mismatch = left._values != right._values
  268. if is_extension_array_dtype(mismatch):
  269. mismatch = cast("ExtensionArray", mismatch).fillna(True)
  270. diff = np.sum(mismatch.astype(int)) * 100.0 / len(left)
  271. msg = f"{obj} values are different ({np.round(diff, 5)} %)"
  272. raise_assert_detail(obj, msg, left, right)
  273. else:
  274. # if we have "equiv", this becomes True
  275. exact_bool = bool(exact)
  276. _testing.assert_almost_equal(
  277. left.values,
  278. right.values,
  279. rtol=rtol,
  280. atol=atol,
  281. check_dtype=exact_bool,
  282. obj=obj,
  283. lobj=left,
  284. robj=right,
  285. )
  286. # metadata comparison
  287. if check_names:
  288. assert_attr_equal("names", left, right, obj=obj)
  289. if isinstance(left, PeriodIndex) or isinstance(right, PeriodIndex):
  290. assert_attr_equal("freq", left, right, obj=obj)
  291. if isinstance(left, IntervalIndex) or isinstance(right, IntervalIndex):
  292. assert_interval_array_equal(left._values, right._values)
  293. if check_categorical:
  294. if is_categorical_dtype(left.dtype) or is_categorical_dtype(right.dtype):
  295. assert_categorical_equal(left._values, right._values, obj=f"{obj} category")
  296. def assert_class_equal(
  297. left, right, exact: bool | str = True, obj: str = "Input"
  298. ) -> None:
  299. """
  300. Checks classes are equal.
  301. """
  302. __tracebackhide__ = True
  303. def repr_class(x):
  304. if isinstance(x, Index):
  305. # return Index as it is to include values in the error message
  306. return x
  307. return type(x).__name__
  308. def is_class_equiv(idx: Index) -> bool:
  309. """Classes that are a RangeIndex (sub-)instance or exactly an `Index` .
  310. This only checks class equivalence. There is a separate check that the
  311. dtype is int64.
  312. """
  313. return type(idx) is Index or isinstance(idx, RangeIndex)
  314. if type(left) == type(right):
  315. return
  316. if exact == "equiv":
  317. if is_class_equiv(left) and is_class_equiv(right):
  318. return
  319. msg = f"{obj} classes are different"
  320. raise_assert_detail(obj, msg, repr_class(left), repr_class(right))
  321. def assert_attr_equal(attr: str, left, right, obj: str = "Attributes") -> None:
  322. """
  323. Check attributes are equal. Both objects must have attribute.
  324. Parameters
  325. ----------
  326. attr : str
  327. Attribute name being compared.
  328. left : object
  329. right : object
  330. obj : str, default 'Attributes'
  331. Specify object name being compared, internally used to show appropriate
  332. assertion message
  333. """
  334. __tracebackhide__ = True
  335. left_attr = getattr(left, attr)
  336. right_attr = getattr(right, attr)
  337. if left_attr is right_attr or is_matching_na(left_attr, right_attr):
  338. # e.g. both np.nan, both NaT, both pd.NA, ...
  339. return None
  340. try:
  341. result = left_attr == right_attr
  342. except TypeError:
  343. # datetimetz on rhs may raise TypeError
  344. result = False
  345. if (left_attr is pd.NA) ^ (right_attr is pd.NA):
  346. result = False
  347. elif not isinstance(result, bool):
  348. result = result.all()
  349. if not result:
  350. msg = f'Attribute "{attr}" are different'
  351. raise_assert_detail(obj, msg, left_attr, right_attr)
  352. return None
  353. def assert_is_valid_plot_return_object(objs) -> None:
  354. import matplotlib.pyplot as plt
  355. if isinstance(objs, (Series, np.ndarray)):
  356. for el in objs.ravel():
  357. msg = (
  358. "one of 'objs' is not a matplotlib Axes instance, "
  359. f"type encountered {repr(type(el).__name__)}"
  360. )
  361. assert isinstance(el, (plt.Axes, dict)), msg
  362. else:
  363. msg = (
  364. "objs is neither an ndarray of Artist instances nor a single "
  365. "ArtistArtist instance, tuple, or dict, 'objs' is a "
  366. f"{repr(type(objs).__name__)}"
  367. )
  368. assert isinstance(objs, (plt.Artist, tuple, dict)), msg
  369. def assert_is_sorted(seq) -> None:
  370. """Assert that the sequence is sorted."""
  371. if isinstance(seq, (Index, Series)):
  372. seq = seq.values
  373. # sorting does not change precisions
  374. assert_numpy_array_equal(seq, np.sort(np.array(seq)))
  375. def assert_categorical_equal(
  376. left,
  377. right,
  378. check_dtype: bool = True,
  379. check_category_order: bool = True,
  380. obj: str = "Categorical",
  381. ) -> None:
  382. """
  383. Test that Categoricals are equivalent.
  384. Parameters
  385. ----------
  386. left : Categorical
  387. right : Categorical
  388. check_dtype : bool, default True
  389. Check that integer dtype of the codes are the same.
  390. check_category_order : bool, default True
  391. Whether the order of the categories should be compared, which
  392. implies identical integer codes. If False, only the resulting
  393. values are compared. The ordered attribute is
  394. checked regardless.
  395. obj : str, default 'Categorical'
  396. Specify object name being compared, internally used to show appropriate
  397. assertion message.
  398. """
  399. _check_isinstance(left, right, Categorical)
  400. exact: bool | str
  401. if isinstance(left.categories, RangeIndex) or isinstance(
  402. right.categories, RangeIndex
  403. ):
  404. exact = "equiv"
  405. else:
  406. # We still want to require exact matches for Index
  407. exact = True
  408. if check_category_order:
  409. assert_index_equal(
  410. left.categories, right.categories, obj=f"{obj}.categories", exact=exact
  411. )
  412. assert_numpy_array_equal(
  413. left.codes, right.codes, check_dtype=check_dtype, obj=f"{obj}.codes"
  414. )
  415. else:
  416. try:
  417. lc = left.categories.sort_values()
  418. rc = right.categories.sort_values()
  419. except TypeError:
  420. # e.g. '<' not supported between instances of 'int' and 'str'
  421. lc, rc = left.categories, right.categories
  422. assert_index_equal(lc, rc, obj=f"{obj}.categories", exact=exact)
  423. assert_index_equal(
  424. left.categories.take(left.codes),
  425. right.categories.take(right.codes),
  426. obj=f"{obj}.values",
  427. exact=exact,
  428. )
  429. assert_attr_equal("ordered", left, right, obj=obj)
  430. def assert_interval_array_equal(
  431. left, right, exact: bool | Literal["equiv"] = "equiv", obj: str = "IntervalArray"
  432. ) -> None:
  433. """
  434. Test that two IntervalArrays are equivalent.
  435. Parameters
  436. ----------
  437. left, right : IntervalArray
  438. The IntervalArrays to compare.
  439. exact : bool or {'equiv'}, default 'equiv'
  440. Whether to check the Index class, dtype and inferred_type
  441. are identical. If 'equiv', then RangeIndex can be substituted for
  442. Index with an int64 dtype as well.
  443. obj : str, default 'IntervalArray'
  444. Specify object name being compared, internally used to show appropriate
  445. assertion message
  446. """
  447. _check_isinstance(left, right, IntervalArray)
  448. kwargs = {}
  449. if left._left.dtype.kind in ["m", "M"]:
  450. # We have a DatetimeArray or TimedeltaArray
  451. kwargs["check_freq"] = False
  452. assert_equal(left._left, right._left, obj=f"{obj}.left", **kwargs)
  453. assert_equal(left._right, right._right, obj=f"{obj}.left", **kwargs)
  454. assert_attr_equal("closed", left, right, obj=obj)
  455. def assert_period_array_equal(left, right, obj: str = "PeriodArray") -> None:
  456. _check_isinstance(left, right, PeriodArray)
  457. assert_numpy_array_equal(left._ndarray, right._ndarray, obj=f"{obj}._ndarray")
  458. assert_attr_equal("freq", left, right, obj=obj)
  459. def assert_datetime_array_equal(
  460. left, right, obj: str = "DatetimeArray", check_freq: bool = True
  461. ) -> None:
  462. __tracebackhide__ = True
  463. _check_isinstance(left, right, DatetimeArray)
  464. assert_numpy_array_equal(left._ndarray, right._ndarray, obj=f"{obj}._ndarray")
  465. if check_freq:
  466. assert_attr_equal("freq", left, right, obj=obj)
  467. assert_attr_equal("tz", left, right, obj=obj)
  468. def assert_timedelta_array_equal(
  469. left, right, obj: str = "TimedeltaArray", check_freq: bool = True
  470. ) -> None:
  471. __tracebackhide__ = True
  472. _check_isinstance(left, right, TimedeltaArray)
  473. assert_numpy_array_equal(left._ndarray, right._ndarray, obj=f"{obj}._ndarray")
  474. if check_freq:
  475. assert_attr_equal("freq", left, right, obj=obj)
  476. def raise_assert_detail(
  477. obj, message, left, right, diff=None, first_diff=None, index_values=None
  478. ):
  479. __tracebackhide__ = True
  480. msg = f"""{obj} are different
  481. {message}"""
  482. if isinstance(index_values, np.ndarray):
  483. msg += f"\n[index]: {pprint_thing(index_values)}"
  484. if isinstance(left, np.ndarray):
  485. left = pprint_thing(left)
  486. elif isinstance(left, (CategoricalDtype, PandasDtype, StringDtype)):
  487. left = repr(left)
  488. if isinstance(right, np.ndarray):
  489. right = pprint_thing(right)
  490. elif isinstance(right, (CategoricalDtype, PandasDtype, StringDtype)):
  491. right = repr(right)
  492. msg += f"""
  493. [left]: {left}
  494. [right]: {right}"""
  495. if diff is not None:
  496. msg += f"\n[diff]: {diff}"
  497. if first_diff is not None:
  498. msg += f"\n{first_diff}"
  499. raise AssertionError(msg)
  500. def assert_numpy_array_equal(
  501. left,
  502. right,
  503. strict_nan: bool = False,
  504. check_dtype: bool | Literal["equiv"] = True,
  505. err_msg=None,
  506. check_same=None,
  507. obj: str = "numpy array",
  508. index_values=None,
  509. ) -> None:
  510. """
  511. Check that 'np.ndarray' is equivalent.
  512. Parameters
  513. ----------
  514. left, right : numpy.ndarray or iterable
  515. The two arrays to be compared.
  516. strict_nan : bool, default False
  517. If True, consider NaN and None to be different.
  518. check_dtype : bool, default True
  519. Check dtype if both a and b are np.ndarray.
  520. err_msg : str, default None
  521. If provided, used as assertion message.
  522. check_same : None|'copy'|'same', default None
  523. Ensure left and right refer/do not refer to the same memory area.
  524. obj : str, default 'numpy array'
  525. Specify object name being compared, internally used to show appropriate
  526. assertion message.
  527. index_values : numpy.ndarray, default None
  528. optional index (shared by both left and right), used in output.
  529. """
  530. __tracebackhide__ = True
  531. # instance validation
  532. # Show a detailed error message when classes are different
  533. assert_class_equal(left, right, obj=obj)
  534. # both classes must be an np.ndarray
  535. _check_isinstance(left, right, np.ndarray)
  536. def _get_base(obj):
  537. return obj.base if getattr(obj, "base", None) is not None else obj
  538. left_base = _get_base(left)
  539. right_base = _get_base(right)
  540. if check_same == "same":
  541. if left_base is not right_base:
  542. raise AssertionError(f"{repr(left_base)} is not {repr(right_base)}")
  543. elif check_same == "copy":
  544. if left_base is right_base:
  545. raise AssertionError(f"{repr(left_base)} is {repr(right_base)}")
  546. def _raise(left, right, err_msg):
  547. if err_msg is None:
  548. if left.shape != right.shape:
  549. raise_assert_detail(
  550. obj, f"{obj} shapes are different", left.shape, right.shape
  551. )
  552. diff = 0
  553. for left_arr, right_arr in zip(left, right):
  554. # count up differences
  555. if not array_equivalent(left_arr, right_arr, strict_nan=strict_nan):
  556. diff += 1
  557. diff = diff * 100.0 / left.size
  558. msg = f"{obj} values are different ({np.round(diff, 5)} %)"
  559. raise_assert_detail(obj, msg, left, right, index_values=index_values)
  560. raise AssertionError(err_msg)
  561. # compare shape and values
  562. if not array_equivalent(left, right, strict_nan=strict_nan):
  563. _raise(left, right, err_msg)
  564. if check_dtype:
  565. if isinstance(left, np.ndarray) and isinstance(right, np.ndarray):
  566. assert_attr_equal("dtype", left, right, obj=obj)
  567. def assert_extension_array_equal(
  568. left,
  569. right,
  570. check_dtype: bool | Literal["equiv"] = True,
  571. index_values=None,
  572. check_exact: bool = False,
  573. rtol: float = 1.0e-5,
  574. atol: float = 1.0e-8,
  575. obj: str = "ExtensionArray",
  576. ) -> None:
  577. """
  578. Check that left and right ExtensionArrays are equal.
  579. Parameters
  580. ----------
  581. left, right : ExtensionArray
  582. The two arrays to compare.
  583. check_dtype : bool, default True
  584. Whether to check if the ExtensionArray dtypes are identical.
  585. index_values : numpy.ndarray, default None
  586. Optional index (shared by both left and right), used in output.
  587. check_exact : bool, default False
  588. Whether to compare number exactly.
  589. rtol : float, default 1e-5
  590. Relative tolerance. Only used when check_exact is False.
  591. .. versionadded:: 1.1.0
  592. atol : float, default 1e-8
  593. Absolute tolerance. Only used when check_exact is False.
  594. .. versionadded:: 1.1.0
  595. obj : str, default 'ExtensionArray'
  596. Specify object name being compared, internally used to show appropriate
  597. assertion message.
  598. .. versionadded:: 2.0.0
  599. Notes
  600. -----
  601. Missing values are checked separately from valid values.
  602. A mask of missing values is computed for each and checked to match.
  603. The remaining all-valid values are cast to object dtype and checked.
  604. Examples
  605. --------
  606. >>> from pandas import testing as tm
  607. >>> a = pd.Series([1, 2, 3, 4])
  608. >>> b, c = a.array, a.array
  609. >>> tm.assert_extension_array_equal(b, c)
  610. """
  611. assert isinstance(left, ExtensionArray), "left is not an ExtensionArray"
  612. assert isinstance(right, ExtensionArray), "right is not an ExtensionArray"
  613. if check_dtype:
  614. assert_attr_equal("dtype", left, right, obj=f"Attributes of {obj}")
  615. if (
  616. isinstance(left, DatetimeLikeArrayMixin)
  617. and isinstance(right, DatetimeLikeArrayMixin)
  618. and type(right) == type(left)
  619. ):
  620. # GH 52449
  621. if not check_dtype and left.dtype.kind in "mM":
  622. if not isinstance(left.dtype, np.dtype):
  623. l_unit = cast(DatetimeTZDtype, left.dtype).unit
  624. else:
  625. l_unit = np.datetime_data(left.dtype)[0]
  626. if not isinstance(right.dtype, np.dtype):
  627. r_unit = cast(DatetimeTZDtype, left.dtype).unit
  628. else:
  629. r_unit = np.datetime_data(right.dtype)[0]
  630. if (
  631. l_unit != r_unit
  632. and compare_mismatched_resolutions(
  633. left._ndarray, right._ndarray, operator.eq
  634. ).all()
  635. ):
  636. return
  637. # Avoid slow object-dtype comparisons
  638. # np.asarray for case where we have a np.MaskedArray
  639. assert_numpy_array_equal(
  640. np.asarray(left.asi8),
  641. np.asarray(right.asi8),
  642. index_values=index_values,
  643. obj=obj,
  644. )
  645. return
  646. left_na = np.asarray(left.isna())
  647. right_na = np.asarray(right.isna())
  648. assert_numpy_array_equal(
  649. left_na, right_na, obj=f"{obj} NA mask", index_values=index_values
  650. )
  651. left_valid = left[~left_na].to_numpy(dtype=object)
  652. right_valid = right[~right_na].to_numpy(dtype=object)
  653. if check_exact:
  654. assert_numpy_array_equal(
  655. left_valid, right_valid, obj=obj, index_values=index_values
  656. )
  657. else:
  658. _testing.assert_almost_equal(
  659. left_valid,
  660. right_valid,
  661. check_dtype=bool(check_dtype),
  662. rtol=rtol,
  663. atol=atol,
  664. obj=obj,
  665. index_values=index_values,
  666. )
  667. # This could be refactored to use the NDFrame.equals method
  668. def assert_series_equal(
  669. left,
  670. right,
  671. check_dtype: bool | Literal["equiv"] = True,
  672. check_index_type: bool | Literal["equiv"] = "equiv",
  673. check_series_type: bool = True,
  674. check_names: bool = True,
  675. check_exact: bool = False,
  676. check_datetimelike_compat: bool = False,
  677. check_categorical: bool = True,
  678. check_category_order: bool = True,
  679. check_freq: bool = True,
  680. check_flags: bool = True,
  681. rtol: float = 1.0e-5,
  682. atol: float = 1.0e-8,
  683. obj: str = "Series",
  684. *,
  685. check_index: bool = True,
  686. check_like: bool = False,
  687. ) -> None:
  688. """
  689. Check that left and right Series are equal.
  690. Parameters
  691. ----------
  692. left : Series
  693. right : Series
  694. check_dtype : bool, default True
  695. Whether to check the Series dtype is identical.
  696. check_index_type : bool or {'equiv'}, default 'equiv'
  697. Whether to check the Index class, dtype and inferred_type
  698. are identical.
  699. check_series_type : bool, default True
  700. Whether to check the Series class is identical.
  701. check_names : bool, default True
  702. Whether to check the Series and Index names attribute.
  703. check_exact : bool, default False
  704. Whether to compare number exactly.
  705. check_datetimelike_compat : bool, default False
  706. Compare datetime-like which is comparable ignoring dtype.
  707. check_categorical : bool, default True
  708. Whether to compare internal Categorical exactly.
  709. check_category_order : bool, default True
  710. Whether to compare category order of internal Categoricals.
  711. .. versionadded:: 1.0.2
  712. check_freq : bool, default True
  713. Whether to check the `freq` attribute on a DatetimeIndex or TimedeltaIndex.
  714. .. versionadded:: 1.1.0
  715. check_flags : bool, default True
  716. Whether to check the `flags` attribute.
  717. .. versionadded:: 1.2.0
  718. rtol : float, default 1e-5
  719. Relative tolerance. Only used when check_exact is False.
  720. .. versionadded:: 1.1.0
  721. atol : float, default 1e-8
  722. Absolute tolerance. Only used when check_exact is False.
  723. .. versionadded:: 1.1.0
  724. obj : str, default 'Series'
  725. Specify object name being compared, internally used to show appropriate
  726. assertion message.
  727. check_index : bool, default True
  728. Whether to check index equivalence. If False, then compare only values.
  729. .. versionadded:: 1.3.0
  730. check_like : bool, default False
  731. If True, ignore the order of the index. Must be False if check_index is False.
  732. Note: same labels must be with the same data.
  733. .. versionadded:: 1.5.0
  734. Examples
  735. --------
  736. >>> from pandas import testing as tm
  737. >>> a = pd.Series([1, 2, 3, 4])
  738. >>> b = pd.Series([1, 2, 3, 4])
  739. >>> tm.assert_series_equal(a, b)
  740. """
  741. __tracebackhide__ = True
  742. if not check_index and check_like:
  743. raise ValueError("check_like must be False if check_index is False")
  744. # instance validation
  745. _check_isinstance(left, right, Series)
  746. if check_series_type:
  747. assert_class_equal(left, right, obj=obj)
  748. # length comparison
  749. if len(left) != len(right):
  750. msg1 = f"{len(left)}, {left.index}"
  751. msg2 = f"{len(right)}, {right.index}"
  752. raise_assert_detail(obj, "Series length are different", msg1, msg2)
  753. if check_flags:
  754. assert left.flags == right.flags, f"{repr(left.flags)} != {repr(right.flags)}"
  755. if check_index:
  756. # GH #38183
  757. assert_index_equal(
  758. left.index,
  759. right.index,
  760. exact=check_index_type,
  761. check_names=check_names,
  762. check_exact=check_exact,
  763. check_categorical=check_categorical,
  764. check_order=not check_like,
  765. rtol=rtol,
  766. atol=atol,
  767. obj=f"{obj}.index",
  768. )
  769. if check_like:
  770. left = left.reindex_like(right)
  771. if check_freq and isinstance(left.index, (DatetimeIndex, TimedeltaIndex)):
  772. lidx = left.index
  773. ridx = right.index
  774. assert lidx.freq == ridx.freq, (lidx.freq, ridx.freq)
  775. if check_dtype:
  776. # We want to skip exact dtype checking when `check_categorical`
  777. # is False. We'll still raise if only one is a `Categorical`,
  778. # regardless of `check_categorical`
  779. if (
  780. isinstance(left.dtype, CategoricalDtype)
  781. and isinstance(right.dtype, CategoricalDtype)
  782. and not check_categorical
  783. ):
  784. pass
  785. else:
  786. assert_attr_equal("dtype", left, right, obj=f"Attributes of {obj}")
  787. if check_exact and is_numeric_dtype(left.dtype) and is_numeric_dtype(right.dtype):
  788. left_values = left._values
  789. right_values = right._values
  790. # Only check exact if dtype is numeric
  791. if isinstance(left_values, ExtensionArray) and isinstance(
  792. right_values, ExtensionArray
  793. ):
  794. assert_extension_array_equal(
  795. left_values,
  796. right_values,
  797. check_dtype=check_dtype,
  798. index_values=np.asarray(left.index),
  799. obj=str(obj),
  800. )
  801. else:
  802. assert_numpy_array_equal(
  803. left_values,
  804. right_values,
  805. check_dtype=check_dtype,
  806. obj=str(obj),
  807. index_values=np.asarray(left.index),
  808. )
  809. elif check_datetimelike_compat and (
  810. needs_i8_conversion(left.dtype) or needs_i8_conversion(right.dtype)
  811. ):
  812. # we want to check only if we have compat dtypes
  813. # e.g. integer and M|m are NOT compat, but we can simply check
  814. # the values in that case
  815. # datetimelike may have different objects (e.g. datetime.datetime
  816. # vs Timestamp) but will compare equal
  817. if not Index(left._values).equals(Index(right._values)):
  818. msg = (
  819. f"[datetimelike_compat=True] {left._values} "
  820. f"is not equal to {right._values}."
  821. )
  822. raise AssertionError(msg)
  823. elif is_interval_dtype(left.dtype) and is_interval_dtype(right.dtype):
  824. assert_interval_array_equal(left.array, right.array)
  825. elif isinstance(left.dtype, CategoricalDtype) or isinstance(
  826. right.dtype, CategoricalDtype
  827. ):
  828. _testing.assert_almost_equal(
  829. left._values,
  830. right._values,
  831. rtol=rtol,
  832. atol=atol,
  833. check_dtype=bool(check_dtype),
  834. obj=str(obj),
  835. index_values=np.asarray(left.index),
  836. )
  837. elif is_extension_array_dtype(left.dtype) and is_extension_array_dtype(right.dtype):
  838. assert_extension_array_equal(
  839. left._values,
  840. right._values,
  841. rtol=rtol,
  842. atol=atol,
  843. check_dtype=check_dtype,
  844. index_values=np.asarray(left.index),
  845. obj=str(obj),
  846. )
  847. elif is_extension_array_dtype_and_needs_i8_conversion(
  848. left.dtype, right.dtype
  849. ) or is_extension_array_dtype_and_needs_i8_conversion(right.dtype, left.dtype):
  850. assert_extension_array_equal(
  851. left._values,
  852. right._values,
  853. check_dtype=check_dtype,
  854. index_values=np.asarray(left.index),
  855. obj=str(obj),
  856. )
  857. elif needs_i8_conversion(left.dtype) and needs_i8_conversion(right.dtype):
  858. # DatetimeArray or TimedeltaArray
  859. assert_extension_array_equal(
  860. left._values,
  861. right._values,
  862. check_dtype=check_dtype,
  863. index_values=np.asarray(left.index),
  864. obj=str(obj),
  865. )
  866. else:
  867. _testing.assert_almost_equal(
  868. left._values,
  869. right._values,
  870. rtol=rtol,
  871. atol=atol,
  872. check_dtype=bool(check_dtype),
  873. obj=str(obj),
  874. index_values=np.asarray(left.index),
  875. )
  876. # metadata comparison
  877. if check_names:
  878. assert_attr_equal("name", left, right, obj=obj)
  879. if check_categorical:
  880. if isinstance(left.dtype, CategoricalDtype) or isinstance(
  881. right.dtype, CategoricalDtype
  882. ):
  883. assert_categorical_equal(
  884. left._values,
  885. right._values,
  886. obj=f"{obj} category",
  887. check_category_order=check_category_order,
  888. )
  889. # This could be refactored to use the NDFrame.equals method
  890. def assert_frame_equal(
  891. left,
  892. right,
  893. check_dtype: bool | Literal["equiv"] = True,
  894. check_index_type: bool | Literal["equiv"] = "equiv",
  895. check_column_type: bool | Literal["equiv"] = "equiv",
  896. check_frame_type: bool = True,
  897. check_names: bool = True,
  898. by_blocks: bool = False,
  899. check_exact: bool = False,
  900. check_datetimelike_compat: bool = False,
  901. check_categorical: bool = True,
  902. check_like: bool = False,
  903. check_freq: bool = True,
  904. check_flags: bool = True,
  905. rtol: float = 1.0e-5,
  906. atol: float = 1.0e-8,
  907. obj: str = "DataFrame",
  908. ) -> None:
  909. """
  910. Check that left and right DataFrame are equal.
  911. This function is intended to compare two DataFrames and output any
  912. differences. It is mostly intended for use in unit tests.
  913. Additional parameters allow varying the strictness of the
  914. equality checks performed.
  915. Parameters
  916. ----------
  917. left : DataFrame
  918. First DataFrame to compare.
  919. right : DataFrame
  920. Second DataFrame to compare.
  921. check_dtype : bool, default True
  922. Whether to check the DataFrame dtype is identical.
  923. check_index_type : bool or {'equiv'}, default 'equiv'
  924. Whether to check the Index class, dtype and inferred_type
  925. are identical.
  926. check_column_type : bool or {'equiv'}, default 'equiv'
  927. Whether to check the columns class, dtype and inferred_type
  928. are identical. Is passed as the ``exact`` argument of
  929. :func:`assert_index_equal`.
  930. check_frame_type : bool, default True
  931. Whether to check the DataFrame class is identical.
  932. check_names : bool, default True
  933. Whether to check that the `names` attribute for both the `index`
  934. and `column` attributes of the DataFrame is identical.
  935. by_blocks : bool, default False
  936. Specify how to compare internal data. If False, compare by columns.
  937. If True, compare by blocks.
  938. check_exact : bool, default False
  939. Whether to compare number exactly.
  940. check_datetimelike_compat : bool, default False
  941. Compare datetime-like which is comparable ignoring dtype.
  942. check_categorical : bool, default True
  943. Whether to compare internal Categorical exactly.
  944. check_like : bool, default False
  945. If True, ignore the order of index & columns.
  946. Note: index labels must match their respective rows
  947. (same as in columns) - same labels must be with the same data.
  948. check_freq : bool, default True
  949. Whether to check the `freq` attribute on a DatetimeIndex or TimedeltaIndex.
  950. .. versionadded:: 1.1.0
  951. check_flags : bool, default True
  952. Whether to check the `flags` attribute.
  953. rtol : float, default 1e-5
  954. Relative tolerance. Only used when check_exact is False.
  955. .. versionadded:: 1.1.0
  956. atol : float, default 1e-8
  957. Absolute tolerance. Only used when check_exact is False.
  958. .. versionadded:: 1.1.0
  959. obj : str, default 'DataFrame'
  960. Specify object name being compared, internally used to show appropriate
  961. assertion message.
  962. See Also
  963. --------
  964. assert_series_equal : Equivalent method for asserting Series equality.
  965. DataFrame.equals : Check DataFrame equality.
  966. Examples
  967. --------
  968. This example shows comparing two DataFrames that are equal
  969. but with columns of differing dtypes.
  970. >>> from pandas.testing import assert_frame_equal
  971. >>> df1 = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
  972. >>> df2 = pd.DataFrame({'a': [1, 2], 'b': [3.0, 4.0]})
  973. df1 equals itself.
  974. >>> assert_frame_equal(df1, df1)
  975. df1 differs from df2 as column 'b' is of a different type.
  976. >>> assert_frame_equal(df1, df2)
  977. Traceback (most recent call last):
  978. ...
  979. AssertionError: Attributes of DataFrame.iloc[:, 1] (column name="b") are different
  980. Attribute "dtype" are different
  981. [left]: int64
  982. [right]: float64
  983. Ignore differing dtypes in columns with check_dtype.
  984. >>> assert_frame_equal(df1, df2, check_dtype=False)
  985. """
  986. __tracebackhide__ = True
  987. # instance validation
  988. _check_isinstance(left, right, DataFrame)
  989. if check_frame_type:
  990. assert isinstance(left, type(right))
  991. # assert_class_equal(left, right, obj=obj)
  992. # shape comparison
  993. if left.shape != right.shape:
  994. raise_assert_detail(
  995. obj, f"{obj} shape mismatch", f"{repr(left.shape)}", f"{repr(right.shape)}"
  996. )
  997. if check_flags:
  998. assert left.flags == right.flags, f"{repr(left.flags)} != {repr(right.flags)}"
  999. # index comparison
  1000. assert_index_equal(
  1001. left.index,
  1002. right.index,
  1003. exact=check_index_type,
  1004. check_names=check_names,
  1005. check_exact=check_exact,
  1006. check_categorical=check_categorical,
  1007. check_order=not check_like,
  1008. rtol=rtol,
  1009. atol=atol,
  1010. obj=f"{obj}.index",
  1011. )
  1012. # column comparison
  1013. assert_index_equal(
  1014. left.columns,
  1015. right.columns,
  1016. exact=check_column_type,
  1017. check_names=check_names,
  1018. check_exact=check_exact,
  1019. check_categorical=check_categorical,
  1020. check_order=not check_like,
  1021. rtol=rtol,
  1022. atol=atol,
  1023. obj=f"{obj}.columns",
  1024. )
  1025. if check_like:
  1026. left = left.reindex_like(right)
  1027. # compare by blocks
  1028. if by_blocks:
  1029. rblocks = right._to_dict_of_blocks()
  1030. lblocks = left._to_dict_of_blocks()
  1031. for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))):
  1032. assert dtype in lblocks
  1033. assert dtype in rblocks
  1034. assert_frame_equal(
  1035. lblocks[dtype], rblocks[dtype], check_dtype=check_dtype, obj=obj
  1036. )
  1037. # compare by columns
  1038. else:
  1039. for i, col in enumerate(left.columns):
  1040. # We have already checked that columns match, so we can do
  1041. # fast location-based lookups
  1042. lcol = left._ixs(i, axis=1)
  1043. rcol = right._ixs(i, axis=1)
  1044. # GH #38183
  1045. # use check_index=False, because we do not want to run
  1046. # assert_index_equal for each column,
  1047. # as we already checked it for the whole dataframe before.
  1048. assert_series_equal(
  1049. lcol,
  1050. rcol,
  1051. check_dtype=check_dtype,
  1052. check_index_type=check_index_type,
  1053. check_exact=check_exact,
  1054. check_names=check_names,
  1055. check_datetimelike_compat=check_datetimelike_compat,
  1056. check_categorical=check_categorical,
  1057. check_freq=check_freq,
  1058. obj=f'{obj}.iloc[:, {i}] (column name="{col}")',
  1059. rtol=rtol,
  1060. atol=atol,
  1061. check_index=False,
  1062. check_flags=False,
  1063. )
  1064. def assert_equal(left, right, **kwargs) -> None:
  1065. """
  1066. Wrapper for tm.assert_*_equal to dispatch to the appropriate test function.
  1067. Parameters
  1068. ----------
  1069. left, right : Index, Series, DataFrame, ExtensionArray, or np.ndarray
  1070. The two items to be compared.
  1071. **kwargs
  1072. All keyword arguments are passed through to the underlying assert method.
  1073. """
  1074. __tracebackhide__ = True
  1075. if isinstance(left, Index):
  1076. assert_index_equal(left, right, **kwargs)
  1077. if isinstance(left, (DatetimeIndex, TimedeltaIndex)):
  1078. assert left.freq == right.freq, (left.freq, right.freq)
  1079. elif isinstance(left, Series):
  1080. assert_series_equal(left, right, **kwargs)
  1081. elif isinstance(left, DataFrame):
  1082. assert_frame_equal(left, right, **kwargs)
  1083. elif isinstance(left, IntervalArray):
  1084. assert_interval_array_equal(left, right, **kwargs)
  1085. elif isinstance(left, PeriodArray):
  1086. assert_period_array_equal(left, right, **kwargs)
  1087. elif isinstance(left, DatetimeArray):
  1088. assert_datetime_array_equal(left, right, **kwargs)
  1089. elif isinstance(left, TimedeltaArray):
  1090. assert_timedelta_array_equal(left, right, **kwargs)
  1091. elif isinstance(left, ExtensionArray):
  1092. assert_extension_array_equal(left, right, **kwargs)
  1093. elif isinstance(left, np.ndarray):
  1094. assert_numpy_array_equal(left, right, **kwargs)
  1095. elif isinstance(left, str):
  1096. assert kwargs == {}
  1097. assert left == right
  1098. else:
  1099. assert kwargs == {}
  1100. assert_almost_equal(left, right)
  1101. def assert_sp_array_equal(left, right) -> None:
  1102. """
  1103. Check that the left and right SparseArray are equal.
  1104. Parameters
  1105. ----------
  1106. left : SparseArray
  1107. right : SparseArray
  1108. """
  1109. _check_isinstance(left, right, pd.arrays.SparseArray)
  1110. assert_numpy_array_equal(left.sp_values, right.sp_values)
  1111. # SparseIndex comparison
  1112. assert isinstance(left.sp_index, SparseIndex)
  1113. assert isinstance(right.sp_index, SparseIndex)
  1114. left_index = left.sp_index
  1115. right_index = right.sp_index
  1116. if not left_index.equals(right_index):
  1117. raise_assert_detail(
  1118. "SparseArray.index", "index are not equal", left_index, right_index
  1119. )
  1120. else:
  1121. # Just ensure a
  1122. pass
  1123. assert_attr_equal("fill_value", left, right)
  1124. assert_attr_equal("dtype", left, right)
  1125. assert_numpy_array_equal(left.to_dense(), right.to_dense())
  1126. def assert_contains_all(iterable, dic) -> None:
  1127. for k in iterable:
  1128. assert k in dic, f"Did not contain item: {repr(k)}"
  1129. def assert_copy(iter1, iter2, **eql_kwargs) -> None:
  1130. """
  1131. iter1, iter2: iterables that produce elements
  1132. comparable with assert_almost_equal
  1133. Checks that the elements are equal, but not
  1134. the same object. (Does not check that items
  1135. in sequences are also not the same object)
  1136. """
  1137. for elem1, elem2 in zip(iter1, iter2):
  1138. assert_almost_equal(elem1, elem2, **eql_kwargs)
  1139. msg = (
  1140. f"Expected object {repr(type(elem1))} and object {repr(type(elem2))} to be "
  1141. "different objects, but they were the same object."
  1142. )
  1143. assert elem1 is not elem2, msg
  1144. def is_extension_array_dtype_and_needs_i8_conversion(left_dtype, right_dtype) -> bool:
  1145. """
  1146. Checks that we have the combination of an ExtensionArraydtype and
  1147. a dtype that should be converted to int64
  1148. Returns
  1149. -------
  1150. bool
  1151. Related to issue #37609
  1152. """
  1153. return is_extension_array_dtype(left_dtype) and needs_i8_conversion(right_dtype)
  1154. def assert_indexing_slices_equivalent(ser: Series, l_slc: slice, i_slc: slice) -> None:
  1155. """
  1156. Check that ser.iloc[i_slc] matches ser.loc[l_slc] and, if applicable,
  1157. ser[l_slc].
  1158. """
  1159. expected = ser.iloc[i_slc]
  1160. assert_series_equal(ser.loc[l_slc], expected)
  1161. if not is_integer_dtype(ser.index):
  1162. # For integer indices, .loc and plain getitem are position-based.
  1163. assert_series_equal(ser[l_slc], expected)
  1164. def assert_metadata_equivalent(
  1165. left: DataFrame | Series, right: DataFrame | Series | None = None
  1166. ) -> None:
  1167. """
  1168. Check that ._metadata attributes are equivalent.
  1169. """
  1170. for attr in left._metadata:
  1171. val = getattr(left, attr, None)
  1172. if right is None:
  1173. assert val is None
  1174. else:
  1175. assert val == getattr(right, attr, None)