Skip to content

Commit e056976

Browse files
authored
Merge pull request #33 from Eddy114514/truncate
Add warning for truncate(0)
2 parents 10528e1 + a209c93 commit e056976

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

Lib/test/test_py2xwarn.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
from test.support.warnings_helper import check_py2x_warnings
44
import warnings
55
from test import test_support
6+
import tempfile
7+
68

79
if not sys.py2x_warning:
810
raise unittest.SkipTest('%s must be run with the -2 flag' % __name__)
@@ -35,6 +37,16 @@ def test_next(self):
3537
self.assertWarning(iterator_marks.next(), w, expected)
3638
w.reset()
3739
self.assertNoWarning(iterator_marks.__next__(), w)
40+
41+
def test_truncate0(self):
42+
expected = "Calling truncate(0) on text stream without seek(0)" + \
43+
" may produce inconsistent results. Use seek(0) before truncate(0)"
44+
with check_py2x_warnings(("", Py2xWarning)) as w:
45+
with tempfile.NamedTemporaryFile("w+", encoding="utf-8", delete=True) as f:
46+
f.write("test")
47+
f.truncate(0)
48+
self.assertWarning((), w, expected)
49+
3850

3951
if __name__ == '__main__':
4052
unittest.main()

Modules/_io/textio.c

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2846,6 +2846,26 @@ _io_TextIOWrapper_truncate_impl(textio *self, PyObject *pos)
28462846
return NULL;
28472847
Py_DECREF(res);
28482848

2849+
if(Py_Py2xWarningFlag){
2850+
if (pos != Py_None && PyLong_Check(pos)) {
2851+
if (PyLong_AsLong(pos) == 0) {
2852+
PyObject *sres = PyObject_CallMethod((PyObject *)self, "seek", "i", 0);
2853+
if (sres == NULL)
2854+
return NULL;
2855+
Py_DECREF(sres);
2856+
if (PyErr_WarnEx(PyExc_Py2xWarning,
2857+
"Calling truncate(0) on text stream without seek(0)"
2858+
" may produce inconsistent results. Use seek(0) before truncate(0)",
2859+
2
2860+
) < 0){
2861+
return NULL;
2862+
}
2863+
}
2864+
2865+
}
2866+
2867+
}
2868+
28492869
return PyObject_CallMethodOneArg(self->buffer, &_Py_ID(truncate), pos);
28502870
}
28512871

0 commit comments

Comments
 (0)