[Python-checkins] cpython (3.2): Issue #12400: runtest() truncates the StringIO stream before a new test

Terry Reedy tjreedy at udel.edu
Wed Jun 29 19:25:59 CEST 2011



On 6/29/2011 1:05 PM, Terry Reedy wrote:
> On 6/29/2011 11:30 AM, victor.stinner wrote:

>> if runtest.stringio is None:
>> runtest.stringio = io.StringIO()
>> stream = runtest.stringio
>> + stream.truncate(0)
>
> You *MUST* seek to 0 to reset the file position, which I presume is your
> intention. 'Resize' does not mean what you probably think is does (and
> what I thought once either ;-).
>
> "truncate(size=None)
> Resize the stream to the given size in bytes (or the current position if
> size is not specified). The current stream position isn’t changed."
>
>  >>> s=io.StringIO()
>  >>> s.write('abc')
> 3
>  >>> s.truncate(0)
> 0
>  >>> s.tell()
> 3
>  >>> s.write('abc')
> 3
>  >>> s.getvalue()
> '\x00\x00\x00abc'

What I did was wrap .getvalue, .seek, and .truncate in a function (which 
also tested the gotten value for equality with expected) so that the 
StringIO object was reset and ready to use at the end of every test 
(restoring the invariant) and therefore ready at the beginning of every 
test. If I forget to get,test,and restore at the end of a test, then the 
next test is screwed, which is good since it catches the bug of omission.

The equivalent for runtest would be

def _assert_sio_equal(expected):
   sio = runtest.stringio
   actual = sio.getvalue()
   sio.seek(0)
   sio.truncate()
   AssertEqual(actual,expected) # or viceversa according to convention

Terry




More information about the Python-checkins mailing list