Skip to content

Commit 1d0d4e7

Browse files
committed
TST: use with where possible instead of manual close
Coincidentally fixes some StataReaders being left open in tests.
1 parent ee352b1 commit 1d0d4e7

10 files changed

+129
-151
lines changed

pandas/tests/io/parser/test_encoding.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -66,13 +66,9 @@ def test_utf16_bom_skiprows(all_parsers, sep, encoding):
6666
with open(path, "wb") as f:
6767
f.write(bytes_data)
6868

69-
bytes_buffer = BytesIO(data.encode(utf8))
70-
bytes_buffer = TextIOWrapper(bytes_buffer, encoding=utf8)
71-
72-
result = parser.read_csv(path, encoding=encoding, **kwargs)
73-
expected = parser.read_csv(bytes_buffer, encoding=utf8, **kwargs)
74-
75-
bytes_buffer.close()
69+
with TextIOWrapper(BytesIO(data.encode(utf8)), encoding=utf8) as bytes_buffer:
70+
result = parser.read_csv(path, encoding=encoding, **kwargs)
71+
expected = parser.read_csv(bytes_buffer, encoding=utf8, **kwargs)
7672
tm.assert_frame_equal(result, expected)
7773

7874

pandas/tests/io/pytables/test_file_handling.py

+12-16
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,8 @@ def test_mode(setup_path, mode):
4242
HDFStore(path, mode=mode)
4343

4444
else:
45-
store = HDFStore(path, mode=mode)
46-
assert store._handle.mode == mode
47-
store.close()
45+
with HDFStore(path, mode=mode) as store:
46+
assert store._handle.mode == mode
4847

4948
with ensure_clean_path(setup_path) as path:
5049

@@ -253,14 +252,13 @@ def test_complibs(setup_path):
253252

254253
# Open file and check metadata
255254
# for correct amount of compression
256-
h5table = tables.open_file(tmpfile, mode="r")
257-
for node in h5table.walk_nodes(where="/" + gname, classname="Leaf"):
258-
assert node.filters.complevel == lvl
259-
if lvl == 0:
260-
assert node.filters.complib is None
261-
else:
262-
assert node.filters.complib == lib
263-
h5table.close()
255+
with tables.open_file(tmpfile, mode="r") as h5table:
256+
for node in h5table.walk_nodes(where="/" + gname, classname="Leaf"):
257+
assert node.filters.complevel == lvl
258+
if lvl == 0:
259+
assert node.filters.complib is None
260+
else:
261+
assert node.filters.complib == lib
264262

265263

266264
@pytest.mark.skipif(
@@ -334,15 +332,13 @@ def test_multiple_open_close(setup_path):
334332

335333
if pytables._table_file_open_policy_is_strict:
336334
# multiples
337-
store1 = HDFStore(path)
338335
msg = (
339336
r"The file [\S]* is already opened\. Please close it before "
340337
r"reopening in write mode\."
341338
)
342-
with pytest.raises(ValueError, match=msg):
343-
HDFStore(path)
344-
345-
store1.close()
339+
with HDFStore(path) as store1:
340+
with pytest.raises(ValueError, match=msg):
341+
HDFStore(path)
346342
else:
347343

348344
# multiples

pandas/tests/io/pytables/test_read.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from contextlib import closing
12
from pathlib import Path
23
import re
34

@@ -208,11 +209,10 @@ def test_read_hdf_open_store(setup_path):
208209
with ensure_clean_path(setup_path) as path:
209210
df.to_hdf(path, "df", mode="w")
210211
direct = read_hdf(path, "df")
211-
store = HDFStore(path, mode="r")
212-
indirect = read_hdf(store, "df")
213-
tm.assert_frame_equal(direct, indirect)
214-
assert store.is_open
215-
store.close()
212+
with HDFStore(path, mode="r") as store:
213+
indirect = read_hdf(store, "df")
214+
tm.assert_frame_equal(direct, indirect)
215+
assert store.is_open
216216

217217

218218
def test_read_hdf_iterator(setup_path):
@@ -224,10 +224,10 @@ def test_read_hdf_iterator(setup_path):
224224
df.to_hdf(path, "df", mode="w", format="t")
225225
direct = read_hdf(path, "df")
226226
iterator = read_hdf(path, "df", iterator=True)
227-
assert isinstance(iterator, TableIterator)
228-
indirect = next(iterator.__iter__())
229-
tm.assert_frame_equal(direct, indirect)
230-
iterator.store.close()
227+
with closing(iterator.store):
228+
assert isinstance(iterator, TableIterator)
229+
indirect = next(iterator.__iter__())
230+
tm.assert_frame_equal(direct, indirect)
231231

232232

233233
def test_read_nokey(setup_path):

pandas/tests/io/pytables/test_select.py

+12-15
Original file line numberDiff line numberDiff line change
@@ -684,10 +684,9 @@ def test_frame_select_complex2():
684684

685685
# scope with list like
686686
l0 = selection.index.tolist() # noqa:F841
687-
store = HDFStore(hh)
688-
result = store.select("df", where="l1=l0")
689-
tm.assert_frame_equal(result, expected)
690-
store.close()
687+
with HDFStore(hh) as store:
688+
result = store.select("df", where="l1=l0")
689+
tm.assert_frame_equal(result, expected)
691690

692691
result = read_hdf(hh, "df", where="l1=l0")
693692
tm.assert_frame_equal(result, expected)
@@ -707,21 +706,19 @@ def test_frame_select_complex2():
707706
tm.assert_frame_equal(result, expected)
708707

709708
# scope with index
710-
store = HDFStore(hh)
711-
712-
result = store.select("df", where="l1=index")
713-
tm.assert_frame_equal(result, expected)
709+
with HDFStore(hh) as store:
714710

715-
result = store.select("df", where="l1=selection.index")
716-
tm.assert_frame_equal(result, expected)
711+
result = store.select("df", where="l1=index")
712+
tm.assert_frame_equal(result, expected)
717713

718-
result = store.select("df", where="l1=selection.index.tolist()")
719-
tm.assert_frame_equal(result, expected)
714+
result = store.select("df", where="l1=selection.index")
715+
tm.assert_frame_equal(result, expected)
720716

721-
result = store.select("df", where="l1=list(selection.index)")
722-
tm.assert_frame_equal(result, expected)
717+
result = store.select("df", where="l1=selection.index.tolist()")
718+
tm.assert_frame_equal(result, expected)
723719

724-
store.close()
720+
result = store.select("df", where="l1=list(selection.index)")
721+
tm.assert_frame_equal(result, expected)
725722

726723

727724
def test_invalid_filtering(setup_path):

pandas/tests/io/pytables/test_store.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -918,9 +918,8 @@ def do_copy(f, new_f=None, keys=None, propindexes=True, **kwargs):
918918
df = tm.makeDataFrame()
919919

920920
with tm.ensure_clean() as path:
921-
st = HDFStore(path)
922-
st.append("df", df, data_columns=["A"])
923-
st.close()
921+
with HDFStore(path) as st:
922+
st.append("df", df, data_columns=["A"])
924923
do_copy(f=path)
925924
do_copy(f=path, propindexes=False)
926925

pandas/tests/io/test_common.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -118,11 +118,11 @@ def test_get_handle_with_path(self, path_type):
118118
assert os.path.expanduser(filename) == handles.handle.name
119119

120120
def test_get_handle_with_buffer(self):
121-
input_buffer = StringIO()
122-
with icom.get_handle(input_buffer, "r") as handles:
123-
assert handles.handle == input_buffer
124-
assert not input_buffer.closed
125-
input_buffer.close()
121+
with StringIO() as input_buffer:
122+
with icom.get_handle(input_buffer, "r") as handles:
123+
assert handles.handle == input_buffer
124+
assert not input_buffer.closed
125+
assert input_buffer.closed
126126

127127
# Test that BytesIOWrapper(get_handle) returns correct amount of bytes every time
128128
def test_bytesiowrapper_returns_correct_bytes(self):

pandas/tests/io/test_compression.py

+5-6
Original file line numberDiff line numberDiff line change
@@ -282,18 +282,17 @@ def test_bzip_compression_level(obj, method):
282282
)
283283
def test_empty_archive_zip(suffix, archive):
284284
with tm.ensure_clean(filename=suffix) as path:
285-
file = archive(path, "w")
286-
file.close()
285+
with archive(path, "w"):
286+
pass
287287
with pytest.raises(ValueError, match="Zero files found"):
288288
pd.read_csv(path)
289289

290290

291291
def test_ambiguous_archive_zip():
292292
with tm.ensure_clean(filename=".zip") as path:
293-
file = zipfile.ZipFile(path, "w")
294-
file.writestr("a.csv", "foo,bar")
295-
file.writestr("b.csv", "foo,bar")
296-
file.close()
293+
with zipfile.ZipFile(path, "w") as file:
294+
file.writestr("a.csv", "foo,bar")
295+
file.writestr("b.csv", "foo,bar")
297296
with pytest.raises(ValueError, match="Multiple files found in ZIP file"):
298297
pd.read_csv(path)
299298

pandas/tests/io/test_fsspec.py

+10-12
Original file line numberDiff line numberDiff line change
@@ -95,21 +95,19 @@ def test_to_csv_fsspec_object(cleared_fs, binary_mode, df1):
9595

9696
path = "memory://test/test.csv"
9797
mode = "wb" if binary_mode else "w"
98-
fsspec_object = fsspec.open(path, mode=mode).open()
99-
100-
df1.to_csv(fsspec_object, index=True)
101-
assert not fsspec_object.closed
98+
with fsspec.open(path, mode=mode).open() as fsspec_object:
99+
df1.to_csv(fsspec_object, index=True)
100+
assert not fsspec_object.closed
102101
fsspec_object.close()
103102

104103
mode = mode.replace("w", "r")
105-
fsspec_object = fsspec.open(path, mode=mode).open()
106-
107-
df2 = read_csv(
108-
fsspec_object,
109-
parse_dates=["dt"],
110-
index_col=0,
111-
)
112-
assert not fsspec_object.closed
104+
with fsspec.open(path, mode=mode) as fsspec_object:
105+
df2 = read_csv(
106+
fsspec_object,
107+
parse_dates=["dt"],
108+
index_col=0,
109+
)
110+
assert not fsspec_object.closed
113111
fsspec_object.close()
114112

115113
tm.assert_frame_equal(df1, df2)

pandas/tests/io/test_sql.py

+19-21
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from __future__ import annotations
2020

2121
import csv
22+
from contextlib import closing
2223
from datetime import (
2324
date,
2425
datetime,
@@ -455,9 +456,8 @@ def sqlite_iris_conn(sqlite_iris_engine):
455456

456457
@pytest.fixture
457458
def sqlite_buildin():
458-
conn = sqlite3.connect(":memory:")
459-
yield conn
460-
conn.close()
459+
with sqlite3.connect(":memory:") as conn:
460+
yield conn
461461

462462

463463
@pytest.fixture
@@ -1532,13 +1532,14 @@ def test_sql_open_close(self, test_frame3):
15321532

15331533
with tm.ensure_clean() as name:
15341534

1535-
conn = self.connect(name)
1536-
assert sql.to_sql(test_frame3, "test_frame3_legacy", conn, index=False) == 4
1537-
conn.close()
1535+
with closing(self.connect(name)) as conn:
1536+
assert (
1537+
sql.to_sql(test_frame3, "test_frame3_legacy", conn, index=False)
1538+
== 4
1539+
)
15381540

1539-
conn = self.connect(name)
1540-
result = sql.read_sql_query("SELECT * FROM test_frame3_legacy;", conn)
1541-
conn.close()
1541+
with closing(self.connect(name)) as conn:
1542+
result = sql.read_sql_query("SELECT * FROM test_frame3_legacy;", conn)
15421543

15431544
tm.assert_frame_equal(test_frame3, result)
15441545

@@ -2371,18 +2372,15 @@ class Test(BaseModel):
23712372

23722373
BaseModel.metadata.create_all(self.conn)
23732374
Session = sessionmaker(bind=self.conn)
2374-
session = Session()
2375-
2376-
df = DataFrame({"id": [0, 1], "foo": ["hello", "world"]})
2377-
assert (
2378-
df.to_sql("test_frame", con=self.conn, index=False, if_exists="replace")
2379-
== 2
2380-
)
2381-
2382-
session.commit()
2383-
foo = session.query(Test.id, Test.foo)
2384-
df = DataFrame(foo)
2385-
session.close()
2375+
with Session() as session:
2376+
df = DataFrame({"id": [0, 1], "foo": ["hello", "world"]})
2377+
assert (
2378+
df.to_sql("test_frame", con=self.conn, index=False, if_exists="replace")
2379+
== 2
2380+
)
2381+
session.commit()
2382+
foo = session.query(Test.id, Test.foo)
2383+
df = DataFrame(foo)
23862384

23872385
assert list(df.columns) == ["id", "foo"]
23882386

0 commit comments

Comments
 (0)