前言
編寫函數(shù)或者類時,還可以為其編寫測試。通過測試,可確定代碼面對各種輸入都能夠按要求的那樣工作。
本次我將介紹如何使用Python模塊unittest中的工具來測試代碼。
測試函數(shù)
首先我們先編寫一個簡單的函數(shù),它接受姓、名、和中間名三個參數(shù),并返回完整的姓名:
names.py
1
2
3
4
5
6
7
8
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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)前的大目錄下會生成一個測試報告,可以通過瀏覽器進行打開查看。
由圖可知,兩個測試通過,并顯示測試的時間!!!
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í)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/JeremyWYL/p/8340316.html