test_pickle.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. """
  2. manage legacy pickle tests
  3. How to add pickle tests:
  4. 1. Install pandas version intended to output the pickle.
  5. 2. Execute "generate_legacy_storage_files.py" to create the pickle.
  6. $ python generate_legacy_storage_files.py <output_dir> pickle
  7. 3. Move the created pickle to "data/legacy_pickle/<version>" directory.
  8. """
  9. from __future__ import annotations
  10. from array import array
  11. import bz2
  12. import datetime
  13. import functools
  14. from functools import partial
  15. import gzip
  16. import io
  17. import os
  18. from pathlib import Path
  19. import pickle
  20. import shutil
  21. import tarfile
  22. from typing import Any
  23. import uuid
  24. import zipfile
  25. import numpy as np
  26. import pytest
  27. from pandas.compat import (
  28. get_lzma_file,
  29. is_platform_little_endian,
  30. )
  31. from pandas.compat._optional import import_optional_dependency
  32. from pandas.compat.compressors import flatten_buffer
  33. import pandas.util._test_decorators as td
  34. import pandas as pd
  35. from pandas import (
  36. DataFrame,
  37. Index,
  38. Series,
  39. period_range,
  40. )
  41. import pandas._testing as tm
  42. from pandas.tests.io.generate_legacy_storage_files import create_pickle_data
  43. import pandas.io.common as icom
  44. from pandas.tseries.offsets import (
  45. Day,
  46. MonthEnd,
  47. )
  48. # ---------------------
  49. # comparison functions
  50. # ---------------------
  51. def compare_element(result, expected, typ):
  52. if isinstance(expected, Index):
  53. tm.assert_index_equal(expected, result)
  54. return
  55. if typ.startswith("sp_"):
  56. tm.assert_equal(result, expected)
  57. elif typ == "timestamp":
  58. if expected is pd.NaT:
  59. assert result is pd.NaT
  60. else:
  61. assert result == expected
  62. else:
  63. comparator = getattr(tm, f"assert_{typ}_equal", tm.assert_almost_equal)
  64. comparator(result, expected)
  65. # ---------------------
  66. # tests
  67. # ---------------------
  68. @pytest.mark.parametrize(
  69. "data",
  70. [
  71. b"123",
  72. b"123456",
  73. bytearray(b"123"),
  74. memoryview(b"123"),
  75. pickle.PickleBuffer(b"123"),
  76. array("I", [1, 2, 3]),
  77. memoryview(b"123456").cast("B", (3, 2)),
  78. memoryview(b"123456").cast("B", (3, 2))[::2],
  79. np.arange(12).reshape((3, 4), order="C"),
  80. np.arange(12).reshape((3, 4), order="F"),
  81. np.arange(12).reshape((3, 4), order="C")[:, ::2],
  82. ],
  83. )
  84. def test_flatten_buffer(data):
  85. result = flatten_buffer(data)
  86. expected = memoryview(data).tobytes("A")
  87. assert result == expected
  88. if isinstance(data, (bytes, bytearray)):
  89. assert result is data
  90. elif isinstance(result, memoryview):
  91. assert result.ndim == 1
  92. assert result.format == "B"
  93. assert result.contiguous
  94. assert result.shape == (result.nbytes,)
  95. def test_pickles(datapath):
  96. if not is_platform_little_endian():
  97. pytest.skip("known failure on non-little endian")
  98. # For loop for compat with --strict-data-files
  99. for legacy_pickle in Path(__file__).parent.glob("data/legacy_pickle/*/*.p*kl*"):
  100. legacy_pickle = datapath(legacy_pickle)
  101. data = pd.read_pickle(legacy_pickle)
  102. for typ, dv in data.items():
  103. for dt, result in dv.items():
  104. expected = data[typ][dt]
  105. if typ == "series" and dt == "ts":
  106. # GH 7748
  107. tm.assert_series_equal(result, expected)
  108. assert result.index.freq == expected.index.freq
  109. assert not result.index.freq.normalize
  110. tm.assert_series_equal(result > 0, expected > 0)
  111. # GH 9291
  112. freq = result.index.freq
  113. assert freq + Day(1) == Day(2)
  114. res = freq + pd.Timedelta(hours=1)
  115. assert isinstance(res, pd.Timedelta)
  116. assert res == pd.Timedelta(days=1, hours=1)
  117. res = freq + pd.Timedelta(nanoseconds=1)
  118. assert isinstance(res, pd.Timedelta)
  119. assert res == pd.Timedelta(days=1, nanoseconds=1)
  120. elif typ == "index" and dt == "period":
  121. tm.assert_index_equal(result, expected)
  122. assert isinstance(result.freq, MonthEnd)
  123. assert result.freq == MonthEnd()
  124. assert result.freqstr == "M"
  125. tm.assert_index_equal(result.shift(2), expected.shift(2))
  126. elif typ == "series" and dt in ("dt_tz", "cat"):
  127. tm.assert_series_equal(result, expected)
  128. elif typ == "frame" and dt in (
  129. "dt_mixed_tzs",
  130. "cat_onecol",
  131. "cat_and_float",
  132. ):
  133. tm.assert_frame_equal(result, expected)
  134. else:
  135. compare_element(result, expected, typ)
  136. def python_pickler(obj, path):
  137. with open(path, "wb") as fh:
  138. pickle.dump(obj, fh, protocol=-1)
  139. def python_unpickler(path):
  140. with open(path, "rb") as fh:
  141. fh.seek(0)
  142. return pickle.load(fh)
  143. def flatten(data: dict) -> list[tuple[str, Any]]:
  144. """Flatten create_pickle_data"""
  145. return [
  146. (typ, example)
  147. for typ, examples in data.items()
  148. for example in examples.values()
  149. ]
  150. @pytest.mark.parametrize(
  151. "pickle_writer",
  152. [
  153. pytest.param(python_pickler, id="python"),
  154. pytest.param(pd.to_pickle, id="pandas_proto_default"),
  155. pytest.param(
  156. functools.partial(pd.to_pickle, protocol=pickle.HIGHEST_PROTOCOL),
  157. id="pandas_proto_highest",
  158. ),
  159. pytest.param(functools.partial(pd.to_pickle, protocol=4), id="pandas_proto_4"),
  160. pytest.param(
  161. functools.partial(pd.to_pickle, protocol=5),
  162. id="pandas_proto_5",
  163. ),
  164. ],
  165. )
  166. @pytest.mark.parametrize("writer", [pd.to_pickle, python_pickler])
  167. @pytest.mark.parametrize("typ, expected", flatten(create_pickle_data()))
  168. def test_round_trip_current(typ, expected, pickle_writer, writer):
  169. with tm.ensure_clean() as path:
  170. # test writing with each pickler
  171. pickle_writer(expected, path)
  172. # test reading with each unpickler
  173. result = pd.read_pickle(path)
  174. compare_element(result, expected, typ)
  175. result = python_unpickler(path)
  176. compare_element(result, expected, typ)
  177. # and the same for file objects (GH 35679)
  178. with open(path, mode="wb") as handle:
  179. writer(expected, path)
  180. handle.seek(0) # shouldn't close file handle
  181. with open(path, mode="rb") as handle:
  182. result = pd.read_pickle(handle)
  183. handle.seek(0) # shouldn't close file handle
  184. compare_element(result, expected, typ)
  185. def test_pickle_path_pathlib():
  186. df = DataFrame(
  187. 1.1 * np.arange(120).reshape((30, 4)),
  188. columns=Index(list("ABCD"), dtype=object),
  189. index=Index([f"i-{i}" for i in range(30)], dtype=object),
  190. )
  191. result = tm.round_trip_pathlib(df.to_pickle, pd.read_pickle)
  192. tm.assert_frame_equal(df, result)
  193. def test_pickle_path_localpath():
  194. df = DataFrame(
  195. 1.1 * np.arange(120).reshape((30, 4)),
  196. columns=Index(list("ABCD"), dtype=object),
  197. index=Index([f"i-{i}" for i in range(30)], dtype=object),
  198. )
  199. result = tm.round_trip_localpath(df.to_pickle, pd.read_pickle)
  200. tm.assert_frame_equal(df, result)
  201. # ---------------------
  202. # test pickle compression
  203. # ---------------------
  204. @pytest.fixture
  205. def get_random_path():
  206. return f"__{uuid.uuid4()}__.pickle"
  207. class TestCompression:
  208. _extension_to_compression = icom.extension_to_compression
  209. def compress_file(self, src_path, dest_path, compression):
  210. if compression is None:
  211. shutil.copyfile(src_path, dest_path)
  212. return
  213. if compression == "gzip":
  214. f = gzip.open(dest_path, "w")
  215. elif compression == "bz2":
  216. f = bz2.BZ2File(dest_path, "w")
  217. elif compression == "zip":
  218. with zipfile.ZipFile(dest_path, "w", compression=zipfile.ZIP_DEFLATED) as f:
  219. f.write(src_path, os.path.basename(src_path))
  220. elif compression == "tar":
  221. with open(src_path, "rb") as fh:
  222. with tarfile.open(dest_path, mode="w") as tar:
  223. tarinfo = tar.gettarinfo(src_path, os.path.basename(src_path))
  224. tar.addfile(tarinfo, fh)
  225. elif compression == "xz":
  226. f = get_lzma_file()(dest_path, "w")
  227. elif compression == "zstd":
  228. f = import_optional_dependency("zstandard").open(dest_path, "wb")
  229. else:
  230. msg = f"Unrecognized compression type: {compression}"
  231. raise ValueError(msg)
  232. if compression not in ["zip", "tar"]:
  233. with open(src_path, "rb") as fh:
  234. with f:
  235. f.write(fh.read())
  236. def test_write_explicit(self, compression, get_random_path):
  237. base = get_random_path
  238. path1 = base + ".compressed"
  239. path2 = base + ".raw"
  240. with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2:
  241. df = DataFrame(
  242. 1.1 * np.arange(120).reshape((30, 4)),
  243. columns=Index(list("ABCD"), dtype=object),
  244. index=Index([f"i-{i}" for i in range(30)], dtype=object),
  245. )
  246. # write to compressed file
  247. df.to_pickle(p1, compression=compression)
  248. # decompress
  249. with tm.decompress_file(p1, compression=compression) as f:
  250. with open(p2, "wb") as fh:
  251. fh.write(f.read())
  252. # read decompressed file
  253. df2 = pd.read_pickle(p2, compression=None)
  254. tm.assert_frame_equal(df, df2)
  255. @pytest.mark.parametrize("compression", ["", "None", "bad", "7z"])
  256. def test_write_explicit_bad(self, compression, get_random_path):
  257. with pytest.raises(ValueError, match="Unrecognized compression type"):
  258. with tm.ensure_clean(get_random_path) as path:
  259. df = DataFrame(
  260. 1.1 * np.arange(120).reshape((30, 4)),
  261. columns=Index(list("ABCD"), dtype=object),
  262. index=Index([f"i-{i}" for i in range(30)], dtype=object),
  263. )
  264. df.to_pickle(path, compression=compression)
  265. def test_write_infer(self, compression_ext, get_random_path):
  266. base = get_random_path
  267. path1 = base + compression_ext
  268. path2 = base + ".raw"
  269. compression = self._extension_to_compression.get(compression_ext.lower())
  270. with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2:
  271. df = DataFrame(
  272. 1.1 * np.arange(120).reshape((30, 4)),
  273. columns=Index(list("ABCD"), dtype=object),
  274. index=Index([f"i-{i}" for i in range(30)], dtype=object),
  275. )
  276. # write to compressed file by inferred compression method
  277. df.to_pickle(p1)
  278. # decompress
  279. with tm.decompress_file(p1, compression=compression) as f:
  280. with open(p2, "wb") as fh:
  281. fh.write(f.read())
  282. # read decompressed file
  283. df2 = pd.read_pickle(p2, compression=None)
  284. tm.assert_frame_equal(df, df2)
  285. def test_read_explicit(self, compression, get_random_path):
  286. base = get_random_path
  287. path1 = base + ".raw"
  288. path2 = base + ".compressed"
  289. with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2:
  290. df = DataFrame(
  291. 1.1 * np.arange(120).reshape((30, 4)),
  292. columns=Index(list("ABCD"), dtype=object),
  293. index=Index([f"i-{i}" for i in range(30)], dtype=object),
  294. )
  295. # write to uncompressed file
  296. df.to_pickle(p1, compression=None)
  297. # compress
  298. self.compress_file(p1, p2, compression=compression)
  299. # read compressed file
  300. df2 = pd.read_pickle(p2, compression=compression)
  301. tm.assert_frame_equal(df, df2)
  302. def test_read_infer(self, compression_ext, get_random_path):
  303. base = get_random_path
  304. path1 = base + ".raw"
  305. path2 = base + compression_ext
  306. compression = self._extension_to_compression.get(compression_ext.lower())
  307. with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2:
  308. df = DataFrame(
  309. 1.1 * np.arange(120).reshape((30, 4)),
  310. columns=Index(list("ABCD"), dtype=object),
  311. index=Index([f"i-{i}" for i in range(30)], dtype=object),
  312. )
  313. # write to uncompressed file
  314. df.to_pickle(p1, compression=None)
  315. # compress
  316. self.compress_file(p1, p2, compression=compression)
  317. # read compressed file by inferred compression method
  318. df2 = pd.read_pickle(p2)
  319. tm.assert_frame_equal(df, df2)
  320. # ---------------------
  321. # test pickle compression
  322. # ---------------------
  323. class TestProtocol:
  324. @pytest.mark.parametrize("protocol", [-1, 0, 1, 2])
  325. def test_read(self, protocol, get_random_path):
  326. with tm.ensure_clean(get_random_path) as path:
  327. df = DataFrame(
  328. 1.1 * np.arange(120).reshape((30, 4)),
  329. columns=Index(list("ABCD"), dtype=object),
  330. index=Index([f"i-{i}" for i in range(30)], dtype=object),
  331. )
  332. df.to_pickle(path, protocol=protocol)
  333. df2 = pd.read_pickle(path)
  334. tm.assert_frame_equal(df, df2)
  335. @pytest.mark.parametrize(
  336. ["pickle_file", "excols"],
  337. [
  338. ("test_py27.pkl", Index(["a", "b", "c"], dtype=object)),
  339. (
  340. "test_mi_py27.pkl",
  341. pd.MultiIndex(
  342. [
  343. Index(["a", "b", "c"], dtype=object),
  344. Index(["A", "B", "C"], dtype=object),
  345. ],
  346. [np.array([0, 1, 2]), np.array([0, 1, 2])],
  347. ),
  348. ),
  349. ],
  350. )
  351. def test_unicode_decode_error(datapath, pickle_file, excols):
  352. # pickle file written with py27, should be readable without raising
  353. # UnicodeDecodeError, see GH#28645 and GH#31988
  354. path = datapath("io", "data", "pickle", pickle_file)
  355. df = pd.read_pickle(path)
  356. # just test the columns are correct since the values are random
  357. tm.assert_index_equal(df.columns, excols)
  358. # ---------------------
  359. # tests for buffer I/O
  360. # ---------------------
  361. def test_pickle_buffer_roundtrip():
  362. with tm.ensure_clean() as path:
  363. df = DataFrame(
  364. 1.1 * np.arange(120).reshape((30, 4)),
  365. columns=Index(list("ABCD"), dtype=object),
  366. index=Index([f"i-{i}" for i in range(30)], dtype=object),
  367. )
  368. with open(path, "wb") as fh:
  369. df.to_pickle(fh)
  370. with open(path, "rb") as fh:
  371. result = pd.read_pickle(fh)
  372. tm.assert_frame_equal(df, result)
  373. # ---------------------
  374. # tests for URL I/O
  375. # ---------------------
  376. @pytest.mark.parametrize(
  377. "mockurl", ["http://url.com", "ftp://test.com", "http://gzip.com"]
  378. )
  379. def test_pickle_generalurl_read(monkeypatch, mockurl):
  380. def python_pickler(obj, path):
  381. with open(path, "wb") as fh:
  382. pickle.dump(obj, fh, protocol=-1)
  383. class MockReadResponse:
  384. def __init__(self, path) -> None:
  385. self.file = open(path, "rb")
  386. if "gzip" in path:
  387. self.headers = {"Content-Encoding": "gzip"}
  388. else:
  389. self.headers = {"Content-Encoding": ""}
  390. def __enter__(self):
  391. return self
  392. def __exit__(self, *args):
  393. self.close()
  394. def read(self):
  395. return self.file.read()
  396. def close(self):
  397. return self.file.close()
  398. with tm.ensure_clean() as path:
  399. def mock_urlopen_read(*args, **kwargs):
  400. return MockReadResponse(path)
  401. df = DataFrame(
  402. 1.1 * np.arange(120).reshape((30, 4)),
  403. columns=Index(list("ABCD"), dtype=object),
  404. index=Index([f"i-{i}" for i in range(30)], dtype=object),
  405. )
  406. python_pickler(df, path)
  407. monkeypatch.setattr("urllib.request.urlopen", mock_urlopen_read)
  408. result = pd.read_pickle(mockurl)
  409. tm.assert_frame_equal(df, result)
  410. def test_pickle_fsspec_roundtrip():
  411. pytest.importorskip("fsspec")
  412. with tm.ensure_clean():
  413. mockurl = "memory://mockfile"
  414. df = DataFrame(
  415. 1.1 * np.arange(120).reshape((30, 4)),
  416. columns=Index(list("ABCD"), dtype=object),
  417. index=Index([f"i-{i}" for i in range(30)], dtype=object),
  418. )
  419. df.to_pickle(mockurl)
  420. result = pd.read_pickle(mockurl)
  421. tm.assert_frame_equal(df, result)
  422. class MyTz(datetime.tzinfo):
  423. def __init__(self) -> None:
  424. pass
  425. def test_read_pickle_with_subclass():
  426. # GH 12163
  427. expected = Series(dtype=object), MyTz()
  428. result = tm.round_trip_pickle(expected)
  429. tm.assert_series_equal(result[0], expected[0])
  430. assert isinstance(result[1], MyTz)
  431. def test_pickle_binary_object_compression(compression):
  432. """
  433. Read/write from binary file-objects w/wo compression.
  434. GH 26237, GH 29054, and GH 29570
  435. """
  436. df = DataFrame(
  437. 1.1 * np.arange(120).reshape((30, 4)),
  438. columns=Index(list("ABCD"), dtype=object),
  439. index=Index([f"i-{i}" for i in range(30)], dtype=object),
  440. )
  441. # reference for compression
  442. with tm.ensure_clean() as path:
  443. df.to_pickle(path, compression=compression)
  444. reference = Path(path).read_bytes()
  445. # write
  446. buffer = io.BytesIO()
  447. df.to_pickle(buffer, compression=compression)
  448. buffer.seek(0)
  449. # gzip and zip safe the filename: cannot compare the compressed content
  450. assert buffer.getvalue() == reference or compression in ("gzip", "zip", "tar")
  451. # read
  452. read_df = pd.read_pickle(buffer, compression=compression)
  453. buffer.seek(0)
  454. tm.assert_frame_equal(df, read_df)
  455. def test_pickle_dataframe_with_multilevel_index(
  456. multiindex_year_month_day_dataframe_random_data,
  457. multiindex_dataframe_random_data,
  458. ):
  459. ymd = multiindex_year_month_day_dataframe_random_data
  460. frame = multiindex_dataframe_random_data
  461. def _test_roundtrip(frame):
  462. unpickled = tm.round_trip_pickle(frame)
  463. tm.assert_frame_equal(frame, unpickled)
  464. _test_roundtrip(frame)
  465. _test_roundtrip(frame.T)
  466. _test_roundtrip(ymd)
  467. _test_roundtrip(ymd.T)
  468. def test_pickle_timeseries_periodindex():
  469. # GH#2891
  470. prng = period_range("1/1/2011", "1/1/2012", freq="M")
  471. ts = Series(np.random.default_rng(2).standard_normal(len(prng)), prng)
  472. new_ts = tm.round_trip_pickle(ts)
  473. assert new_ts.index.freqstr == "M"
  474. @pytest.mark.parametrize(
  475. "name", [777, 777.0, "name", datetime.datetime(2001, 11, 11), (1, 2)]
  476. )
  477. def test_pickle_preserve_name(name):
  478. unpickled = tm.round_trip_pickle(Series(np.arange(10, dtype=np.float64), name=name))
  479. assert unpickled.name == name
  480. def test_pickle_datetimes(datetime_series):
  481. unp_ts = tm.round_trip_pickle(datetime_series)
  482. tm.assert_series_equal(unp_ts, datetime_series)
  483. def test_pickle_strings(string_series):
  484. unp_series = tm.round_trip_pickle(string_series)
  485. tm.assert_series_equal(unp_series, string_series)
  486. @td.skip_array_manager_invalid_test
  487. def test_pickle_preserves_block_ndim():
  488. # GH#37631
  489. ser = Series(list("abc")).astype("category").iloc[[0]]
  490. res = tm.round_trip_pickle(ser)
  491. assert res._mgr.blocks[0].ndim == 1
  492. assert res._mgr.blocks[0].shape == (1,)
  493. # GH#37631 OP issue was about indexing, underlying problem was pickle
  494. tm.assert_series_equal(res[[True]], ser)
  495. @pytest.mark.parametrize("protocol", [pickle.DEFAULT_PROTOCOL, pickle.HIGHEST_PROTOCOL])
  496. def test_pickle_big_dataframe_compression(protocol, compression):
  497. # GH#39002
  498. df = DataFrame(range(100000))
  499. result = tm.round_trip_pathlib(
  500. partial(df.to_pickle, protocol=protocol, compression=compression),
  501. partial(pd.read_pickle, compression=compression),
  502. )
  503. tm.assert_frame_equal(df, result)
  504. def test_pickle_frame_v124_unpickle_130(datapath):
  505. # GH#42345 DataFrame created in 1.2.x, unpickle in 1.3.x
  506. path = datapath(
  507. Path(__file__).parent,
  508. "data",
  509. "legacy_pickle",
  510. "1.2.4",
  511. "empty_frame_v1_2_4-GH#42345.pkl",
  512. )
  513. with open(path, "rb") as fd:
  514. df = pickle.load(fd)
  515. expected = DataFrame(index=[], columns=[])
  516. tm.assert_frame_equal(df, expected)
  517. def test_pickle_pos_args_deprecation():
  518. # GH-54229
  519. df = DataFrame({"a": [1, 2, 3]})
  520. msg = (
  521. r"Starting with pandas version 3.0 all arguments of to_pickle except for the "
  522. r"argument 'path' will be keyword-only."
  523. )
  524. with tm.assert_produces_warning(FutureWarning, match=msg):
  525. buffer = io.BytesIO()
  526. df.to_pickle(buffer, "infer")