(original) (raw)
changeset: 73737:5a6911930bad user: Antoine Pitrou solipsis@pitrou.net date: Fri Nov 25 18:03:09 2011 +0100 files: Lib/tempfile.py Lib/test/test_tempfile.py Misc/NEWS description: Issue #9957: SpooledTemporaryFile.truncate() now accepts an optional size parameter, as other file-like objects. Patch by Ryan Kelly. diff -r 905b6f1eca74 -r 5a6911930bad Lib/tempfile.py --- a/Lib/tempfile.py Fri Nov 25 16:34:23 2011 +0100 +++ b/Lib/tempfile.py Fri Nov 25 18:03:09 2011 +0100 @@ -578,8 +578,13 @@ def tell(self): return self._file.tell() - def truncate(self): - self._file.truncate() + def truncate(self, size=None): + if size is None: + self._file.truncate() + else: + if size > self._max_size: + self.rollover() + self._file.truncate(size) def write(self, s): file = self._file diff -r 905b6f1eca74 -r 5a6911930bad Lib/test/test_tempfile.py --- a/Lib/test/test_tempfile.py Fri Nov 25 16:34:23 2011 +0100 +++ b/Lib/test/test_tempfile.py Fri Nov 25 18:03:09 2011 +0100 @@ -846,6 +846,27 @@ pass self.assertRaises(ValueError, use_closed) + def test_truncate_with_size_parameter(self): + # A SpooledTemporaryFile can be truncated to zero size + f = tempfile.SpooledTemporaryFile(max_size=10) + f.write(b'abcdefg\n') + f.seek(0) + f.truncate() + self.assertFalse(f._rolled) + self.assertEqual(f._file.getvalue(), b'') + # A SpooledTemporaryFile can be truncated to a specific size + f = tempfile.SpooledTemporaryFile(max_size=10) + f.write(b'abcdefg\n') + f.truncate(4) + self.assertFalse(f._rolled) + self.assertEqual(f._file.getvalue(), b'abcd') + # A SpooledTemporaryFile rolls over if truncated to large size + f = tempfile.SpooledTemporaryFile(max_size=10) + f.write(b'abcdefg\n') + f.truncate(20) + self.assertTrue(f._rolled) + if has_stat: + self.assertEqual(os.fstat(f.fileno()).st_size, 20) test_classes.append(test_SpooledTemporaryFile) diff -r 905b6f1eca74 -r 5a6911930bad Misc/NEWS --- a/Misc/NEWS Fri Nov 25 16:34:23 2011 +0100 +++ b/Misc/NEWS Fri Nov 25 18:03:09 2011 +0100 @@ -386,10 +386,12 @@ - Issue #12380: The rjust, ljust and center methods of bytes and bytearray now accept a bytearray argument. - Library ------- +- Issue #9957: SpooledTemporaryFile.truncate() now accepts an optional size + parameter, as other file-like objects. Patch by Ryan Kelly. + - Issue #13458: Fix a memory leak in the ssl module when decoding a certificate with a subjectAltName. Patch by Robert Xiao. /solipsis@pitrou.net