Welcome, guest | Sign In | My Account | Store | Cart
class expected:

    def __init__(self, e):
        if isinstance(e, Exception):
            self._t, self._v = e.__class__, str(e)
        elif isinstance(e, type):
            self._t, self._v = e, ""
        else:
            raise Exception("usage: with expected(Exception): ... or "
                            "with expected(Exception(\"text\")): ...")

    def __enter__(self):
        try:
            pass
        except:
            pass # this is a Python 3000 way of saying sys.exc_clear()

    def __exit__(self, t, v, tb):
        assert t is not None, "expected {0:s} to have been thrown".format(self._t.__name__)
        return t is self._t and str(v).startswith(self._v)

if __name__ == "__main__": # some examples

    with expected(ZeroDivisionError):
        1 / 0

    with expected(AssertionError("expected ZeroDivisionError to have been thrown")):
        with expected(ZeroDivisionError):
            1 / 2

    with expected(Exception("foo")):
        raise Exception("foo")

    with expected(Exception("bar")):
        with expected(Exception("foo")): # this won't catch it
            raise Exception("bar")
        assert False, "should not see me"

    with expected(Exception("can specify")):
        raise Exception("can specify prefixes")

History