pythonunit-testingstringiostubs

Python's StringIO doesn't do well with `with` statements


I need to stub tempfile and StringIO seemed perfect. Only that all this fails in an omission:

In [1]: from StringIO import StringIO
In [2]: with StringIO("foo") as f: f.read()

--> AttributeError: StringIO instance has no attribute '__exit__'

What's the usual way to provide canned info instead of reading files with nondeterministic content?


Solution

  • The StringIO module predates the with statement. Since StringIO has been removed in Python 3 anyways, you can just use its replacement, io.BytesIO:

    >>> import io
    >>> with io.BytesIO(b"foo") as f: f.read()
    b'foo'