代碼測試

Unittest

剛剛學(xué)習(xí)了Unittest模塊,這里簡單總結(jié)下

函數(shù)測試
可通過測試
先創(chuàng)建一個(gè)要測試的代碼,name_function.py


# -*- coding:utf-8 -*-

def get_formatted_name(first, last):
    '''
    生成一個(gè)整潔的格式化全名
    1、在名和姓之間加上一個(gè)空格
    2、返回的全名首字母大寫
    '''
    full_name = first + ' ' + last
    return full_name.title()

接下來,我們創(chuàng)建一個(gè)用來檢查get_formatted_name函數(shù)在給出名和姓時(shí),能否正確地工作

  1. 這里我們創(chuàng)建了一個(gè)叫做NamesTestCase的類,它繼承自u(píng)nitest.TestCase
  2. 方法名必須以test_打頭
  3. 給get_formatted_name()方法添加了兩個(gè)參數(shù)‘jiahao’ 'shen'
  4. 使用assertEqual斷言比較formatted_name變量和后面字符串,如果相等name_function.py代碼就沒問題,如果不想等就報(bào)錯(cuò)!
# -*- coding:utf-8 -*-

import unittest
from .name_function import get_formatted_name


class NamesTestCase(unittest.TestCase):
    '''
    測試name_function.py
    '''

    def test_first_last_name(self):
        '''
        能夠正確地處理Jiahao Shen這樣的姓名么?
        '''
        formatted_name = get_formatted_name('jiahao', 'shen')
        self.assertEqual(formatted_name, 'Jiahao Shen')


if __name__ == '__mian__':
    unittest.main()

.表示有一個(gè)測試通過了,接下來一行指出python運(yùn)行了一個(gè)測試,消耗時(shí)間不到0.003秒


image

不可通過測試

這里修改下get_formatted_name函數(shù),使其能夠處理中間名

# -*- coding:utf-8 -*-

def get_formatted_name(first, middle, last):
    '''
    生成一個(gè)整潔的格式化全名
    1、在名和姓之間加上一個(gè)空格
    2、返回的全名首字母大寫
    '''
    full_name = first + ' ' + middle + ' ' + last
    return full_name.title()

再次測試代碼會(huì)出現(xiàn)報(bào)錯(cuò),它告訴你還少了一個(gè)位置參數(shù)

image

測試通過了意味著函數(shù)的行為是對(duì)的,測試未通過意味著新編寫的代碼有錯(cuò),因此測試未通過時(shí),不要修改測試,而應(yīng)該修改代碼,這里我們把中間名變成可選的來避免代碼錯(cuò)誤

修改name_function.py

# -*- coding:utf-8 -*-

def get_formatted_name(first,last, middle=''):
    '''
    生成一個(gè)整潔的格式化全名
    1、在名和姓之間加上一個(gè)空格
    2、返回的全名首字母大寫
    '''
    if middle:
        full_name = first + ' ' + middle + ' ' + last
    else:
        full_name = first + ' ' + last
    return full_name.title()

再次測試,代碼測試完成

添加新測試
在測試代碼中添加一個(gè)新方法,用于添加中間名的測試

# -*- coding:utf-8 -*-

import unittest
from .name_function import get_formatted_name


class NamesTestCase(unittest.TestCase):
    '''
    測試name_function.py
    '''

    def test_first_last_name(self):
        '''
        能夠正確地處理Jiahao Shen這樣的姓名么?
        '''
        formatted_name = get_formatted_name('jiahao', 'shen')
        self.assertEqual(formatted_name, 'Jiahao Shen')

    def test_first_last_middle_name(self):
        '''
        能夠正確處理Jiahao Shen Treehl這樣的姓名么?
        '''
        formatted_name = get_formatted_name('jiahao', 'shen', 'treehl')
        self.assertEqual(formatted_name, 'Jiahao Treehl Shen')

if __name__ == '__mian__':
    unittest.main()

再次測試,兩個(gè)測試都通過了?。?!

方法 用途
assertEqual(a, b) 核實(shí)a==b
assertNotEqual(a, b) 核實(shí)a != b
assertTrue(x) 核實(shí)x為True
assertFalse(x) 核實(shí)x為False
assertIn(item, list) 核實(shí)item在list中
assertNotIn(item, list) 核實(shí)item不在list中

類測試
先編寫一個(gè)類做測試,關(guān)于幫助管理匿名調(diào)查的類

# -*- coding:utf-8 -*-


class AnonymousSurvey():
    '''
    收集匿名調(diào)查問卷的答案
    '''

    def __init__(self, question):
        '''
        存儲(chǔ)一個(gè)問題,并為存儲(chǔ)答案做準(zhǔn)備
        1、存儲(chǔ)一個(gè)問題
        2、創(chuàng)建一個(gè)空的列表用來存儲(chǔ)答案
        '''
        self.question = question
        self.responses = []

    def show_question(self):
        '''
        顯示調(diào)查問卷
        '''
        print(self.question)

    def store_response(self, new_response):
        '''
        存儲(chǔ)單份調(diào)查問卷
        '''
        self.responses.append(new_response)

    def show_results(self):
        '''
        顯示收集到的所有答案
        '''
        print("Survey results:")
        for response in self.responses:
            print('- ' + response)

測試AnonymousSurvey類
核實(shí)單個(gè)答案的測試

# -*- coding:utf-8 -*-

import unittest
from .survey import AnonymousSurvey


class TestAnonymousSurvey(unittest.TestCase):
    '''
    針對(duì)AnonymousSurevy類的測試
    1、創(chuàng)建測試單個(gè)答案的方法test_store_single_response
    2、創(chuàng)建AnonymousSurvey實(shí)例my_survey
    3、使用assertIn來檢查Chinese是否在答案列表中
    '''

    def test_store_single_response(self):
        '''
        測試單個(gè)答案會(huì)被妥善保存
        :return:
        '''
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        my_survey.store_response('Chinese')
        self.assertIn('Chinese', my_survey.responses)

if __name__ == "__main__":
    unittest.main()

核實(shí)多個(gè)答案的測試,我們?cè)赥estAnonymouseSurvey類中再添加一個(gè)方法


    def test_store_three_responses(self):
        '''
        測試三個(gè)答案
        1、使用for循環(huán)每個(gè)答案
        2、再使用for循環(huán)來確認(rèn)每個(gè)答案都在列表內(nèi)
        '''
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        responses = ['Chinese', 'English', 'Chongming']
        for response in responses:
            my_survey.store_response(response)
        for response in responses:
            self.assertIn(response, my_survey.responses)

setUp方法

使用setUp()來創(chuàng)建一個(gè)調(diào)查對(duì)象和一組答案,供test_store_single_response()和test_store_three_responses()使用
可以在setUp()方法中創(chuàng)建一系列實(shí)例并設(shè)置它們的屬性,再在測試方法中直接使用這些實(shí)例,有點(diǎn)類似于Django中的ClassBaseView讓代碼更加容易擴(kuò)展而不是修改代碼

# -*- coding:utf-8 -*-

import unittest
from .survey import AnonymousSurvey


class TestAnonymousSurvey(unittest.TestCase):
    '''
    針對(duì)AnonymousSurevy類的測試
    1、創(chuàng)建測試單個(gè)答案的方法test_store_single_response
    2、創(chuàng)建AnonymousSurvey實(shí)例my_survey
    3、使用assertIn來檢查Chinese是否在答案列表中
    '''

    def setUp(self):
        '''
        創(chuàng)建一個(gè)調(diào)查對(duì)象和一組答案
        '''
        question = "What language didi you first learn to speak?"
        self.my_survey = AnonymousSurvey(question)
        self.responses = ['Chinese', 'English', 'France']


    def test_store_single_response(self):
        '''
        測試單個(gè)答案
        :return:
        '''
        self.my_survey.store_response(self.responses[0])
        self.assertIn(self.responses[0], self.my_survey.responses)

    def test_store_three_responses(self):
        '''
        測試三個(gè)答案
        1、使用for循環(huán)每個(gè)答案
        2、再使用for循環(huán)來確認(rèn)每個(gè)答案都在列表內(nèi)
        '''
        for response in self.responses:
            self.my_survey.store_response(response)
        for response in self.responses:
            self.assertIn(response, self.my_survey.responses)

if __name__ == "__main__":
    unittest.main()


GitHub
歡迎訪問博客Treehl的博客

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 編寫函數(shù)或類時(shí),還可為其編寫測試。通過測試,可確定代碼面對(duì)各種輸入都能夠按要求的那樣工作。在程序中添加新代碼時(shí),你...
    Darren_Lin閱讀 5,346評(píng)論 1 5
  • 在計(jì)算機(jī)編程中,單元測試(英語:Unit Testing)又稱為模塊測試, 是針對(duì)程序模塊(軟件設(shè)計(jì)的最小單位)來...
    張伯函閱讀 2,173評(píng)論 0 0
  • 主要內(nèi)容: 1.函數(shù) 2.類 3.異常處理 4.文件 8.函數(shù) 1.定義函數(shù): 使用關(guān)鍵字def來告訴python...
    起個(gè)名字真難999閱讀 543評(píng)論 0 2
  • 活了很久了,看不懂太多的故事,有時(shí)候都不能做個(gè)完整人格的人,這才是生活賦予我們最大的幸福,一直讓我追尋心中難以完成...
    三改閱讀 239評(píng)論 0 3
  • 我的謊言很笨拙,別人撒謊都是騙別人,唯獨(dú)我是騙自己。FROM 阿明 阿明下樓買煙,正付賬時(shí),阿芒推門進(jìn)來。阿明的心...
    蔚藍(lán)月光閱讀 307評(píng)論 0 0

友情鏈接更多精彩內(nèi)容