Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python unittest - opposite of assertRaises?

I want to write a test to establish that an Exception is not raised in a given circumstance.

It's straightforward to test if an Exception is raised ...

sInvalidPath=AlwaysSuppliesAnInvalidPath() self.assertRaises(PathIsNotAValidOne, MyObject, sInvalidPath)  

... but how can you do the opposite.

Something like this i what I'm after ...

sValidPath=AlwaysSuppliesAValidPath() self.assertNotRaises(PathIsNotAValidOne, MyObject, sValidPath)  
like image 811
glaucon Avatar asked Nov 30 '10 23:11

glaucon


People also ask

Is PyUnit the same as Unittest?

PyUnit is an easy way to create unit testing programs and UnitTests with Python. (Note that docs.python.org uses the name "unittest", which is also the module name.)

How do you handle exceptions in unit test Python?

assertRaises(exception, callable, *args, **kwds) Test that an exception (first argument) is raised when a function is called with any positional or keyword arguments. The test passes if the expected exception is raised, is an error if another exception is raised, or fails if no exception is raised.

Is Pytest better than Unittest?

Which is better – pytest or unittest? Although both the frameworks are great for performing testing in python, pytest is easier to work with. The code in pytest is simple, compact, and efficient. For unittest, we will have to import modules, create a class and define the testing functions within that class.

How do you test try and except in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.


2 Answers

def run_test(self):     try:         myFunc()     except ExceptionType:         self.fail("myFunc() raised ExceptionType unexpectedly!") 
like image 190
DGH Avatar answered Sep 20 '22 07:09

DGH


Hi - I want to write a test to establish that an Exception is not raised in a given circumstance.

That's the default assumption -- exceptions are not raised.

If you say nothing else, that's assumed in every single test.

You don't have to actually write an any assertion for that.

like image 39
S.Lott Avatar answered Sep 19 '22 07:09

S.Lott