From 0e86a5842d0fadff37c299e8a1c03535c6727b19 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Fri, 25 Nov 2011 18:03:09 +0100 Subject: [PATCH] Issue #9957: SpooledTemporaryFile.truncate() now accepts an optional size parameter, as other file-like objects. Patch by Ryan Kelly. --- Lib/tempfile.py | 9 +++++++-- Lib/test/test_tempfile.py | 21 +++++++++++++++++++++ Misc/NEWS | 4 +++- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/Lib/tempfile.py b/Lib/tempfile.py index 3ec6b4a3da9..e3afa3b0ac0 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -578,8 +578,13 @@ class SpooledTemporaryFile: 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 --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py index 014fca01a99..5b0bca797e9 100644 --- a/Lib/test/test_tempfile.py +++ b/Lib/test/test_tempfile.py @@ -846,6 +846,27 @@ class test_SpooledTemporaryFile(TC): 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 --git a/Misc/NEWS b/Misc/NEWS index f78a31eec70..93169e4608b 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -386,10 +386,12 @@ Core and Builtins - 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.