From 1847c774472857fc9543d5c0b2212fb48b269d27 Mon Sep 17 00:00:00 2001 From: Matthew Treinish Date: Mon, 7 Mar 2016 10:47:11 -0500 Subject: [PATCH] Add new decorator to raise xfail on known exceptions This commit adds a new decorator to TestCase that will take in a exception class and when it's raised by a test it will be converted to _ExpectedFailure. If a different exception is raised by the test it will just passthrough and be handled like normal. --- testtools/testcase.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/testtools/testcase.py b/testtools/testcase.py index 1e131eeb..cb782baa 100644 --- a/testtools/testcase.py +++ b/testtools/testcase.py @@ -108,6 +108,27 @@ def wrapper(*args, **kwargs): return wrapper +def xfail_on_exc(*args, **kwargs): + """A test decorator to catch a specific exception and handle it as xfail. + + If an exception is raised other than the expected exception type it will + passthrough and be handled like normal. + + :param Exception exc: The exception class to catch and treat as + """ + def decorator(f): + if len(args) == 0: + raise TypeError('A expected exception needs to be provided') + expected_exception = args[0] + @functools.wraps(func) + def wrapper(self, *func_args, **func_kwargs): + try: + func(*func_args, **func_kwargs) + except expected_exception: + raise _ExpectedFailure(sys.exc_info()) + return wrapper + + def run_test_with(test_runner, **kwargs): """Decorate a test as using a specific ``RunTest``.