python 面向对象入门 - 之 单元测试

来源:互联网 发布:怎样成为淘宝卖家 编辑:程序博客网 时间:2024/05/17 04:14
详细代码见附件 

Java代码  收藏代码
  1. """Unit test for odbchelper.py  
  2. This program is part of "Dive Into Python", a free Python book for  
  3. experienced programmers.  Visit http://diveintopython.org/ for the  
  4. latest version.  
  5. """  
  6.   
  7. #加载单元测试模块  
  8. import unittest  
  9. #加载 你的编写的模块  
  10. import odbchelper  
  11. #测试中包括:  
  12. #1.正面测试  
  13. #2.负面测试  
  14. #3.完备性测试:A状态->B状态 ->A状态  
  15.   
  16.   
  17. #正面测试  
  18. class GoodInput(unittest.TestCase): #这里要继承 unittest.TestCase  
  19.     #编写测试用例,以test 开头  
  20.     def testBlank(self):  
  21.         """buildConnectionString handles empty dictionary"""  
  22.         self.assertEqual("", odbchelper.buildConnectionString({}))  
  23.     def testKnownValue(self):  
  24.         """buildConnectionString returns known result with known input"""  
  25.         params = {"server":"mpilgrim""database":"master""uid":"sa""pwd":"secret"}  
  26.         knownItems = params.items()  
  27.         knownItems.sort()  
  28.         knownString = repr(knownItems)  
  29.         result = odbchelper.buildConnectionString(params)  
  30.         resultItems = [tuple(e.split("=")) for e in result.split(";")]  
  31.         resultItems.sort()  
  32.         resultString = repr(resultItems)  
  33.         self.assertEqual(knownString, resultString)  
  34.   
  35. #负面测试  
  36. class BadInput(unittest.TestCase):  
  37.     def testString(self):  
  38.         """buildConnectionString should fail with string input"""  
  39.         self.assertRaises(AttributeError, odbchelper.buildConnectionString, "")  
  40.   
  41.     def testList(self):  
  42.         """buildConnectionString should fail with list input"""  
  43.         self.assertRaises(AttributeError, odbchelper.buildConnectionString, [])  
  44.   
  45.     def testTuple(self):  
  46.         """buildConnectionString should fail with tuple input"""  
  47.         self.assertRaises(AttributeError, odbchelper.buildConnectionString, ())  
  48.   
  49. if __name__ == "__main__":  
  50.     unittest.main()  
原创粉丝点击