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

Skip to content

Commit 79b79ee

Browse files
committed
Patch # 1323 by Amaury Forgeot d'Arc.
This patch corrects a problem in test_file.py on Windows: f.truncate() seeks to the truncation point, but does not empty the buffers. In the test, f.tell() returns -1...
1 parent 687b9c0 commit 79b79ee

2 files changed

Lines changed: 23 additions & 9 deletions

File tree

Lib/io.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -597,9 +597,24 @@ def tell(self):
597597
return self.raw.tell()
598598

599599
def truncate(self, pos=None):
600+
# On Windows, the truncate operation changes the current position
601+
# to the end of the file, which may leave us with desynchronized
602+
# buffers.
603+
# Since we promise that truncate() won't change the current position,
604+
# the easiest thing is to capture current pos now and seek back to
605+
# it at the end.
606+
607+
initialpos = self.tell()
600608
if pos is None:
601-
pos = self.tell()
602-
return self.raw.truncate(pos)
609+
pos = initialpos
610+
611+
# Flush the stream. We're mixing buffered I/O with lower-level I/O,
612+
# and a flush may be necessary to synch both views of the current
613+
# file state.
614+
self.flush()
615+
newpos = self.raw.truncate(pos)
616+
self.seek(initialpos)
617+
return newpos
603618

604619
### Flush and close ###
605620

Lib/test/test_file.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -181,12 +181,13 @@ def testSetBufferSize(self):
181181
self.assertEquals(d, s)
182182

183183
def testTruncateOnWindows(self):
184+
# SF bug <http://www.python.org/sf/801631>
185+
# "file.truncate fault on windows"
186+
184187
os.unlink(TESTFN)
188+
f = open(TESTFN, 'wb')
185189

186-
def bug801631():
187-
# SF bug <http://www.python.org/sf/801631>
188-
# "file.truncate fault on windows"
189-
f = open(TESTFN, 'wb')
190+
try:
190191
f.write(b'12345678901') # 11 bytes
191192
f.close()
192193

@@ -205,10 +206,8 @@ def bug801631():
205206
size = os.path.getsize(TESTFN)
206207
if size != 5:
207208
self.fail("File size after ftruncate wrong %d" % size)
208-
209-
try:
210-
bug801631()
211209
finally:
210+
f.close()
212211
os.unlink(TESTFN)
213212

214213
def testIteration(self):

0 commit comments

Comments
 (0)