Beispiel #1
0
def test_broken_getattr_handling():
    """
    Test subiterator with a broken getattr implementation
    """
    import _io, sys

    class Broken:
        def __iter__(self):
            return self

        def __next__(self):
            return 1

        def __getattr__(self, attr):
            1 / 0

    def g():
        yield from Broken()

    gi = g()
    assert next(gi) == 1
    with raises(ZeroDivisionError):
        gi.send(1)

    gi = g()
    assert next(gi) == 1
    with raises(ZeroDivisionError):
        gi.throw(RuntimeError)

    gi = g()
    assert next(gi) == 1
    sys.stderr = _io.StringIO()
    gi.close()
    assert 'ZeroDivisionError' in sys.stderr.getvalue()
Beispiel #2
0
 def packtabs(self, s, tabsize=8):
     if tabsize > 0:
         sb = _io.StringIO()
         for i in range(0, len(s), tabsize):
             c = s[i:i + tabsize]
             cr = c.rstrip(" ")
             if c != cr:  # Spaces at the end of a section
                 sb.write(cr + "\t")  # replace by tab
             else:
                 sb.write(c)
         return sb.getvalue()
     else:
         return s
Beispiel #3
0
def print_exc(e):
    buf = io.StringIO()
    print_exception(e, buf)
    s = buf.getvalue()
    for l in s.split("\n"):
        # uPy on pyboard prints <stdin> as file, so remove filename.
        if l.startswith("  File "):
            l = l.split('"')
            print(l[0], l[2])
        # uPy and CPy tracebacks differ in that CPy prints a source line for
        # each traceback entry. In this case, we know that offending line
        # has 4-space indent, so filter it out.
        elif not l.startswith("    "):
            print(l)
Beispiel #4
0
 def expandtabs(self, s, tabsize=8):
     import _io
     if '\t' in s and tabsize > 0:
         sb = _io.StringIO()
         pos = 0
         for c in s:
             if c == '\t':  # tab is seen
                 sb.write(" " * (tabsize - pos % tabsize))  # replace by space
                 pos += tabsize - pos % tabsize
             else:
                 sb.write(c)
                 pos += 1
         return sb.getvalue()
     else:
         return s
Beispiel #5
0
    def test_excepthook_failsafe_path(self):
        import traceback
        original_print_exception = traceback.print_exception
        import sys, _io
        savestderr = sys.stderr
        err = _io.StringIO()
        sys.stderr = err
        try:
            traceback.print_exception = "foo"
            eh = sys.__excepthook__
            try:
                raise ValueError(42)
            except ValueError as exc:
                eh(*sys.exc_info())
        finally:
            traceback.print_exception = original_print_exception
            sys.stderr = savestderr

        assert err.getvalue() == "ValueError: 42\n"
Beispiel #6
0
    def test_original_excepthook(self):
        import sys, _io
        savestderr = sys.stderr
        err = _io.StringIO()
        sys.stderr = err

        eh = sys.__excepthook__

        raises(TypeError, eh)
        try:
            raise ValueError(42)
        except ValueError as exc:
            eh(*sys.exc_info())
        assert err.getvalue().endswith("ValueError: 42\n")

        eh(1, '1', 1)
        expected = ("TypeError: print_exception(): Exception expected for "
                    "value, str found")
        assert expected in err.getvalue()

        sys.stderr = savestderr
Beispiel #7
0
    def test_original_displayhook(self):
        import sys, _io, builtins
        savestdout = sys.stdout
        out = _io.StringIO()
        sys.stdout = out

        dh = sys.__displayhook__

        raises(TypeError, dh)
        if hasattr(builtins, "_"):
            del builtins._

        dh(None)
        assert out.getvalue() == ""
        assert not hasattr(builtins, "_")
        dh("hello")
        assert out.getvalue() == "'hello'\n"
        assert builtins._ == "hello"

        del sys.stdout
        raises(RuntimeError, dh, 42)

        sys.stdout = savestdout
Beispiel #8
0
import _io as io

# test __enter__/__exit__
with io.StringIO() as b:
    b.write("foo")
    print(b.getvalue())
Beispiel #9
0
 def test_stringio_overwrite(self):
     s = _io.StringIO('hello')
     s.seek(2)
     s.write('ab')
     self.assertEqual('heabo', s.getvalue())
Beispiel #10
0
import _io as io

a = io.StringIO()
print(a.getvalue())
print(a.read())

a = io.StringIO("foobar")
print(a.getvalue())
print(a.read())
print(a.read())

a = io.StringIO()
a.write("foo")
print(a.getvalue())

a = io.StringIO("foo")
a.write("12")
print(a.getvalue())

a = io.StringIO("foo")
a.write("123")
print(a.getvalue())

a = io.StringIO("foo")
a.write("1234")
print(a.getvalue())

a = io.StringIO()
a.write("foo")
print(a.read())
Beispiel #11
0
# This tests that printing recursive data structure doesn't lead to segfault.
import _io as io

l = [1, 2, 3, None]
l[-1] = l
try:
    print(l, file=io.StringIO())
except RuntimeError:
    print("RuntimeError")
Beispiel #12
0
import _io as io  # uPy does not have io module builtin
import sys
if hasattr(sys, 'print_exception'):
    print_exception = sys.print_exception
else:
    import traceback
    print_exception = lambda e, f: traceback.print_exception(
        None, e, None, file=f)

try:
    XXX
except Exception as e:
    print('caught')
    buf = io.StringIO()
    print_exception(e, buf)
    s = buf.getvalue()
    for l in s.split("\n"):
        # uPy on pyboard prints <stdin> as file, so remove filename.
        if l.startswith("  File "):
            print(l[:8], l[-23:])
        # uPy and CPy tracebacks differ in that CPy prints a source line for
        # each traceback entry. In this case, we know that offending line
        # has 4-space indent, so filter it out.
        elif not l.startswith("    "):
            print(l)