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 =====


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...