一、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) #往过去计算