执行篇
单元测试的执行 (通过特定的框架进行测试代码的过程)
unittest框架的使用
Python语言编写一个运算的类(Calc),类中包含两个函数:
1) sum(self,a,b) 返回a+b之和
2) sub(self,a,c) 返回a-c之差
#新建类 calc
class Calc():
#定义类函数sum
def sum(self,a,b):
return a+b
#定义类函数sub
def sub(self,a,b):
return a-b
if __name__ == '__main__':
print(Calc().sum(1,2))
print(Calc().sub(2,2))
import unittest#导入unittest包
from Cs.case.t616_0 import Calc#导入calc
#新建单元测试类
class Test(unittest.TestCase):
def setUp(self):
print('setup被运行')
def test_sub(self):
result=Calc().sub(20,20)
self.assertEqual(result,0)#添加断言
print('test_sub 被执行')
def test_sum(self):
result=Calc().sum(20,10)
self.assertEqual(result,30)#添加断言
print('test_sum被执行')
if __name__ == '__main__':
unittest.main()#执行测试
参数化(数据分离:解决大量数据测试问题)
参数化方式
1.XML格式XML是一种标记语句,很类似HTML标记语言;后缀 .xml
<?xml version="1.0" encoding="utf-8" ?>
<SJX>
<bian>
<b1>3</b1>>
<b2>3</b2>>
<b3>4</b3>>
</bian>>
</SJX>
对三角形案例单元测试使用XML格式进行参数化
class Sjx():
def Sjx(self,a,b,c):
#判断是否三角形
if a+b>c and a+c >b and b+c>a:
if a==b and b==c:
return "等边三角形"
elif a==b or b==c or a==c:
return "等腰三角形"
else:
return "普通三角形"
else:
return "不是三角形"
if __name__ == '__main__':
print(Sjx().Sjx(2,2,1))
#导入minidom
from xml.dom import minidom
class Read_xml():
def readxml(self,node,number,nodeChild):
#解析文档
dom=minidom.parse("../database/sjx.xml")
#获取文档对象
root=dom.documentElement
#获取bian元素
element=root.getElementsByTagName(node)[int(number)]
#获取制定元素边元素
return element.getElementsByTagName(nodeChild)[0].firstChild.data
def get_len(self,node):
# 解析文档
dom = minidom.parse("../database/sjx.xml")
# 获取文档对象
root = dom.documentElement
# 获取bian元素
return len(root.getElementsByTagName(node))
if __name__ == '__main__':
print(Read_xml().readxml("bian",0,"b2"))
print(Read_xml().get_len('bian'))
<?xml version="1.0" encoding="utf-8" ?>
<SJX>
<bian>
<b1>3</b1>>
<b2>3</b2>>
<b3>3</b3>>
<expect>等边三角形</expect>
</bian>>
<bian>
<b1>2</b1>>
<b2>3</b2>>
<b3>4</b3>>
<expect>普通三角形</expect>
<bian>
<b1>3</b1>>
<b2>3</b2>>
<b3>4</b3>>
<expect>等腰三角形</expect>
</bian>>
<bian>
<b1>2</b1>>
<b2>2</b2>>
<b3>3</b3>>
<expect>等腰三角形</expect>
</bian>>
<bian>
<b1>4</b1>>
<b2>4</b2>>
<b3>5</b3>>
<expect>等腰三角形</expect>
</bian>>
<bian>
<b1>1</b1>>
<b2>1</b2>>
<b3>2</b3>>
<expect>不是三角形</expect>
</bian>>
<bian>
<b1>2</b1>>
<b2>2</b2>>
<b3>4</b3>>
<expect>不是三角形</expect>
</bian>>
<bian>
<b1>3</b1>>
<b2>3</b2>>
<b3>6</b3>>
<expect>不是三角形</expect>
</bian>>
</bian>>
</SJX>
#导包 unittest、三角形函数、读取xml
import unittest
from Cs.case.sjx_616 import Sjx
from Cs.Readdate.read_xml import Read_xml
#实例化三角形
sjxclass=Sjx()
#实例化读取xml
readclass=Read_xml()
class Testxml(unittest.TestCase):
def test01(self):
for i in range(readclass.get_len("bian")):
#测试三角形程序
result = sjxclass.Sjx(int(readclass.readxml("bian", i, "b1")),
int(readclass.readxml("bian", i, "b2")),
int(readclass.readxml("bian", i, "b3"))
)
self.assertEqual(result, readclass.readxml("bian", i, "expect"))
print(readclass.readxml("bian", i, "b1"),
readclass.readxml("bian", i, "b2"),
readclass.readxml("bian", i, "b3"),
readclass.readxml("bian", i, "expect"), "——》验证通过")
2.CSV是一种以逗号做分割的表格格式; 后缀 .csv
text文本改为CSV格式即可
读取csv
#导包
import csv
#打开
class ReadCsv():
def readcsv(self):
#打开CSV
with open('../database/sjx.csv','r',encoding='utf-8') as f:
dates=csv.reader(f)
# 新建空列表
lines = []
for date in dates:
lines.append(date)
return lines
if __name__ == '__main__':
print(ReadCsv().readcsv())
#导包 三角形函数 CSV
import unittest
from Cs.case.sjx_616 import Sjx
from Cs.Readdate.read_csv import ReadCsv
#实例化三角形
sjxclass=Sjx()
#实例化读取
readcsv=ReadCsv()
class Test(unittest.TestCase):
def test(self):
for i in range(len(readcsv.readcsv())):
result=sjxclass.Sjx(int(readcsv.readcsv()[i][0]),
int(readcsv.readcsv()[i][1]),
int(readcsv.readcsv()[i][2]))
#断言
self.assertEqual(result,readcsv.readcsv()[i][3])
print(readcsv.readcsv()[i][0],
readcsv.readcsv()[i][1],
readcsv.readcsv()[i][2],
readcsv.readcsv()[i][3],"------>验证通过")
if __name__ == '__main__':
unittest.main()
3.json一种轻量级数据交换格式;后缀名 .json
json格式
{
"data":
[
{"b1":2,"b2":2,"b3":2,"expect":"等边三角形"},
{"b1":3,"b2":3,"b3":6,"expect":"不是三角形"},
{"b1":2,"b2":3,"b3":4,"expect":"普通三角形"},
{"b1":4,"b2":4,"b3":5,"expect":"等腰三角形"},
{"b1":1,"b2":1,"b3":2,"expect":"不是三角形"},
{"b1":2,"b2":2,"b3":4,"expect":"不是三角形"},
{"b1":2,"b2":2,"b3":3,"expect":"等腰三角形"}
]
}
读取json
#导包Jason
import json
#打开文件流
class Read_josn():
def read_josn(self):
with open('../database/sjx.json','r',encoding='utf-8') as f:
#调用load
datas=json.load(f)
return datas["data"]
if __name__ == '__main__':
print(Read_josn().read_josn())
执行
#导包 三角形 数据
import unittest
from Cs.case.sjx_616 import Sjx
from Cs.Readdate.read_josn import Read_josn
#实例化三角形
sjxclass=Sjx()
#实例化数据
readjosn=Read_josn()
class Test(unittest.TestCase):
def test(self):
for i in range(len(readjosn.read_josn())):
result=sjxclass.Sjx(
int(readjosn.read_josn()[i]["b1"]),
int(readjosn.read_josn()[i]["b2"]),
int(readjosn.read_josn()[i]["b3"]))
self.assertEqual(result,readjosn.read_josn()[i]["expect"])
#打印
print(readjosn.read_josn()[i]["b1"],
readjosn.read_josn()[i]["b2"],
readjosn.read_josn()[i]["b3"],
readjosn.read_josn()[i]["expect"],"------->通过")
if __name__ == '__main__':
unittest.main()
4TXT:一种纯文本格式; 后缀名 .txt(与CSV类似)
3,3,6,不是三角形
2,2,3,等腰三角形
2,3,4,普通三角形
3,3,3,等边三角形
3,3,4,等腰三角形
4,4,5,等腰三角形
1,1,2,不是三角形
2,2,4,不是三角形
读取数据
class readtext():
def read_text(self):
with open('../database/sjx.txt','r',encoding='utf-8') as f:
#通过文件流调用读取方法——》所有行
datas=f.readlines()
#新建列表——》
lines=[]
#遍历
for data in datas :
lines.append(data.strip().split(','))
return lines
"""
strip() 去除字符串前后回车
spilt() 使用指定字符串进行分割字符串 并以列表的格式返回分割后数据
"""
if __name__ == '__main__':
print(readtext().read_text())
执行
#导包 三角形 读取数据
import unittest
from Cs.case.sjx_616 import Sjx
from Cs.Readdate.read_text import readtext
#实例化
sjxclass=Sjx()
readtextclass=readtext()
class Test(unittest.TestCase):
def test(self):
for i in range (len(readtextclass.read_text())):
result=sjxclass.Sjx(
int(readtextclass.read_text()[i][0]),
int(readtextclass.read_text()[i][1]),
int(readtextclass.read_text()[i][2])
)
self.assertEqual(result,readtextclass.read_text()[i][3])
print(readtextclass.read_text()[i][0],
readtextclass.read_text()[i][1],
readtextclass.read_text()[i][2],
readtextclass.read_text()[i][3],"----通过")
if __name__ == '__main__':
unittest.main()
测试报告生成
#导包
import unittest
import time
from Cs.case.HTMLTestRunner import HTMLTestRunner
if __name__ == '__main__':
#声明测试套件
dis=unittest.defaultTestLoader.discover('./',pattern='test*.py')
#指定报告的目录、文件名 、后缀名
dir_path='../report/'
nowtime=time.strftime('%Y_%m_%d %H_%M_%S')
file_name=dir_path+nowtime+"report.html"
#打开文件流
with open(file_name,"wb") as f:
#实例化
HTMLTestRunner(stream=f,title='单元测试',description='单元测试学习').run(dis)