Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b476d59

Browse files
committed
Add __enter__ and __exit__ methods to addbase() so that it supports with.
This change also adds a minimal unittest of urllib.response.addbase. More are needed, but not to cover the small change being made here. Addresses http://bugs.python.org/issue5418
1 parent 81fac43 commit b476d59

2 files changed

Lines changed: 50 additions & 0 deletions

File tree

Lib/test/test_urllib_response.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""Unit tests for code in urllib.response."""
2+
3+
import test.support
4+
import urllib.response
5+
import unittest
6+
7+
class TestFile(object):
8+
9+
def __init__(self):
10+
self.closed = False
11+
12+
def read(self, bytes):
13+
pass
14+
15+
def readline(self):
16+
pass
17+
18+
def close(self):
19+
self.closed = True
20+
21+
class Testaddbase(unittest.TestCase):
22+
23+
# TODO(jhylton): Write tests for other functionality of addbase()
24+
25+
def setUp(self):
26+
self.fp = TestFile()
27+
self.addbase = urllib.response.addbase(self.fp)
28+
29+
def test_with(self):
30+
def f():
31+
with self.addbase as spam:
32+
pass
33+
self.assertFalse(self.fp.closed)
34+
f()
35+
self.assertTrue(self.fp.closed)
36+
self.assertRaises(ValueError, f)
37+
38+
def test_main():
39+
test.support.run_unittest(Testaddbase)
40+
41+
if __name__ == '__main__':
42+
test_main()

Lib/urllib/response.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,14 @@ def close(self):
4040
if self.fp: self.fp.close()
4141
self.fp = None
4242

43+
def __enter__(self):
44+
if self.fp is None:
45+
raise ValueError("I/O operation on closed file")
46+
return self
47+
48+
def __exit__(self, type, value, traceback):
49+
self.close()
50+
4351
class addclosehook(addbase):
4452
"""Class to add a close hook to an open file."""
4553

0 commit comments

Comments
 (0)