Skip to content

Commit 1abb945

Browse files
[3.13] gh-62917: Add tests for urllib.request.urlcleanup() (GH-155446) (GH-155467)
Test that it removes temporary files created by urlretrieve() and resets the cached opener. (cherry picked from commit c44dca0) Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
1 parent 4d92c53 commit 1abb945

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

Lib/test/test_urllib.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -870,6 +870,61 @@ def test_short_content_raises_ContentTooShortError_without_reporthook(self):
870870
self.unfakehttp()
871871

872872

873+
class urlcleanup_Tests(unittest.TestCase, FakeHTTPMixin):
874+
"""Test urllib.request.urlcleanup()"""
875+
876+
def setUp(self):
877+
self.addCleanup(urllib.request.urlcleanup)
878+
879+
def urlretrieve(self):
880+
self.fakehttp(b'HTTP/1.1 200 OK\r\n\r\ndata')
881+
try:
882+
filename, headers = urllib.request.urlretrieve(
883+
support.TEST_HTTP_URL)
884+
finally:
885+
self.unfakehttp()
886+
self.addCleanup(os_helper.unlink, filename)
887+
return filename
888+
889+
def fake_urlopen(self, data):
890+
self.fakehttp(b'HTTP/1.1 200 OK\r\n\r\n' + data)
891+
try:
892+
with urllib.request.urlopen(support.TEST_HTTP_URL) as fp:
893+
return fp.read()
894+
finally:
895+
self.unfakehttp()
896+
897+
def test_temporary_files(self):
898+
filename = self.urlretrieve()
899+
self.assertTrue(os.path.exists(filename))
900+
901+
urllib.request.urlcleanup()
902+
self.assertFalse(os.path.exists(filename))
903+
904+
# A file created after the cleanup is not deleted.
905+
os_helper.create_empty_file(filename)
906+
urllib.request.urlcleanup()
907+
self.assertTrue(os.path.exists(filename))
908+
909+
def test_opener(self):
910+
# The implicitly created opener supports http.
911+
self.assertEqual(self.fake_urlopen(b'first'), b'first')
912+
913+
# An installed opener replaces it and supports only its handlers.
914+
opener = urllib.request.OpenerDirector()
915+
opener.add_handler(urllib.request.DataHandler())
916+
opener.add_handler(urllib.request.UnknownHandler())
917+
urllib.request.install_opener(opener)
918+
with urllib.request.urlopen('data:,hello') as fp:
919+
self.assertEqual(fp.read(), b'hello')
920+
with self.assertRaises(urllib.error.URLError):
921+
self.fake_urlopen(b'')
922+
923+
# urlcleanup() resets the opener.
924+
urllib.request.urlcleanup()
925+
self.assertEqual(self.fake_urlopen(b'second'), b'second')
926+
927+
873928
class QuotingTests(unittest.TestCase):
874929
r"""Tests for urllib.quote() and urllib.quote_plus()
875930

0 commit comments

Comments
 (0)