From b4fd46260f0e83d4243c8778bd5a128aa48e45fe Mon Sep 17 00:00:00 2001 From: AN Long Date: Tue, 6 May 2025 00:17:28 +0900 Subject: [PATCH 1/2] Fix test_file in test_urllib2 on Windows with a longer repo path --- Lib/test/test_urllib2.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py index 7d7f2fa00d35b6..96f474b6641b11 100644 --- a/Lib/test/test_urllib2.py +++ b/Lib/test/test_urllib2.py @@ -850,14 +850,16 @@ def test_file(self): self.assertEqual(headers["Last-modified"], modified) self.assertEqual(respurl, canonurl) + _, cwd = os.path.splitdrive(os.getcwd()) + cwd = cwd.replace("\\", "/") for url in [ parsed._replace(netloc='localhost:80').geturl(), "file:///file_does_not_exist.txt", "file://not-a-local-host.com//dir/file.txt", "file://%s:80%s/%s" % (socket.gethostbyname('localhost'), - os.getcwd(), TESTFN), + cwd, TESTFN), "file://somerandomhost.ontheinternet.com%s/%s" % - (os.getcwd(), TESTFN), + (cwd, TESTFN), ]: try: f = open(TESTFN, "wb") From 985fee07a82d846197d58750ee904be9cdc17b3f Mon Sep 17 00:00:00 2001 From: AN Long Date: Sat, 6 Sep 2025 02:45:30 +0900 Subject: [PATCH 2/2] Update by review --- Lib/test/test_urllib2.py | 25 ++++++++----------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py index 96f474b6641b11..fa03186c5554b6 100644 --- a/Lib/test/test_urllib2.py +++ b/Lib/test/test_urllib2.py @@ -850,28 +850,19 @@ def test_file(self): self.assertEqual(headers["Last-modified"], modified) self.assertEqual(respurl, canonurl) - _, cwd = os.path.splitdrive(os.getcwd()) - cwd = cwd.replace("\\", "/") + with open(TESTFN, "wb") as f: + f.write(towrite) + self.addCleanup(os.remove, TESTFN) for url in [ parsed._replace(netloc='localhost:80').geturl(), "file:///file_does_not_exist.txt", "file://not-a-local-host.com//dir/file.txt", - "file://%s:80%s/%s" % (socket.gethostbyname('localhost'), - cwd, TESTFN), - "file://somerandomhost.ontheinternet.com%s/%s" % - (cwd, TESTFN), + "file://%s:80%s" % (socket.gethostbyname('localhost'), + urllib.request.pathname2url(os.path.join(os.getcwd(), TESTFN))), + "file://somerandomhost.ontheinternet.com%s" % + urllib.request.pathname2url(os.path.join(os.getcwd(), TESTFN)), ]: - try: - f = open(TESTFN, "wb") - try: - f.write(towrite) - finally: - f.close() - - self.assertRaises(urllib.error.URLError, - h.file_open, Request(url)) - finally: - os.remove(TESTFN) + self.assertRaises(urllib.error.URLError, h.file_open, Request(url)) h = urllib.request.FileHandler() o = h.parent = MockOpener()