使用pytest进行单元测试
1.安装测试环境
1.1:安装pytest
pip install pytest
1.2:安装pytest-html
pip install pytest-html
1.3:安装allure-pytest
pip install allure-pytest
2.创建开发文件包
2.1:添加开发文档
class Kaifa():
def add(self,a,b):
return a+b
def reduct(self,a,b):
return a-b
3.创建测试文档包
3.1:添加文件(csv,xml)(在这里用xml文档)
<jack>
<aa>
<a>1</a>
<a1>2</a1>
<a2>3</a2>
</aa>
<bb>
<b>5</b>
<b1>3</b1>
<b2>2</b2>
</bb>
</jack>
4.创建读取测试文件包
4.1:添加读取文件(xml)
from xml.dom import minidom
class Testclass():
def tesst(self,a,b,c):
jack = minidom.parse(a)
jack2 = jack.getElementsByTagName(b)[0]
jack1 = jack2.getElementsByTagName(c)[0].firstChild.data
return jack1
if __name__ == '__main__': #这个是在内部运行的功能,在外引用不会读取这个
t = Testclass() #验证代码块是否有问题
print(t.tesst("../cswendang/test.xml","aa","a"))
5.创建单元测试包
5.1添加单元测试
import pytest,allure,os #导入pytest,allure,os
from duqucswendang.duqutest import Testclass #导入读取文件代码
from rd.kaifa import Kaifa #导入开发代码
a = Testclass()
aa = int(a.tesst("../cswendang/test.xml","aa","a"))
aa1 = int(a.tesst("../cswendang/test.xml","aa","a1"))
aa2 = int(a.tesst("../cswendang/test.xml","aa","a2"))
bb = int(a.tesst("../cswendang/test.xml","bb","b"))
bb1 = int(a.tesst("../cswendang/test.xml","bb","b1"))
bb2 = int(a.tesst("../cswendang/test.xml","bb","b2"))
k = Kaifa()
class Testclass():
@allure.feature("加法")
@allure.story("成功")
def test001(self):
bb = k.add(aa,aa1)
assert bb == aa2
@allure.feature("加法")
@allure.story("这个减法错了")
def test002(self):
bb = k.add(aa,aa1)
assert bb != aa2
@allure.feature("加法")
@allure.story("成功")
def test003(self):
aa = k.reduct(bb,bb1)
assert aa == bb2
@allure.feature("加法")
@allure.story("这个加法错了")
def test004(self):
aa = k.reduct(bb,bb1)
assert aa != bb2
def test005(self):
with allure.step("查看哈吉利系列车信息"):
allure.attach("博越", "吉利")
with allure.step("查看哈弗系列车信息"):
allure.attach("H7", "哈弗")
if __name__ == '__main__': #这个下面就是allue生成测试报告html类型
pytest.main(['--alluredir', 'report/result', 'cs_test.py']) # 生成json类型的测试报告
split = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean' # 将测试报告转为html格式
os.system(split) # system函数可以将字符串转化成命令在服务器上运行