詳解Python之unittest單元測試代碼
前言
編寫函數(shù)或者類時,還可以為其編寫測試。通過測試,可確定代碼面對各種輸入都能夠按要求的那樣工作。
本次我將介紹如何使用Python模塊unittest中的工具來測試代碼。
測試函數(shù)
首先我們先編寫一個簡單的函數(shù),它接受姓、名、和中間名三個參數(shù),并返回完整的姓名:
names.py
def get_fullname(firstname,lastname,middel=''):
'''創(chuàng)建全名'''
if middel:
full_name = firstname + ' ' + middel + ' ' + lastname
return full_name.title()
else:
full_name = firstname + ' ' + lastname
return full_name.title()
然后再當(dāng)前目錄下編寫調(diào)用函數(shù)程序
get_name.py
from names import get_fullname
message = "Please input 'q' to quit."
print(message)
while True:
first = input("Please input your firstname: ")
if first == 'q':
break
last = input("Please input your lastname: ")
if last == 'q':
break
middels = input("Please input your middel name or None: ")
if last == 'q':
break
formant_name = get_fullname(first,last,middels)
print("\tYour are fullname is: " + formant_name.title())
調(diào)用結(jié)果:
Please input 'q' to quit.
進程已結(jié)束,退出代碼0
Please input your firstname: xiao
Please input your lastname: peng
Please input your middel or None:
Your are fullname is: Xiao Peng
Please input your firstname: xiao
Please input your lastname: peng
Please input your middel or None: you
Your are fullname is: Xiao You Peng
Please input your firstname: q
創(chuàng)建測試程序
創(chuàng)建測試用例的語法需要一段時間才能習(xí)慣,但測試用例創(chuàng)建后,再針對函數(shù)的單元測試就很簡單了。先導(dǎo)入模塊unittest以及要測試的函數(shù),再創(chuàng)建一個繼承函數(shù)unittest.TestCase的類,
并編寫一系列方法對函數(shù)行為的不同方便進行測試。
下面介紹測試上面names.py函數(shù)是否能夠正確的獲取姓名:
Test_get_name.py
import unittest
from names import get_fullname
class NamesTestCase(unittest.TestCase):
'''定義測試類'''
def test_get_name2(self):
'''測試2個字的名字'''
formatied_name2 = get_fullname('xiao','pengyou')
self.assertEqual(formatied_name2,'Xiao Pengyou')
def test_get_name3(self):
'''測試3個字的名字'''
formatied_name3 = get_fullname('xiao','peng',middel='you')
self.assertEqual(formatied_name3,'Xiao Peng You')
if __name__ == '__init__':
unittest.main()
測試結(jié)果:
Ran 2 tests in 0.034s
OK
兩個測試單元測試通過測試!
在當(dāng)前的大目錄下會生成一個測試報告,可以通過瀏覽器進行打開查看。

由圖可知,兩個測試通過,并顯示測試的時間?。。?/p>
unittest.TestCase的各種斷言方法
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中 |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python?plotly設(shè)置go.Scatter為實線實例
這篇文章主要為大家介紹了python?plotly設(shè)置go.Scatter為實線線條的樣式實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10
Python實踐之使用Pandas進行數(shù)據(jù)分析
在數(shù)據(jù)分析領(lǐng)域,Python的Pandas庫是一個非常強大的工具。這篇文章將為大家詳細(xì)介紹如何使用Pandas進行數(shù)據(jù)分析,希望對大家有所幫助2023-04-04
Python實現(xiàn)杰卡德距離以及環(huán)比算法講解
這篇文章主要為大家介紹了Python實現(xiàn)杰卡德距離以及環(huán)比算法的示例講解,有需要的朋友可以借鑒參考下2022-02-02

