2018年8月7日 星期二

[ Python 常見問題 ] How do you test that a Python function throws an exception?

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

How-To 
Use TestCase.assertRaises (or TestCase.failUnlessRaises) from the unittest module, for example: 
- TestExp.py 
  1. #!/usr/bin/env python3  
  2. import unittest  
  3.   
  4. def my_fun(val):  
  5.     if val % 2 == 0:  
  6.         raise Exception('Val is even')  
  7.     else:  
  8.         return "Val is odd"  
  9.   
  10. class MyTestCase(unittest.TestCase):  
  11.     def test_01(self):  
  12.         self.assertEquals("Val is odd", my_fun(1))  
  13.   
  14.     def test_02(self):  
  15.         # Even number will raise Exception  
  16.         self.assertRaises(Exception, my_fun, 2)  
  17.   
  18.         # You can leverage with this way  
  19.         with self.assertRaises(Exception) as context:  
  20.             my_fun(4)  
  21.   
  22.         self.assertTrue('Val is even' in str(context.exception))  
Running example: 
# pytest -s TestExp.py 
... 
platform linux -- Python 3.5.0, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 
rootdir: /tmp, inifile: 
plugins: celery-4.1.0 
collected 2 items 
... 
===== 2 passed in 0.02 seconds =====


沒有留言:

張貼留言

[ JS 常見問題 ] Javascript Date output formatting

Source From  Here   Question   I need to  capture the Now() date and time in the YYYY/mm/dd hh:m:sec format . It needs to be in GMT time. Ho...