Question

In a unittest I want to do something like:

result = myFunction()
self.assertFalse(result) OR self.assertRaises(Exception, myFunction)

with the idea being that if the implementation of myFunction changes to return false instead of raise an exception (or vice-versa), the test will still behave correctly (i.e. indicate a non-positive result).

Is something like this possible?

Was it helpful?

Solution

You can check if myFunction() raises a specific exception:

try:
    self.assertFalse(myFunction())
except SpecificException:
    pass

In this case if myFunction() raises SpecificException it would be silently ignored.

In other words, you would see the test failing in two cases: either myFunction() raises the exception you are not waiting for, or the result of myFunction() call doesn't evaluate to False.


In case if your function can throw any exception, you can check whether you caught an AssertionError in the except block and reraise it, silently ignoring other exceptions:

try:
    self.assertFalse(myFunction())
except AssertionError:
    raise
except:
    pass

Note that this doesn't seem very intuitive and clear to me. In an ideal world, you would need to handle these two situations separately: create a test that would make myFunction() result into False and another one that would make it raise an exception.

OTHER TIPS

You could, but that will make your test weaker. Every other unit test that uses myFunction will have to assume that it could either raise an exception or return False -- or else that test may break when the behavior changes.

Making all your other tests accomodate this uncertainty will make all those pieces of code harder to write. And for what purpose? The benefit is dubious.

Instead, make a definite test which uses assertRaises. Let the test fail if the implementation changes, and change the test then to assertFalse. That change may also cause other tests to fail, and that is a good thing. It will force you to review use cases for myFunction, and the repercussions for changing the behavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top