一、unittest測試模塊
此小實驗已經傳至github,喜歡的朋友們給個star喔~
單元測試小實驗
總結
setUp()函數:相當於定義的全局變量,裏面變量對以下的函數都有效
score是字典類型,傳字典類型需要加**
部分代碼如下:
import unittest
from test.Student import Student as Student
class UnitTest_Student(unittest.TestCase):
def setUp(self):
self.score = {
"語文":90,
"數學":80,
"歷史":80,
"地理":70,
"生物":80
}
self.stu = Student("Joy",20,"女",**self.score)
self.meanscore = sum(self.stu.score.values()) / len(self.stu.score.values())
def test_name(self):
self.assertEqual(self.stu.name,"Joy")
def test_age(self):
self.assertEqual(self.stu.age, 20)
def test_sex(self):
self.assertEqual(self.stu.sex, "女")
def test_score(self):
self.assertEqual(self.stu.score,self.score)
def test_mean(self):
self.assertEqual(self.meanscore ,(90+80+80+80+70)/5)
def Down(self):
del(self.score )
del(self.stu)
del(self.meanscore)
常用斷言如下
其他的斷言請參考python文檔
python的斷言文檔
二、異常處理
其except後接的error提示可參考官方文檔
Built-in Exceptions官方文檔
三、數值打印格式處理(如小數)
四、隨機函數
五、日期及時間
import datetime
today = datetime.date.today() #獲取今天的日期
birthday = datetime.date(1995,6,7)
now = datetime.datetime.today() #獲取今天的日期和時間
s = '1996-3-15'
t = datetime.datetime.strptime(s,'%Y-%m-%d') #字符串轉成日期格式
txt = t.strftime('%Y/%m/%d') #日期格式轉字符串格式
cha = today - birthday #可得出總天數和總秒數
later = birthday + datetime.timedelta(days = 100) #往後計算
front = birthday + datetime.timedelta(days = -100) #往過去計算