conftest.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. from collections import abc
  2. from datetime import date, time, timedelta, timezone
  3. from decimal import Decimal
  4. import operator
  5. import os
  6. from dateutil.tz import tzlocal, tzutc
  7. import hypothesis
  8. from hypothesis import strategies as st
  9. import numpy as np
  10. import pytest
  11. from pytz import FixedOffset, utc
  12. import pandas.util._test_decorators as td
  13. import pandas as pd
  14. from pandas import DataFrame
  15. import pandas._testing as tm
  16. from pandas.core import ops
  17. hypothesis.settings.register_profile(
  18. "ci",
  19. # Hypothesis timing checks are tuned for scalars by default, so we bump
  20. # them from 200ms to 500ms per test case as the global default. If this
  21. # is too short for a specific test, (a) try to make it faster, and (b)
  22. # if it really is slow add `@settings(deadline=...)` with a working value,
  23. # or `deadline=None` to entirely disable timeouts for that test.
  24. deadline=500,
  25. suppress_health_check=(hypothesis.HealthCheck.too_slow,),
  26. )
  27. hypothesis.settings.load_profile("ci")
  28. def pytest_addoption(parser):
  29. parser.addoption("--skip-slow", action="store_true", help="skip slow tests")
  30. parser.addoption("--skip-network", action="store_true", help="skip network tests")
  31. parser.addoption("--skip-db", action="store_true", help="skip db tests")
  32. parser.addoption(
  33. "--run-high-memory", action="store_true", help="run high memory tests"
  34. )
  35. parser.addoption("--only-slow", action="store_true", help="run only slow tests")
  36. parser.addoption(
  37. "--strict-data-files",
  38. action="store_true",
  39. help="Fail if a test is skipped for missing data file.",
  40. )
  41. def pytest_runtest_setup(item):
  42. if "slow" in item.keywords and item.config.getoption("--skip-slow"):
  43. pytest.skip("skipping due to --skip-slow")
  44. if "slow" not in item.keywords and item.config.getoption("--only-slow"):
  45. pytest.skip("skipping due to --only-slow")
  46. if "network" in item.keywords and item.config.getoption("--skip-network"):
  47. pytest.skip("skipping due to --skip-network")
  48. if "db" in item.keywords and item.config.getoption("--skip-db"):
  49. pytest.skip("skipping due to --skip-db")
  50. if "high_memory" in item.keywords and not item.config.getoption(
  51. "--run-high-memory"
  52. ):
  53. pytest.skip("skipping high memory test since --run-high-memory was not set")
  54. # Configurations for all tests and all test modules
  55. @pytest.fixture(autouse=True)
  56. def configure_tests():
  57. pd.set_option("chained_assignment", "raise")
  58. # For running doctests: make np and pd names available
  59. @pytest.fixture(autouse=True)
  60. def add_imports(doctest_namespace):
  61. doctest_namespace["np"] = np
  62. doctest_namespace["pd"] = pd
  63. @pytest.fixture(params=["bsr", "coo", "csc", "csr", "dia", "dok", "lil"])
  64. def spmatrix(request):
  65. from scipy import sparse
  66. return getattr(sparse, request.param + "_matrix")
  67. @pytest.fixture(params=[0, 1, "index", "columns"], ids=lambda x: f"axis {repr(x)}")
  68. def axis(request):
  69. """
  70. Fixture for returning the axis numbers of a DataFrame.
  71. """
  72. return request.param
  73. axis_frame = axis
  74. @pytest.fixture(params=[0, "index"], ids=lambda x: f"axis {repr(x)}")
  75. def axis_series(request):
  76. """
  77. Fixture for returning the axis numbers of a Series.
  78. """
  79. return request.param
  80. @pytest.fixture
  81. def ip():
  82. """
  83. Get an instance of IPython.InteractiveShell.
  84. Will raise a skip if IPython is not installed.
  85. """
  86. pytest.importorskip("IPython", minversion="6.0.0")
  87. from IPython.core.interactiveshell import InteractiveShell
  88. return InteractiveShell()
  89. @pytest.fixture(params=[True, False, None])
  90. def observed(request):
  91. """
  92. Pass in the observed keyword to groupby for [True, False]
  93. This indicates whether categoricals should return values for
  94. values which are not in the grouper [False / None], or only values which
  95. appear in the grouper [True]. [None] is supported for future compatibility
  96. if we decide to change the default (and would need to warn if this
  97. parameter is not passed).
  98. """
  99. return request.param
  100. @pytest.fixture(params=[True, False, None])
  101. def ordered_fixture(request):
  102. """
  103. Boolean 'ordered' parameter for Categorical.
  104. """
  105. return request.param
  106. _all_arithmetic_operators = [
  107. "__add__",
  108. "__radd__",
  109. "__sub__",
  110. "__rsub__",
  111. "__mul__",
  112. "__rmul__",
  113. "__floordiv__",
  114. "__rfloordiv__",
  115. "__truediv__",
  116. "__rtruediv__",
  117. "__pow__",
  118. "__rpow__",
  119. "__mod__",
  120. "__rmod__",
  121. ]
  122. @pytest.fixture(params=_all_arithmetic_operators)
  123. def all_arithmetic_operators(request):
  124. """
  125. Fixture for dunder names for common arithmetic operations.
  126. """
  127. return request.param
  128. @pytest.fixture(
  129. params=[
  130. operator.add,
  131. ops.radd,
  132. operator.sub,
  133. ops.rsub,
  134. operator.mul,
  135. ops.rmul,
  136. operator.truediv,
  137. ops.rtruediv,
  138. operator.floordiv,
  139. ops.rfloordiv,
  140. operator.mod,
  141. ops.rmod,
  142. operator.pow,
  143. ops.rpow,
  144. ]
  145. )
  146. def all_arithmetic_functions(request):
  147. """
  148. Fixture for operator and roperator arithmetic functions.
  149. Notes
  150. -----
  151. This includes divmod and rdivmod, whereas all_arithmetic_operators
  152. does not.
  153. """
  154. return request.param
  155. _all_numeric_reductions = [
  156. "sum",
  157. "max",
  158. "min",
  159. "mean",
  160. "prod",
  161. "std",
  162. "var",
  163. "median",
  164. "kurt",
  165. "skew",
  166. ]
  167. @pytest.fixture(params=_all_numeric_reductions)
  168. def all_numeric_reductions(request):
  169. """
  170. Fixture for numeric reduction names.
  171. """
  172. return request.param
  173. _all_boolean_reductions = ["all", "any"]
  174. @pytest.fixture(params=_all_boolean_reductions)
  175. def all_boolean_reductions(request):
  176. """
  177. Fixture for boolean reduction names.
  178. """
  179. return request.param
  180. _cython_table = pd.core.base.SelectionMixin._cython_table.items()
  181. @pytest.fixture(params=list(_cython_table))
  182. def cython_table_items(request):
  183. return request.param
  184. def _get_cython_table_params(ndframe, func_names_and_expected):
  185. """
  186. Combine frame, functions from SelectionMixin._cython_table
  187. keys and expected result.
  188. Parameters
  189. ----------
  190. ndframe : DataFrame or Series
  191. func_names_and_expected : Sequence of two items
  192. The first item is a name of a NDFrame method ('sum', 'prod') etc.
  193. The second item is the expected return value.
  194. Returns
  195. -------
  196. list
  197. List of three items (DataFrame, function, expected result)
  198. """
  199. results = []
  200. for func_name, expected in func_names_and_expected:
  201. results.append((ndframe, func_name, expected))
  202. results += [
  203. (ndframe, func, expected)
  204. for func, name in _cython_table
  205. if name == func_name
  206. ]
  207. return results
  208. @pytest.fixture(params=["__eq__", "__ne__", "__le__", "__lt__", "__ge__", "__gt__"])
  209. def all_compare_operators(request):
  210. """
  211. Fixture for dunder names for common compare operations
  212. * >=
  213. * >
  214. * ==
  215. * !=
  216. * <
  217. * <=
  218. """
  219. return request.param
  220. @pytest.fixture(params=["__le__", "__lt__", "__ge__", "__gt__"])
  221. def compare_operators_no_eq_ne(request):
  222. """
  223. Fixture for dunder names for compare operations except == and !=
  224. * >=
  225. * >
  226. * <
  227. * <=
  228. """
  229. return request.param
  230. @pytest.fixture(
  231. params=["__and__", "__rand__", "__or__", "__ror__", "__xor__", "__rxor__"]
  232. )
  233. def all_logical_operators(request):
  234. """
  235. Fixture for dunder names for common logical operations
  236. * |
  237. * &
  238. * ^
  239. """
  240. return request.param
  241. @pytest.fixture(params=[None, "gzip", "bz2", "zip", "xz"])
  242. def compression(request):
  243. """
  244. Fixture for trying common compression types in compression tests.
  245. """
  246. return request.param
  247. @pytest.fixture(params=["gzip", "bz2", "zip", "xz"])
  248. def compression_only(request):
  249. """
  250. Fixture for trying common compression types in compression tests excluding
  251. uncompressed case.
  252. """
  253. return request.param
  254. @pytest.fixture(params=[True, False])
  255. def writable(request):
  256. """
  257. Fixture that an array is writable.
  258. """
  259. return request.param
  260. @pytest.fixture(scope="module")
  261. def datetime_tz_utc():
  262. return timezone.utc
  263. @pytest.fixture(params=["utc", "dateutil/UTC", utc, tzutc(), timezone.utc])
  264. def utc_fixture(request):
  265. """
  266. Fixture to provide variants of UTC timezone strings and tzinfo objects.
  267. """
  268. return request.param
  269. @pytest.fixture(params=["inner", "outer", "left", "right"])
  270. def join_type(request):
  271. """
  272. Fixture for trying all types of join operations.
  273. """
  274. return request.param
  275. @pytest.fixture
  276. def strict_data_files(pytestconfig):
  277. return pytestconfig.getoption("--strict-data-files")
  278. @pytest.fixture
  279. def datapath(strict_data_files):
  280. """
  281. Get the path to a data file.
  282. Parameters
  283. ----------
  284. path : str
  285. Path to the file, relative to ``pandas/tests/``
  286. Returns
  287. -------
  288. path including ``pandas/tests``.
  289. Raises
  290. ------
  291. ValueError
  292. If the path doesn't exist and the --strict-data-files option is set.
  293. """
  294. BASE_PATH = os.path.join(os.path.dirname(__file__), "tests")
  295. def deco(*args):
  296. path = os.path.join(BASE_PATH, *args)
  297. if not os.path.exists(path):
  298. if strict_data_files:
  299. raise ValueError(
  300. f"Could not find file {path} and --strict-data-files is set."
  301. )
  302. else:
  303. pytest.skip(f"Could not find {path}.")
  304. return path
  305. return deco
  306. @pytest.fixture
  307. def iris(datapath):
  308. """
  309. The iris dataset as a DataFrame.
  310. """
  311. return pd.read_csv(datapath("data", "iris.csv"))
  312. @pytest.fixture(params=["nlargest", "nsmallest"])
  313. def nselect_method(request):
  314. """
  315. Fixture for trying all nselect methods.
  316. """
  317. return request.param
  318. @pytest.fixture(params=["left", "right", "both", "neither"])
  319. def closed(request):
  320. """
  321. Fixture for trying all interval closed parameters.
  322. """
  323. return request.param
  324. @pytest.fixture(params=["left", "right", "both", "neither"])
  325. def other_closed(request):
  326. """
  327. Secondary closed fixture to allow parametrizing over all pairs of closed.
  328. """
  329. return request.param
  330. @pytest.fixture(params=[None, np.nan, pd.NaT, float("nan"), np.float("NaN")])
  331. def nulls_fixture(request):
  332. """
  333. Fixture for each null type in pandas.
  334. """
  335. return request.param
  336. nulls_fixture2 = nulls_fixture # Generate cartesian product of nulls_fixture
  337. @pytest.fixture(params=[None, np.nan, pd.NaT])
  338. def unique_nulls_fixture(request):
  339. """
  340. Fixture for each null type in pandas, each null type exactly once.
  341. """
  342. return request.param
  343. # Generate cartesian product of unique_nulls_fixture:
  344. unique_nulls_fixture2 = unique_nulls_fixture
  345. TIMEZONES = [
  346. None,
  347. "UTC",
  348. "US/Eastern",
  349. "Asia/Tokyo",
  350. "dateutil/US/Pacific",
  351. "dateutil/Asia/Singapore",
  352. tzutc(),
  353. tzlocal(),
  354. FixedOffset(300),
  355. FixedOffset(0),
  356. FixedOffset(-300),
  357. timezone.utc,
  358. timezone(timedelta(hours=1)),
  359. timezone(timedelta(hours=-1), name="foo"),
  360. ]
  361. TIMEZONE_IDS = [repr(i) for i in TIMEZONES]
  362. @td.parametrize_fixture_doc(str(TIMEZONE_IDS))
  363. @pytest.fixture(params=TIMEZONES, ids=TIMEZONE_IDS)
  364. def tz_naive_fixture(request):
  365. """
  366. Fixture for trying timezones including default (None): {0}
  367. """
  368. return request.param
  369. @td.parametrize_fixture_doc(str(TIMEZONE_IDS[1:]))
  370. @pytest.fixture(params=TIMEZONES[1:], ids=TIMEZONE_IDS[1:])
  371. def tz_aware_fixture(request):
  372. """
  373. Fixture for trying explicit timezones: {0}
  374. """
  375. return request.param
  376. # Generate cartesian product of tz_aware_fixture:
  377. tz_aware_fixture2 = tz_aware_fixture
  378. # ----------------------------------------------------------------
  379. # Dtypes
  380. # ----------------------------------------------------------------
  381. UNSIGNED_INT_DTYPES = ["uint8", "uint16", "uint32", "uint64"]
  382. UNSIGNED_EA_INT_DTYPES = ["UInt8", "UInt16", "UInt32", "UInt64"]
  383. SIGNED_INT_DTYPES = [int, "int8", "int16", "int32", "int64"]
  384. SIGNED_EA_INT_DTYPES = ["Int8", "Int16", "Int32", "Int64"]
  385. ALL_INT_DTYPES = UNSIGNED_INT_DTYPES + SIGNED_INT_DTYPES
  386. ALL_EA_INT_DTYPES = UNSIGNED_EA_INT_DTYPES + SIGNED_EA_INT_DTYPES
  387. FLOAT_DTYPES = [float, "float32", "float64"]
  388. COMPLEX_DTYPES = [complex, "complex64", "complex128"]
  389. STRING_DTYPES = [str, "str", "U"]
  390. DATETIME64_DTYPES = ["datetime64[ns]", "M8[ns]"]
  391. TIMEDELTA64_DTYPES = ["timedelta64[ns]", "m8[ns]"]
  392. BOOL_DTYPES = [bool, "bool"]
  393. BYTES_DTYPES = [bytes, "bytes"]
  394. OBJECT_DTYPES = [object, "object"]
  395. ALL_REAL_DTYPES = FLOAT_DTYPES + ALL_INT_DTYPES
  396. ALL_NUMPY_DTYPES = (
  397. ALL_REAL_DTYPES
  398. + COMPLEX_DTYPES
  399. + STRING_DTYPES
  400. + DATETIME64_DTYPES
  401. + TIMEDELTA64_DTYPES
  402. + BOOL_DTYPES
  403. + OBJECT_DTYPES
  404. + BYTES_DTYPES
  405. )
  406. @pytest.fixture(params=STRING_DTYPES)
  407. def string_dtype(request):
  408. """
  409. Parametrized fixture for string dtypes.
  410. * str
  411. * 'str'
  412. * 'U'
  413. """
  414. return request.param
  415. @pytest.fixture(params=BYTES_DTYPES)
  416. def bytes_dtype(request):
  417. """
  418. Parametrized fixture for bytes dtypes.
  419. * bytes
  420. * 'bytes'
  421. """
  422. return request.param
  423. @pytest.fixture(params=OBJECT_DTYPES)
  424. def object_dtype(request):
  425. """
  426. Parametrized fixture for object dtypes.
  427. * object
  428. * 'object'
  429. """
  430. return request.param
  431. @pytest.fixture(params=DATETIME64_DTYPES)
  432. def datetime64_dtype(request):
  433. """
  434. Parametrized fixture for datetime64 dtypes.
  435. * 'datetime64[ns]'
  436. * 'M8[ns]'
  437. """
  438. return request.param
  439. @pytest.fixture(params=TIMEDELTA64_DTYPES)
  440. def timedelta64_dtype(request):
  441. """
  442. Parametrized fixture for timedelta64 dtypes.
  443. * 'timedelta64[ns]'
  444. * 'm8[ns]'
  445. """
  446. return request.param
  447. @pytest.fixture(params=FLOAT_DTYPES)
  448. def float_dtype(request):
  449. """
  450. Parameterized fixture for float dtypes.
  451. * float
  452. * 'float32'
  453. * 'float64'
  454. """
  455. return request.param
  456. @pytest.fixture(params=COMPLEX_DTYPES)
  457. def complex_dtype(request):
  458. """
  459. Parameterized fixture for complex dtypes.
  460. * complex
  461. * 'complex64'
  462. * 'complex128'
  463. """
  464. return request.param
  465. @pytest.fixture(params=SIGNED_INT_DTYPES)
  466. def sint_dtype(request):
  467. """
  468. Parameterized fixture for signed integer dtypes.
  469. * int
  470. * 'int8'
  471. * 'int16'
  472. * 'int32'
  473. * 'int64'
  474. """
  475. return request.param
  476. @pytest.fixture(params=UNSIGNED_INT_DTYPES)
  477. def uint_dtype(request):
  478. """
  479. Parameterized fixture for unsigned integer dtypes.
  480. * 'uint8'
  481. * 'uint16'
  482. * 'uint32'
  483. * 'uint64'
  484. """
  485. return request.param
  486. @pytest.fixture(params=ALL_INT_DTYPES)
  487. def any_int_dtype(request):
  488. """
  489. Parameterized fixture for any integer dtype.
  490. * int
  491. * 'int8'
  492. * 'uint8'
  493. * 'int16'
  494. * 'uint16'
  495. * 'int32'
  496. * 'uint32'
  497. * 'int64'
  498. * 'uint64'
  499. """
  500. return request.param
  501. @pytest.fixture(params=ALL_EA_INT_DTYPES)
  502. def any_nullable_int_dtype(request):
  503. """
  504. Parameterized fixture for any nullable integer dtype.
  505. * 'UInt8'
  506. * 'Int8'
  507. * 'UInt16'
  508. * 'Int16'
  509. * 'UInt32'
  510. * 'Int32'
  511. * 'UInt64'
  512. * 'Int64'
  513. """
  514. return request.param
  515. @pytest.fixture(params=ALL_REAL_DTYPES)
  516. def any_real_dtype(request):
  517. """
  518. Parameterized fixture for any (purely) real numeric dtype.
  519. * int
  520. * 'int8'
  521. * 'uint8'
  522. * 'int16'
  523. * 'uint16'
  524. * 'int32'
  525. * 'uint32'
  526. * 'int64'
  527. * 'uint64'
  528. * float
  529. * 'float32'
  530. * 'float64'
  531. """
  532. return request.param
  533. @pytest.fixture(params=ALL_NUMPY_DTYPES)
  534. def any_numpy_dtype(request):
  535. """
  536. Parameterized fixture for all numpy dtypes.
  537. * bool
  538. * 'bool'
  539. * int
  540. * 'int8'
  541. * 'uint8'
  542. * 'int16'
  543. * 'uint16'
  544. * 'int32'
  545. * 'uint32'
  546. * 'int64'
  547. * 'uint64'
  548. * float
  549. * 'float32'
  550. * 'float64'
  551. * complex
  552. * 'complex64'
  553. * 'complex128'
  554. * str
  555. * 'str'
  556. * 'U'
  557. * bytes
  558. * 'bytes'
  559. * 'datetime64[ns]'
  560. * 'M8[ns]'
  561. * 'timedelta64[ns]'
  562. * 'm8[ns]'
  563. * object
  564. * 'object'
  565. """
  566. return request.param
  567. # categoricals are handled separately
  568. _any_skipna_inferred_dtype = [
  569. ("string", ["a", np.nan, "c"]),
  570. ("string", ["a", pd.NA, "c"]),
  571. ("bytes", [b"a", np.nan, b"c"]),
  572. ("empty", [np.nan, np.nan, np.nan]),
  573. ("empty", []),
  574. ("mixed-integer", ["a", np.nan, 2]),
  575. ("mixed", ["a", np.nan, 2.0]),
  576. ("floating", [1.0, np.nan, 2.0]),
  577. ("integer", [1, np.nan, 2]),
  578. ("mixed-integer-float", [1, np.nan, 2.0]),
  579. ("decimal", [Decimal(1), np.nan, Decimal(2)]),
  580. ("boolean", [True, np.nan, False]),
  581. ("boolean", [True, pd.NA, False]),
  582. ("datetime64", [np.datetime64("2013-01-01"), np.nan, np.datetime64("2018-01-01")]),
  583. ("datetime", [pd.Timestamp("20130101"), np.nan, pd.Timestamp("20180101")]),
  584. ("date", [date(2013, 1, 1), np.nan, date(2018, 1, 1)]),
  585. # The following two dtypes are commented out due to GH 23554
  586. # ('complex', [1 + 1j, np.nan, 2 + 2j]),
  587. # ('timedelta64', [np.timedelta64(1, 'D'),
  588. # np.nan, np.timedelta64(2, 'D')]),
  589. ("timedelta", [timedelta(1), np.nan, timedelta(2)]),
  590. ("time", [time(1), np.nan, time(2)]),
  591. ("period", [pd.Period(2013), pd.NaT, pd.Period(2018)]),
  592. ("interval", [pd.Interval(0, 1), np.nan, pd.Interval(0, 2)]),
  593. ]
  594. ids, _ = zip(*_any_skipna_inferred_dtype) # use inferred type as fixture-id
  595. @pytest.fixture(params=_any_skipna_inferred_dtype, ids=ids)
  596. def any_skipna_inferred_dtype(request):
  597. """
  598. Fixture for all inferred dtypes from _libs.lib.infer_dtype
  599. The covered (inferred) types are:
  600. * 'string'
  601. * 'empty'
  602. * 'bytes'
  603. * 'mixed'
  604. * 'mixed-integer'
  605. * 'mixed-integer-float'
  606. * 'floating'
  607. * 'integer'
  608. * 'decimal'
  609. * 'boolean'
  610. * 'datetime64'
  611. * 'datetime'
  612. * 'date'
  613. * 'timedelta'
  614. * 'time'
  615. * 'period'
  616. * 'interval'
  617. Returns
  618. -------
  619. inferred_dtype : str
  620. The string for the inferred dtype from _libs.lib.infer_dtype
  621. values : np.ndarray
  622. An array of object dtype that will be inferred to have
  623. `inferred_dtype`
  624. Examples
  625. --------
  626. >>> import pandas._libs.lib as lib
  627. >>>
  628. >>> def test_something(any_skipna_inferred_dtype):
  629. ... inferred_dtype, values = any_skipna_inferred_dtype
  630. ... # will pass
  631. ... assert lib.infer_dtype(values, skipna=True) == inferred_dtype
  632. """
  633. inferred_dtype, values = request.param
  634. values = np.array(values, dtype=object) # object dtype to avoid casting
  635. # correctness of inference tested in tests/dtypes/test_inference.py
  636. return inferred_dtype, values
  637. @pytest.fixture(
  638. params=[
  639. getattr(pd.offsets, o)
  640. for o in pd.offsets.__all__
  641. if issubclass(getattr(pd.offsets, o), pd.offsets.Tick)
  642. ]
  643. )
  644. def tick_classes(request):
  645. """
  646. Fixture for Tick based datetime offsets available for a time series.
  647. """
  648. return request.param
  649. # ----------------------------------------------------------------
  650. # Global setup for tests using Hypothesis
  651. # Registering these strategies makes them globally available via st.from_type,
  652. # which is use for offsets in tests/tseries/offsets/test_offsets_properties.py
  653. for name in "MonthBegin MonthEnd BMonthBegin BMonthEnd".split():
  654. cls = getattr(pd.tseries.offsets, name)
  655. st.register_type_strategy(
  656. cls, st.builds(cls, n=st.integers(-99, 99), normalize=st.booleans())
  657. )
  658. for name in "YearBegin YearEnd BYearBegin BYearEnd".split():
  659. cls = getattr(pd.tseries.offsets, name)
  660. st.register_type_strategy(
  661. cls,
  662. st.builds(
  663. cls,
  664. n=st.integers(-5, 5),
  665. normalize=st.booleans(),
  666. month=st.integers(min_value=1, max_value=12),
  667. ),
  668. )
  669. for name in "QuarterBegin QuarterEnd BQuarterBegin BQuarterEnd".split():
  670. cls = getattr(pd.tseries.offsets, name)
  671. st.register_type_strategy(
  672. cls,
  673. st.builds(
  674. cls,
  675. n=st.integers(-24, 24),
  676. normalize=st.booleans(),
  677. startingMonth=st.integers(min_value=1, max_value=12),
  678. ),
  679. )
  680. @pytest.fixture
  681. def float_frame():
  682. """
  683. Fixture for DataFrame of floats with index of unique strings
  684. Columns are ['A', 'B', 'C', 'D'].
  685. A B C D
  686. P7GACiRnxd -0.465578 -0.361863 0.886172 -0.053465
  687. qZKh6afn8n -0.466693 -0.373773 0.266873 1.673901
  688. tkp0r6Qble 0.148691 -0.059051 0.174817 1.598433
  689. wP70WOCtv8 0.133045 -0.581994 -0.992240 0.261651
  690. M2AeYQMnCz -1.207959 -0.185775 0.588206 0.563938
  691. QEPzyGDYDo -0.381843 -0.758281 0.502575 -0.565053
  692. r78Jwns6dn -0.653707 0.883127 0.682199 0.206159
  693. ... ... ... ... ...
  694. IHEGx9NO0T -0.277360 0.113021 -1.018314 0.196316
  695. lPMj8K27FA -1.313667 -0.604776 -1.305618 -0.863999
  696. qa66YMWQa5 1.110525 0.475310 -0.747865 0.032121
  697. yOa0ATsmcE -0.431457 0.067094 0.096567 -0.264962
  698. 65znX3uRNG 1.528446 0.160416 -0.109635 -0.032987
  699. eCOBvKqf3e 0.235281 1.622222 0.781255 0.392871
  700. xSucinXxuV -1.263557 0.252799 -0.552247 0.400426
  701. [30 rows x 4 columns]
  702. """
  703. return DataFrame(tm.getSeriesData())
  704. @pytest.fixture(params=[pd.Index, pd.Series], ids=["index", "series"])
  705. def index_or_series(request):
  706. """
  707. Fixture to parametrize over Index and Series, made necessary by a mypy
  708. bug, giving an error:
  709. List item 0 has incompatible type "Type[Series]"; expected "Type[PandasObject]"
  710. See GH#29725
  711. """
  712. return request.param
  713. @pytest.fixture
  714. def dict_subclass():
  715. """
  716. Fixture for a dictionary subclass.
  717. """
  718. class TestSubDict(dict):
  719. def __init__(self, *args, **kwargs):
  720. dict.__init__(self, *args, **kwargs)
  721. return TestSubDict
  722. @pytest.fixture
  723. def non_mapping_dict_subclass():
  724. """
  725. Fixture for a non-mapping dictionary subclass.
  726. """
  727. class TestNonDictMapping(abc.Mapping):
  728. def __init__(self, underlying_dict):
  729. self._data = underlying_dict
  730. def __getitem__(self, key):
  731. return self._data.__getitem__(key)
  732. def __iter__(self):
  733. return self._data.__iter__()
  734. def __len__(self):
  735. return self._data.__len__()
  736. return TestNonDictMapping