Skip to content

Commit 10702eb

Browse files
[3.14] gh-62917: Add tests for urllib.request.urlcleanup() (GH-155446) (GH-155466)
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 b54c346 commit 10702eb

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
@@ -807,6 +807,61 @@ def test_short_content_raises_ContentTooShortError_without_reporthook(self):
807807
self.unfakehttp()
808808

809809

810+
class urlcleanup_Tests(unittest.TestCase, FakeHTTPMixin):
811+
"""Test urllib.request.urlcleanup()"""
812+
813+
def setUp(self):
814+
self.addCleanup(urllib.request.urlcleanup)
815+
816+
def urlretrieve(self):
817+
self.fakehttp(b'HTTP/1.1 200 OK\r\n\r\ndata')
818+
try:
819+
filename, headers = urllib.request.urlretrieve(
820+
support.TEST_HTTP_URL)
821+
finally:
822+
self.unfakehttp()
823+
self.addCleanup(os_helper.unlink, filename)
824+
return filename
825+
826+
def fake_urlopen(self, data):
827+
self.fakehttp(b'HTTP/1.1 200 OK\r\n\r\n' + data)
828+
try:
829+
with urllib.request.urlopen(support.TEST_HTTP_URL) as fp:
830+
return fp.read()
831+
finally:
832+
self.unfakehttp()
833+
834+
def test_temporary_files(self):
835+
filename = self.urlretrieve()
836+
self.assertTrue(os.path.exists(filename))
837+
838+
urllib.request.urlcleanup()
839+
self.assertFalse(os.path.exists(filename))
840+
841+
# A file created after the cleanup is not deleted.
842+
os_helper.create_empty_file(filename)
843+
urllib.request.urlcleanup()
844+
self.assertTrue(os.path.exists(filename))
845+
846+
def test_opener(self):
847+
# The implicitly created opener supports http.
848+
self.assertEqual(self.fake_urlopen(b'first'), b'first')
849+
850+
# An installed opener replaces it and supports only its handlers.
851+
opener = urllib.request.OpenerDirector()
852+
opener.add_handler(urllib.request.DataHandler())
853+
opener.add_handler(urllib.request.UnknownHandler())
854+
urllib.request.install_opener(opener)
855+
with urllib.request.urlopen('data:,hello') as fp:
856+
self.assertEqual(fp.read(), b'hello')
857+
with self.assertRaises(urllib.error.URLError):
858+
self.fake_urlopen(b'')
859+
860+
# urlcleanup() resets the opener.
861+
urllib.request.urlcleanup()
862+
self.assertEqual(self.fake_urlopen(b'second'), b'second')
863+
864+
810865
class QuotingTests(unittest.TestCase):
811866
r"""Tests for urllib.quote() and urllib.quote_plus()
812867

0 commit comments

Comments
 (0)