Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you assert two functions throw the same error without knowing the error?

I have an outer function that calls an inner function by passing the arguments along. Is it possible to test that both functions throw the same exception/error without knowing the exact error type?

I'm looking for something like:

def test_invalidInput_throwsSameError(self):
    arg = 'invalidarg'
    self.assertRaisesSameError(
        innerFunction(arg),
        outerFunction(arg)
    )
like image 702
neverendingqs Avatar asked Dec 01 '25 05:12

neverendingqs


2 Answers

Assuming you're using unittest (and python2.7 or newer) and that you're not doing something pathological like raising old-style class instances as errors, you can get the exception from the error context if you use assertRaises as a 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))
like image 83
mgilson Avatar answered Dec 03 '25 17:12

mgilson


First call the first function and capture what exception it raises:

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

Then assert that the other function raises the same exception:

 self.assertRaises(e, outerfunction, arg)
like image 27
kindall Avatar answered Dec 03 '25 18:12

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!