Skip to content

Commit 100e234

Browse files
Warn for truncate
1 parent 50b46c5 commit 100e234

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

Lib/test/test_py3kwarn.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,14 @@ def test_file_xreadlines(self):
308308
with check_py3k_warnings() as w:
309309
self.assertWarning(f.xreadlines(), w, expected)
310310

311+
def test_bytesio_truncate(self):
312+
from io import BytesIO
313+
x = BytesIO(b'AAAAAA')
314+
expected = "BytesIO.truncate() does not shift the file pointer: use seek(0) before doing truncate(0)"
315+
self.assertWarning(x.truncate(0), w, expected)
316+
w.reset()
317+
self.assertNoWarning(x.truncate(-1), w)
318+
311319
def test_file_open(self):
312320
expected = ("The builtin 'file()'/'open()' function is not supported in 3.x, "
313321
"use the 'io.open()' function instead with the encoding keyword argument")

Modules/_io/bytesio.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,10 @@ bytesio_truncate(bytesio *self, PyObject *args)
447447
size = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
448448
if (size == -1 && PyErr_Occurred())
449449
return NULL;
450+
if (size == 0 && PyErr_WarnPy3k_WithFix("BytesIO.truncate() does not shift the file pointer",
451+
"use seek(0) before doing truncate(0)", 1) < 0){
452+
return NULL;
453+
}
450454
}
451455
else if (arg == Py_None) {
452456
/* Truncate to current position if no argument is passed. */

0 commit comments

Comments
 (0)