Files
zaqar/marconi/tests/util/helpers.py
kgriffs 8b31b2e9b0 refactor: Hoist helpers.expect into package namespace
It's silly to have to import a package's submodule directly,
since in this case that only introduces another module name
that the developer has to keep track of, just to gain access
to a solitary function. This patch hoists
marconi.tests.util.helpers.expect into marocni.tests.util so
that it can be referenced more naturally by the test author.

Accordingly, the Hacking.rst guide has been updated to allow
this sort of thing (with some discretion).

Implements: blueprint grizzly-debt
Change-Id: Iad2e4f728aa4826d99bec2c599e2947a87eb5945
2013-05-07 18:00:14 -04:00

47 lines
1.6 KiB
Python

# Copyright (c) 2013 Rackspace Hosting, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import contextlib
@contextlib.contextmanager
def expect(*exc_type):
"""A context manager to validate raised expections.
Can be used as an alternative to testtools.ExpectedException.
Notable differences:
1. This context manager accepts child classes of the
given type, testing that an "except" statement
referencing the given type would indeed catch it when
raised by the statement(s) defined inside the context.
2. When the expected exception (or a child thereof) is
not raised, this context manager *always* raises
an AssertionError, both when a different exception
is raised, and when no exception is raised at all.
:param *exc_type: Exception type(s) expected to be raised during
execution of the "with" context.
"""
assert len(exc_type) > 0
try:
yield
except exc_type:
pass
else:
raise AssertionError(
'Not raised: %s' % ', '.join(e.__name__ for e in exc_type))