Python單元測試

2021-09-25 09:12:51 字數 2277 閱讀 9980

本文章整理自:

使用python3.6編寫乙個單元測試demo,例如:對學生student類編寫乙個簡單的單元測試。

1、編寫student類:

#!/usr/bin/env python3

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

class student(object):

def __init__(self,name,score):

self.name = name

self.score = score

def get_grade(self):

if self.score >= 80 and self.score <= 100:

return 'a'

elif self.score >= 60 and self.score <= 79:

return 'b'

elif self.score >= 0 and self.score <= 59:

return 'c'

else:

raise valueerror('value is not between 0 and 100')

2、編寫乙個測試類teststudent,從unittest.testcase繼承:

#!/usr/bin/env python3

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

import unittest

from student import student

class teststudent(unittest.testcase):

def test_80_to_100(self):

s1 = student('bart',80)

s2 = student('lisa',100)

self.assertequal(s1.get_grade(),'a')

self.assertequal(s2.get_grade(),'a')

def test_60_to_80(self):

s1 = student('bart',60)

s2 = student('lisa',79)

self.assertequal(s1.get_grade(),'b')

self.assertequal(s2.get_grade(),'b')

def test_0_to_60(self):

s1 = student('bart',0)

s2 = student('lisa',59)

self.assertequal(s1.get_grade(),'c')

self.assertequal(s2.get_grade(),'c')

def test_invalid(self):

s1 = student('bart',-1)

s2 = student('lisa',101)

with self.assertraises(valueerror):

s1.get_grade()

with self.assertraises(valueerror):

s2.get_grade()

3、執行單元測試**檔案時,要在命令列中操作。示意如下:

4、行單元測試另一種方法:在命令列通過引數-m unittest直接執行單元測試,例如:python -m unittest student_test

最後對使用unittest模組的一些總結:

編寫單元測試時,需要編寫乙個測試類,從unittest.testcase繼承

對每乙個類測試都需要編寫乙個test_***()方法

最常用的斷言就是assertequal()

另一種重要的斷言就是期待丟擲指定型別的error,eg:with self.assertraises(keyerror):

另一種方法是在命令列通過引數-m unittest直接執行單元測試:eg:python -m unittest student_test

最簡單的執行方式是xx.py的最後加上兩行**:

if __name__ == '__main__':

unittest.main()

Python 單元測試

一 假設我們編寫了一段程式,主要功能是完成阿拉伯數字和羅馬數字之間的轉換 在羅馬數字中,利用7個字母進行重複或者組合來表達各式各樣的數字 i 1 v 5 x 10 l 50 c 100 d 500 m 1000 還有一些關於構造羅馬數字的規則。此程式的框架如下 其中,class romanerror...

python 單元測試

assertequal a,b assertnotequal a,b 斷言值是否相等 assertis a,b assertisnot a,b 斷言是否同一物件 記憶體位址一樣 assertlistequal list1,list2 assertitemnotequal list1,list2 斷言...

Python單元測試

在python的圈子裡常流行一句話 動態一時爽,重構火葬場 我們知道python寫起來很方便,但在重構或者對某部分 修改時,可能會造成 牽一髮而動全身 所以對於python專案,特別是大型專案來說單元測試來保證 質量是非常有必要的。單元測試 unit testing 1.針對程式模組進行正確性檢驗 ...