Skip to content

Commit 4571846

Browse files
committed
Update tarfile tests to use context managers
1 parent 15216b9 commit 4571846

File tree

1 file changed

+15
-21
lines changed

1 file changed

+15
-21
lines changed

Lib/test/test_tarfile.py

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -694,10 +694,11 @@ def test_extract_hardlink(self):
694694
def test_extractall(self):
695695
# Test if extractall() correctly restores directory permissions
696696
# and times (see issue1735).
697-
tar = tarfile.open(tarname, encoding="iso8859-1")
698-
DIR = os.path.join(TEMPDIR, "extractall")
699-
os.mkdir(DIR)
700-
try:
697+
DIR = pathlib.Path(TEMPDIR) / "extractall"
698+
with (
699+
os_helper.temp_dir(DIR),
700+
tarfile.open(tarname, encoding="iso8859-1") as tar
701+
):
701702
directories = [t for t in tar if t.isdir()]
702703
tar.extractall(DIR, directories, filter='fully_trusted')
703704
for tarinfo in directories:
@@ -718,31 +719,24 @@ def format_mtime(mtime):
718719
format_mtime(file_mtime),
719720
path)
720721
self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
721-
finally:
722-
tar.close()
723-
os_helper.rmtree(DIR)
724722

725723
@staticmethod
726-
@unittest.mock.patch("tarfile.data_filter", wraps=tarfile.data_filter)
727-
@unittest.mock.patch("tarfile.tar_filter", wraps=tarfile.tar_filter)
728-
@unittest.mock.patch("tarfile.fully_trusted_filter", wraps=tarfile.fully_trusted_filter)
729-
def test_extractall_default_filter(mock_ft_filter: unittest.mock.Mock,
730-
mock_tar_filter: unittest.mock.Mock,
731-
mock_data_filter: unittest.mock.Mock):
732-
tar = tarfile.open(tarname, encoding="iso8859-1")
733-
DIR = os.path.join(TEMPDIR, "extractall_default_filter")
734-
os.mkdir(DIR)
735-
try:
724+
def test_extractall_default_filter():
725+
# Test that the default filter is now "data", and the other filter types are not used.
726+
DIR = pathlib.Path(TEMPDIR) / "extractall_default_filter"
727+
with (
728+
os_helper.temp_dir(DIR),
729+
tarfile.open(tarname, encoding="iso8859-1") as tar,
730+
unittest.mock.patch("tarfile.data_filter", wraps=tarfile.data_filter) as mock_data_filter,
731+
unittest.mock.patch("tarfile.tar_filter", wraps=tarfile.tar_filter) as mock_tar_filter,
732+
unittest.mock.patch("tarfile.fully_trusted_filter", wraps=tarfile.fully_trusted_filter) as mock_ft_filter
733+
):
736734
directories = [t for t in tar if t.isdir()]
737735
tar.extractall(DIR, directories)
738736

739-
# Test that the default filter is now "data", and the other filter types are not used.
740737
mock_data_filter.assert_called()
741738
mock_ft_filter.assert_not_called()
742739
mock_tar_filter.assert_not_called()
743-
finally:
744-
tar.close()
745-
os_helper.rmtree(DIR)
746740

747741
@os_helper.skip_unless_working_chmod
748742
def test_extract_directory(self):

0 commit comments

Comments
 (0)