[Tutor] Proper way to unit test the raising of exceptions?

Mats Wichmann mats at wichmann.us
Sun Apr 1 11:31:38 EDT 2018


On 04/01/2018 09:10 AM, Peter Otten wrote:
> Simon Connah via Tutor wrote:
> 
>> Hi,
>> I'm just wondering what the accepted way to handle unit testing exceptions
>> is? I know you are meant to use assertRaises, but my code seems a little
>> off. 
> 
>> try:
>>     some_func()
>> except SomeException:   
>>     self.assertRaises(SomeException) 
> 
> The logic is wrong here as you surmise below. If you catch the exception 
> explicitly you have to write
> 
> try:
>     some_func()
> except SomeException:
>     pass  # OK
> else:
>     self.fail("no exception raised")


If you use PyTest, the procedure is pretty well documented:

https://docs.pytest.org/en/latest/assert.html



More information about the Tutor mailing list