From 100e2346198b304cf4c05ec3a0c5034f1b211912 Mon Sep 17 00:00:00 2001 From: Joannah Nanjekye Date: Fri, 14 Apr 2023 06:35:58 -0300 Subject: [PATCH] Warn for truncate --- Lib/test/test_py3kwarn.py | 8 ++++++++ Modules/_io/bytesio.c | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/Lib/test/test_py3kwarn.py b/Lib/test/test_py3kwarn.py index a5fe68ab7e3c06..517c1826c8a7ed 100644 --- a/Lib/test/test_py3kwarn.py +++ b/Lib/test/test_py3kwarn.py @@ -308,6 +308,14 @@ def test_file_xreadlines(self): with check_py3k_warnings() as w: self.assertWarning(f.xreadlines(), w, expected) + def test_bytesio_truncate(self): + from io import BytesIO + x = BytesIO(b'AAAAAA') + expected = "BytesIO.truncate() does not shift the file pointer: use seek(0) before doing truncate(0)" + self.assertWarning(x.truncate(0), w, expected) + w.reset() + self.assertNoWarning(x.truncate(-1), w) + def test_file_open(self): expected = ("The builtin 'file()'/'open()' function is not supported in 3.x, " "use the 'io.open()' function instead with the encoding keyword argument") diff --git a/Modules/_io/bytesio.c b/Modules/_io/bytesio.c index 0ee4b80434c804..289aaf3e9d410b 100644 --- a/Modules/_io/bytesio.c +++ b/Modules/_io/bytesio.c @@ -447,6 +447,10 @@ bytesio_truncate(bytesio *self, PyObject *args) size = PyNumber_AsSsize_t(arg, PyExc_OverflowError); if (size == -1 && PyErr_Occurred()) return NULL; + if (size == 0 && PyErr_WarnPy3k_WithFix("BytesIO.truncate() does not shift the file pointer", + "use seek(0) before doing truncate(0)", 1) < 0){ + return NULL; + } } else if (arg == Py_None) { /* Truncate to current position if no argument is passed. */