Python中单元测试出错了,会怎么样?
在上一篇中,我們看到了單元測試正常通過時的情況,如果我們邊修改一下要測試的函數,然后再運行單元測試,會出現什么情況。
原say_hello_name.py
1 def hello_name(name): 2 greet = "Hello , " 3 return greet + name.title()修改后say_hello_name.py
1 def hello_name(first_name,last_name): 2 greet = "Hello , " 3 return greet + first_name.title() + ' ' + last_name.title()修改后的問候語句,不止包含名字,還包含姓,然后我們運行測試類HelloTest,看下效果:
test_say_hello.py
#coding=gbk import unittestfrom say_hello_function import hello_nameclass HelloTest(unittest.TestCase):"""用于測試say_hello_function.py"""def test_hello_name(self):"""是否能正確處理Joker 這個名字"""hello_str = hello_name('Joker')self.assertEqual(hello_str,'Hello , Joker')unittest.main()運行后如下:
解釋:我們發現控制臺報錯了,且包含很多信息,因為測試 未通過時,Python得讓你盡可能多的知道為什么錯,第一行字母E,表示測試用例中有一個單元測試導致錯誤。
第二行 ERROR: test_hello_name (__main__.HelloTest) 可以看出是HelloTest 中的test_hello_name 方法導致了錯誤。而在圖中Traceback 更明確的指出了錯誤的位置,hello_name()缺少了一個必須的位置實參 來對應形參 last_name。倒數第2行,表示運行了一個單元測試。最后還看到了一條消息FAILED它表示整個測試用例都未通過,因為在運行測試用例的時候發生了一個錯誤。
這樣我們就很清楚的知道了錯誤的位置,我們既然知道錯誤的位置接下來如何去做?
優化函數hello_name():讓這個函數技能接收兩個實參,也能接收一個實參,這樣就不會出錯了,具體修改如下:
最終版say_hello_name.py
1 def hello_name(first_name,last_name=""): 2 greet = "Hello , " 3 if last_name: 4 return greet + first_name.title() + ' ' + last_name.title() 5 else : 6 return greet + first_name.title()在這個最終版中,姓是可選的,不管是只有名字還是包含姓和名字都能進行處理,我們添加一個新測試來測試包含姓和名字的新功能,修改測試類如下:
test_say_hello.py
#coding=gbk import unittestfrom say_hello_function import hello_nameclass HelloTest(unittest.TestCase):"""用于測試say_hello_function.py"""def test_hello_name(self):"""是否能正確處理Joker 這個名字"""hello_str = hello_name('Joker')self.assertEqual(hello_str,'Hello , Joker')def test_hello_first_last(self):"""能否正確處理Joker Pan這個姓名"""hello_str1 = hello_name('joker','pan')self.assertEqual(hello_str1,'Hello , Joker Pan')unittest.main()運行后控制臺打印如下:
額,運氣真好,測試用例都通過了,所以在最終版中,函數hello_name()既可以處理Joker 這樣的名字也可以處理Joker Pan 這樣的姓名,而且我們無需手動去測試此函數。在此函數中添加新功能時,我們就很容易修復完善此函數,因為只要未通過的測試,我們就知道新代碼破壞了函數原來的行為。
?
附上unittest中常用的斷言方法(如果想用這些方法,前提是你導入了unittest模塊)
| 方法 | 作用 |
| assertEqual(a,b) | 核實 a == b |
| assertNotEqual(a,b) | 核實? a != b |
| assertTrue(x) | 核實x為True |
| assertFalse(x) | 核實x為False |
| assertIn(item,list) | 核實 item 在list中 |
| assertNotIn(item,list) | 核實 item不在 list中 |
?
轉載于:https://www.cnblogs.com/tizer/p/11087012.html
總結
以上是生活随笔為你收集整理的Python中单元测试出错了,会怎么样?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: g3220cpu相当于i几
- 下一篇: python之美_Python之美[从菜