Skip to content

Commit d97df25

Browse files
mroeschkenoatamir
authored andcommitted
TST/CLN: Remove ensure_clean_path for tmp_dir fixture (pandas-dev#48925)
1 parent 3a47936 commit d97df25

16 files changed

+795
-848
lines changed

pandas/tests/io/pytables/common.py

+11-47
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from contextlib import contextmanager
2-
import os
2+
import pathlib
33
import tempfile
44
from typing import Generator
55

@@ -14,14 +14,6 @@
1414
tables.parameters.MAX_THREADS = 1
1515

1616

17-
def safe_remove(path):
18-
if path is not None:
19-
try:
20-
os.remove(path) # noqa: PDF008
21-
except OSError:
22-
pass
23-
24-
2517
def safe_close(store):
2618
try:
2719
if store is not None:
@@ -30,50 +22,22 @@ def safe_close(store):
3022
pass
3123

3224

33-
def create_tempfile(path):
34-
"""create an unopened named temporary file"""
35-
return os.path.join(tempfile.gettempdir(), path)
36-
37-
3825
# contextmanager to ensure the file cleanup
3926
@contextmanager
4027
def ensure_clean_store(
4128
path, mode="a", complevel=None, complib=None, fletcher32=False
4229
) -> Generator[HDFStore, None, None]:
4330

44-
try:
45-
46-
# put in the temporary path if we don't have one already
47-
if not len(os.path.dirname(path)):
48-
path = create_tempfile(path)
49-
50-
store = HDFStore(
51-
path, mode=mode, complevel=complevel, complib=complib, fletcher32=False
52-
)
53-
yield store
54-
finally:
55-
safe_close(store)
56-
if mode == "w" or mode == "a":
57-
safe_remove(path)
58-
59-
60-
@contextmanager
61-
def ensure_clean_path(path):
62-
"""
63-
return essentially a named temporary file that is not opened
64-
and deleted on exiting; if path is a list, then create and
65-
return list of filenames
66-
"""
67-
try:
68-
if isinstance(path, list):
69-
filenames = [create_tempfile(p) for p in path]
70-
yield filenames
71-
else:
72-
filenames = [create_tempfile(path)]
73-
yield filenames[0]
74-
finally:
75-
for f in filenames:
76-
safe_remove(f)
31+
with tempfile.TemporaryDirectory() as tmpdirname:
32+
tmp_path = pathlib.Path(tmpdirname, path)
33+
with HDFStore(
34+
tmp_path,
35+
mode=mode,
36+
complevel=complevel,
37+
complib=complib,
38+
fletcher32=fletcher32,
39+
) as store:
40+
yield store
7741

7842

7943
def _maybe_remove(store, key):

pandas/tests/io/pytables/test_append.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
)
2121
from pandas.tests.io.pytables.common import (
2222
_maybe_remove,
23-
ensure_clean_path,
2423
ensure_clean_store,
2524
)
2625

@@ -634,7 +633,7 @@ def check_col(key, name, size):
634633
tm.assert_frame_equal(result, expected)
635634

636635

637-
def test_append_hierarchical(setup_path, multiindex_dataframe_random_data):
636+
def test_append_hierarchical(tmp_path, setup_path, multiindex_dataframe_random_data):
638637
df = multiindex_dataframe_random_data
639638
df.columns.name = None
640639

@@ -648,11 +647,11 @@ def test_append_hierarchical(setup_path, multiindex_dataframe_random_data):
648647
expected = df.reindex(columns=["A", "B"])
649648
tm.assert_frame_equal(result, expected)
650649

651-
with ensure_clean_path("test.hdf") as path:
652-
df.to_hdf(path, "df", format="table")
653-
result = read_hdf(path, "df", columns=["A", "B"])
654-
expected = df.reindex(columns=["A", "B"])
655-
tm.assert_frame_equal(result, expected)
650+
path = tmp_path / "test.hdf"
651+
df.to_hdf(path, "df", format="table")
652+
result = read_hdf(path, "df", columns=["A", "B"])
653+
expected = df.reindex(columns=["A", "B"])
654+
tm.assert_frame_equal(result, expected)
656655

657656

658657
def test_append_misc(setup_path):

pandas/tests/io/pytables/test_categorical.py

+21-20
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
)
1212
from pandas.tests.io.pytables.common import (
1313
_maybe_remove,
14-
ensure_clean_path,
1514
ensure_clean_store,
1615
)
1716

@@ -147,7 +146,7 @@ def test_categorical(setup_path):
147146
store.select("df3/meta/s/meta")
148147

149148

150-
def test_categorical_conversion(setup_path):
149+
def test_categorical_conversion(tmp_path, setup_path):
151150

152151
# GH13322
153152
# Check that read_hdf with categorical columns doesn't return rows if
@@ -161,24 +160,24 @@ def test_categorical_conversion(setup_path):
161160

162161
# We are expecting an empty DataFrame matching types of df
163162
expected = df.iloc[[], :]
164-
with ensure_clean_path(setup_path) as path:
165-
df.to_hdf(path, "df", format="table", data_columns=True)
166-
result = read_hdf(path, "df", where="obsids=B")
167-
tm.assert_frame_equal(result, expected)
163+
path = tmp_path / setup_path
164+
df.to_hdf(path, "df", format="table", data_columns=True)
165+
result = read_hdf(path, "df", where="obsids=B")
166+
tm.assert_frame_equal(result, expected)
168167

169168
# Test with categories
170169
df.obsids = df.obsids.astype("category")
171170
df.imgids = df.imgids.astype("category")
172171

173172
# We are expecting an empty DataFrame matching types of df
174173
expected = df.iloc[[], :]
175-
with ensure_clean_path(setup_path) as path:
176-
df.to_hdf(path, "df", format="table", data_columns=True)
177-
result = read_hdf(path, "df", where="obsids=B")
178-
tm.assert_frame_equal(result, expected)
174+
path = tmp_path / setup_path
175+
df.to_hdf(path, "df", format="table", data_columns=True)
176+
result = read_hdf(path, "df", where="obsids=B")
177+
tm.assert_frame_equal(result, expected)
179178

180179

181-
def test_categorical_nan_only_columns(setup_path):
180+
def test_categorical_nan_only_columns(tmp_path, setup_path):
182181
# GH18413
183182
# Check that read_hdf with categorical columns with NaN-only values can
184183
# be read back.
@@ -194,10 +193,10 @@ def test_categorical_nan_only_columns(setup_path):
194193
df["b"] = df.b.astype("category")
195194
df["d"] = df.b.astype("category")
196195
expected = df
197-
with ensure_clean_path(setup_path) as path:
198-
df.to_hdf(path, "df", format="table", data_columns=True)
199-
result = read_hdf(path, "df")
200-
tm.assert_frame_equal(result, expected)
196+
path = tmp_path / setup_path
197+
df.to_hdf(path, "df", format="table", data_columns=True)
198+
result = read_hdf(path, "df")
199+
tm.assert_frame_equal(result, expected)
201200

202201

203202
@pytest.mark.parametrize(
@@ -207,7 +206,9 @@ def test_categorical_nan_only_columns(setup_path):
207206
('col=="a"', DataFrame({"col": ["a", "b", "s"]}), DataFrame({"col": ["a"]})),
208207
],
209208
)
210-
def test_convert_value(setup_path, where: str, df: DataFrame, expected: DataFrame):
209+
def test_convert_value(
210+
tmp_path, setup_path, where: str, df: DataFrame, expected: DataFrame
211+
):
211212
# GH39420
212213
# Check that read_hdf with categorical columns can filter by where condition.
213214
df.col = df.col.astype("category")
@@ -216,7 +217,7 @@ def test_convert_value(setup_path, where: str, df: DataFrame, expected: DataFram
216217
expected.col = expected.col.astype("category")
217218
expected.col = expected.col.cat.set_categories(categorical_values)
218219

219-
with ensure_clean_path(setup_path) as path:
220-
df.to_hdf(path, "df", format="table", min_itemsize=max_widths)
221-
result = read_hdf(path, where=where)
222-
tm.assert_frame_equal(result, expected)
220+
path = tmp_path / setup_path
221+
df.to_hdf(path, "df", format="table", min_itemsize=max_widths)
222+
result = read_hdf(path, where=where)
223+
tm.assert_frame_equal(result, expected)

pandas/tests/io/pytables/test_compat.py

+9-11
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,12 @@
22

33
import pandas as pd
44
import pandas._testing as tm
5-
from pandas.tests.io.pytables.common import ensure_clean_path
65

76
tables = pytest.importorskip("tables")
87

98

109
@pytest.fixture
11-
def pytables_hdf5_file():
10+
def pytables_hdf5_file(tmp_path):
1211
"""
1312
Use PyTables to create a simple HDF5 file.
1413
"""
@@ -29,16 +28,15 @@ def pytables_hdf5_file():
2928

3029
objname = "pandas_test_timeseries"
3130

32-
with ensure_clean_path("written_with_pytables.h5") as path:
33-
# The `ensure_clean_path` context mgr removes the temp file upon exit.
34-
with tables.open_file(path, mode="w") as f:
35-
t = f.create_table("/", name=objname, description=table_schema)
36-
for sample in testsamples:
37-
for key, value in sample.items():
38-
t.row[key] = value
39-
t.row.append()
31+
path = tmp_path / "written_with_pytables.h5"
32+
with tables.open_file(path, mode="w") as f:
33+
t = f.create_table("/", name=objname, description=table_schema)
34+
for sample in testsamples:
35+
for key, value in sample.items():
36+
t.row[key] = value
37+
t.row.append()
4038

41-
yield path, objname, pd.DataFrame(testsamples)
39+
yield path, objname, pd.DataFrame(testsamples)
4240

4341

4442
class TestReadPyTablesHDF5:

0 commit comments

Comments
 (0)