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

Simon Connah sc_opensource at yahoo.com
Sun Apr 1 12:14:11 EDT 2018


 Awesome. Thank you all. Your solutions are great and should make the whole process a lot more simple.
The only problem is that some_func() on my end is Django model with about 8 named arguments so it might be a bit of a pain passing all of those arguments.
The context manager example seems like a perfect fit for that particular problem.
Thanks again. All of your help is much appreciated.
    On Sunday, 1 April 2018, 16:32:11 BST, Mats Wichmann <mats at wichmann.us> wrote:  
 
 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

_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
  


More information about the Tutor mailing list