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

Skip to content

Commit ea5d827

Browse files
committed
Merged revisions 85503 via svnmerge from
svn+ssh://[email protected]/python/branches/py3k ........ r85503 | antoine.pitrou | 2010-10-15 00:11:44 +0200 (ven., 15 oct. 2010) | 2 lines More proper closing of files ........
1 parent 3d400b7 commit ea5d827

7 files changed

Lines changed: 83 additions & 58 deletions

File tree

Lib/doctest.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,8 @@ def _load_testfile(filename, package, module_relative, encoding):
214214
# get_data() opens files as 'rb', so one must do the equivalent
215215
# conversion as universal newlines would do.
216216
return file_contents.replace(os.linesep, '\n'), filename
217-
return open(filename, encoding=encoding).read(), filename
217+
with open(filename, encoding=encoding) as f:
218+
return f.read(), filename
218219

219220
def _indent(s, indent=4):
220221
"""
@@ -2503,7 +2504,8 @@ def debug_script(src, pm=False, globs=None):
25032504

25042505
if pm:
25052506
try:
2506-
exec(open(srcfilename).read(), globs, globs)
2507+
with open(srcfilename) as f:
2508+
exec(f.read(), globs, globs)
25072509
except:
25082510
print(sys.exc_info()[1])
25092511
pdb.post_mortem(sys.exc_info()[2])

Lib/test/test_decimal.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -218,14 +218,15 @@ def eval_file(self, file):
218218
if skip_expected:
219219
raise unittest.SkipTest
220220
return
221-
for line in open(file):
222-
line = line.replace('\r\n', '').replace('\n', '')
223-
#print line
224-
try:
225-
t = self.eval_line(line)
226-
except DecimalException as exception:
227-
#Exception raised where there shoudn't have been one.
228-
self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line)
221+
with open(file) as f:
222+
for line in f:
223+
line = line.replace('\r\n', '').replace('\n', '')
224+
#print line
225+
try:
226+
t = self.eval_line(line)
227+
except DecimalException as exception:
228+
#Exception raised where there shoudn't have been one.
229+
self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line)
229230

230231
return
231232

Lib/test/test_modulefinder.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -204,11 +204,17 @@ def open_file(path):
204204

205205
def create_package(source):
206206
ofi = None
207-
for line in source.splitlines():
208-
if line.startswith(" ") or line.startswith("\t"):
209-
ofi.write(line.strip() + "\n")
210-
else:
211-
ofi = open_file(os.path.join(TEST_DIR, line.strip()))
207+
try:
208+
for line in source.splitlines():
209+
if line.startswith(" ") or line.startswith("\t"):
210+
ofi.write(line.strip() + "\n")
211+
else:
212+
if ofi:
213+
ofi.close()
214+
ofi = open_file(os.path.join(TEST_DIR, line.strip()))
215+
finally:
216+
if ofi:
217+
ofi.close()
212218

213219
class ModuleFinderTest(unittest.TestCase):
214220
def _do_test(self, info, report=False):

Lib/test/test_multibytecodec.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ def test_errorcallback_longindex(self):
4949
def test_codingspec(self):
5050
try:
5151
for enc in ALL_CJKENCODINGS:
52-
print('# coding:', enc, file=io.open(TESTFN, 'w'))
53-
exec(open(TESTFN).read())
52+
code = '# coding: {}\n'.format(enc)
53+
exec(code)
5454
finally:
5555
support.unlink(TESTFN)
5656

Lib/test/test_multibytecodec_support.py

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ class TestBase_Mapping(unittest.TestCase):
277277
def __init__(self, *args, **kw):
278278
unittest.TestCase.__init__(self, *args, **kw)
279279
try:
280-
self.open_mapping_file() # test it to report the error early
280+
self.open_mapping_file().close() # test it to report the error early
281281
except IOError:
282282
self.skipTest("Could not retrieve "+self.mapfileurl)
283283

@@ -294,36 +294,38 @@ def _test_mapping_file_plain(self):
294294
unichrs = lambda s: ''.join(map(chr, map(eval, s.split('+'))))
295295
urt_wa = {}
296296

297-
for line in self.open_mapping_file():
298-
if not line:
299-
break
300-
data = line.split('#')[0].strip().split()
301-
if len(data) != 2:
302-
continue
303-
304-
csetval = eval(data[0])
305-
if csetval <= 0x7F:
306-
csetch = bytes([csetval & 0xff])
307-
elif csetval >= 0x1000000:
308-
csetch = bytes([(csetval >> 24), ((csetval >> 16) & 0xff),
309-
((csetval >> 8) & 0xff), (csetval & 0xff)])
310-
elif csetval >= 0x10000:
311-
csetch = bytes([(csetval >> 16), ((csetval >> 8) & 0xff),
312-
(csetval & 0xff)])
313-
elif csetval >= 0x100:
314-
csetch = bytes([(csetval >> 8), (csetval & 0xff)])
315-
else:
316-
continue
297+
with self.open_mapping_file() as f:
298+
for line in f:
299+
if not line:
300+
break
301+
data = line.split('#')[0].strip().split()
302+
if len(data) != 2:
303+
continue
304+
305+
csetval = eval(data[0])
306+
if csetval <= 0x7F:
307+
csetch = bytes([csetval & 0xff])
308+
elif csetval >= 0x1000000:
309+
csetch = bytes([(csetval >> 24), ((csetval >> 16) & 0xff),
310+
((csetval >> 8) & 0xff), (csetval & 0xff)])
311+
elif csetval >= 0x10000:
312+
csetch = bytes([(csetval >> 16), ((csetval >> 8) & 0xff),
313+
(csetval & 0xff)])
314+
elif csetval >= 0x100:
315+
csetch = bytes([(csetval >> 8), (csetval & 0xff)])
316+
else:
317+
continue
317318

318-
unich = unichrs(data[1])
319-
if ord(unich) == 0xfffd or unich in urt_wa:
320-
continue
321-
urt_wa[unich] = csetch
319+
unich = unichrs(data[1])
320+
if ord(unich) == 0xfffd or unich in urt_wa:
321+
continue
322+
urt_wa[unich] = csetch
322323

323-
self._testpoint(csetch, unich)
324+
self._testpoint(csetch, unich)
324325

325326
def _test_mapping_file_ucm(self):
326-
ucmdata = self.open_mapping_file().read()
327+
with self.open_mapping_file() as f:
328+
ucmdata = f.read()
327329
uc = re.findall('<a u="([A-F0-9]{4})" b="([0-9A-F ]+)"/>', ucmdata)
328330
for uni, coded in uc:
329331
unich = chr(int(uni, 16))

Lib/test/test_pipes.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,43 +23,53 @@ def testSimplePipe1(self):
2323
f = t.open(TESTFN, 'w')
2424
f.write('hello world #1')
2525
f.close()
26-
self.assertEqual(open(TESTFN).read(), 'HELLO WORLD #1')
26+
with open(TESTFN) as f:
27+
self.assertEqual(f.read(), 'HELLO WORLD #1')
2728

2829
def testSimplePipe2(self):
29-
open(TESTFN, 'w').write('hello world #2')
30+
with open(TESTFN, 'w') as f:
31+
f.write('hello world #2')
3032
t = pipes.Template()
3133
t.append(s_command + ' < $IN > $OUT', pipes.FILEIN_FILEOUT)
3234
t.copy(TESTFN, TESTFN2)
33-
self.assertEqual(open(TESTFN2).read(), 'HELLO WORLD #2')
35+
with open(TESTFN2) as f:
36+
self.assertEqual(f.read(), 'HELLO WORLD #2')
3437

3538
def testSimplePipe3(self):
36-
open(TESTFN, 'w').write('hello world #2')
39+
with open(TESTFN, 'w') as f:
40+
f.write('hello world #2')
3741
t = pipes.Template()
3842
t.append(s_command + ' < $IN', pipes.FILEIN_STDOUT)
3943
self.assertEqual(t.open(TESTFN, 'r').read(), 'HELLO WORLD #2')
4044

4145
def testEmptyPipeline1(self):
4246
# copy through empty pipe
4347
d = 'empty pipeline test COPY'
44-
open(TESTFN, 'w').write(d)
45-
open(TESTFN2, 'w').write('')
48+
with open(TESTFN, 'w') as f:
49+
f.write(d)
50+
with open(TESTFN2, 'w') as f:
51+
f.write('')
4652
t=pipes.Template()
4753
t.copy(TESTFN, TESTFN2)
48-
self.assertEqual(open(TESTFN2).read(), d)
54+
with open(TESTFN2) as f:
55+
self.assertEqual(f.read(), d)
4956

5057
def testEmptyPipeline2(self):
5158
# read through empty pipe
5259
d = 'empty pipeline test READ'
53-
open(TESTFN, 'w').write(d)
60+
with open(TESTFN, 'w') as f:
61+
f.write(d)
5462
t=pipes.Template()
5563
self.assertEqual(t.open(TESTFN, 'r').read(), d)
5664

5765
def testEmptyPipeline3(self):
5866
# write through empty pipe
5967
d = 'empty pipeline test WRITE'
6068
t = pipes.Template()
61-
t.open(TESTFN, 'w').write(d)
62-
self.assertEqual(open(TESTFN).read(), d)
69+
with t.open(TESTFN, 'w') as f:
70+
f.write(d)
71+
with open(TESTFN) as f:
72+
self.assertEqual(f.read(), d)
6373

6474
def testQuoting(self):
6575
safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./'

Lib/test/test_shutil.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -217,15 +217,17 @@ def test_dont_copy_file_onto_link_to_itself(self):
217217

218218
os.link(src, dst)
219219
self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
220-
self.assertEqual(open(src,'r').read(), 'cheddar')
220+
with open(src, 'r') as f:
221+
self.assertEqual(f.read(), 'cheddar')
221222
os.remove(dst)
222223

223224
# Using `src` here would mean we end up with a symlink pointing
224225
# to TESTFN/TESTFN/cheese, while it should point at
225226
# TESTFN/cheese.
226227
os.symlink('cheese', dst)
227228
self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
228-
self.assertEqual(open(src,'r').read(), 'cheddar')
229+
with open(src, 'r') as f:
230+
self.assertEqual(f.read(), 'cheddar')
229231
os.remove(dst)
230232
finally:
231233
try:
@@ -307,9 +309,11 @@ def tearDown(self):
307309
pass
308310

309311
def _check_move_file(self, src, dst, real_dst):
310-
contents = open(src, "rb").read()
312+
with open(src, "rb") as f:
313+
contents = f.read()
311314
shutil.move(src, dst)
312-
self.assertEqual(contents, open(real_dst, "rb").read())
315+
with open(real_dst, "rb") as f:
316+
self.assertEqual(contents, f.read())
313317
self.assertFalse(os.path.exists(src))
314318

315319
def _check_move_dir(self, src, dst, real_dst):

0 commit comments

Comments
 (0)