Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you test that a Python function throws an exception?

How does one write a unittest that fails only if a function doesn't throw an expected exception?

like image 769
Daryl Spitzer Avatar asked Sep 24 '08 20:09

Daryl Spitzer


People also ask

How do you catch exceptions in Python?

Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

What is throwing an exception in Python?

Sometimes you want Python to throw a custom exception for error handling. You can do this by checking a condition and raising the exception, if the condition is true. The raised exception typically warns the user or the calling application. You use the “raise” keyword to throw a Python exception manually.


1 Answers

Use TestCase.assertRaises (or TestCase.failUnlessRaises) from the unittest module, for example:

import mymod  class MyTestCase(unittest.TestCase):     def test1(self):         self.assertRaises(SomeCoolException, mymod.myfunc) 
like image 155
Moe Avatar answered Sep 23 '22 15:09

Moe