How do you state that two functions throw the same error without being aware of the error?

I have an outer function that calls an inner function passing in arguments. Is it possible to check that both functions are throwing the same exception / error without knowing the exact type of error?

I am looking for something like:

def test_invalidInput_throwsSameError(self):
    arg = 'invalidarg'
    self.assertRaisesSameError(
        innerFunction(arg),
        outerFunction(arg)
    )

      

+3


source to share


3 answers


Assuming you are using unittest

(and python2.7 or newer), and that you are not doing something pathological, such as collecting old-style class instances as errors, you might get an exception from the error context if you use assertRaises

as the context manager ...



with self.assertRaises(Exception) as err_context1:
    innerFunction(arg)

with self.assertRaises(Exception) as err_context2:
    outerFunction(arg)

# Or some other measure of "sameness"
self.assertEqual(
    type(err_context1.exception),
    type(err_context2.exception))

      

+7


source


First, call the first function and write down what exception it raises:

try:
    innerfunction(arg)
except Exception as e:
    pass
else:
    e = None

      



They then assert that the other function is throwing the same exception:

 self.assertRaises(e, outerfunction, arg)

      

+1


source


I believe this will do what you want; just add it as another method of your TestCase class:

def assertRaisesSameError(self, *funcs, bases=(Exception,)):
    exceptions = []

    for func in funcs:
        with self.assertRaises(base) as error_context:
            func()
            exceptions.append(error_context.exception)

    for exc in exceptions:
        self.assertEqual(type(exc), type(exc[-1]))

      

I haven't tested this, but it should work. For simplicity, this only accepts functions with no arguments, so if your function has arguments, you will have to create a wrapper (even with a lambda). It would not be easy to expand this so that it would be possible to go to * args and ** kwargs.

Let me know about any changes anyone might think.

0


source







All Articles