命名规则
Pytest
单元测试中的类名和方法名必须是以
test
开头
,
执行中只能找到
test
开头的类和方法,比unittest更加严谨
Pytest生成自带的html测试报告
前提条件:需要下载pytest-html模块(python自带的生成测试报告模块)
pip install pytest-html
Pytest调用语句
pytst
.
main
([
'-x'
,
'--html=./report.html'
,
't12est000.py'
])
-x
出现一条测试用例失败就退出测试
-s:
显示
print
内容
Pytest的运行方式
.
点号,表示用例通过
F
表示失败
Failure
E
表示用例中存在异常
Error
拿取数据
from xml.dom import minidom
class ReadXml():
# def readxml(self):
# # parse解析哪个xml文件
# #../返回上一级 解析test01.xml
# #root随意起名
# root = minidom.parse("../data/test01.xml")
# #add对应的标签
# firstnode=root.getElementsByTagName("add")[0]
# #拿到add里面的数据 firstChild.data获取第一个
# secondnode=firstnode.getElementsByTagName("exepiton")[0].firstChild.data
# return secondnode
# # #打印
# # print(root)
# parse解析哪个xml文件
# ../返回上一级 解析test01.xml
# root随意起名
def readxml(self,path,firstname,secondname):
#传进文件路径
root = minidom.parse(path)
firstnode = root.getElementsByTagName(firstname)[0]
secondnode = firstnode.getElementsByTagName(secondname)[0].firstChild.data
return secondnode
# #打印
# print(root)
#调用实例化对象 print输出
print(ReadXml().readxml("../data/test01.xml","add","exepiton"))
导入pytest验证是否通过
#导入
import pytest
class TestClass():
# def setup(self):
# print("setup")
# @classmethod
# def setup_class(cls):
# print("setup_class")
# def test001(self):
# print("我是test001")
# def test002(self):
# print("我是test002")
# def teardown(self):
# print("teardown")
# @classmethod
# def teardown_class(cls):
# print("teardown_class")
def test001(self):
assert 3==4
def test002(self):
assert 2==2
#跳过语句
@pytest.mark.skip
def test003(self):
assert 1==1
if __name__ == '__main__':
#加入参数只执行一个 放入路径
# pytest.main(["-s","test_001.py"])
#生成测试报告
pytest.main(["-s","test_001.py","--html=./report.html"])
类名规则报错
加入参数 -s才能出运行结果
报错为 没有权限
解决方法 加入下载pytest
然后生成测试报告
跳过语句的演示
测试报告显示出
f报错 .为通过 s为跳过
参数必须加入命名才能运行出来
testxml代码
from calcdemo.calc import Calc
from readdata.readxml import ReadXml
import pytest
#实例化
c = Calc()
r = ReadXml()
qq=int(r.readxml("../data/test1.xml","cheng","cheng1"))
ww=int(r.readxml("../data/test1.xml","cheng","cheng2"))
ee=int(r.readxml("../data/test1.xml","cheng","execption"))
rr=int(r.readxml("../data/test1.xml","chu","chu1"))
tt=int(r.readxml("../data/test1.xml","chu","chu2"))
yy=int(r.readxml("../data/test1.xml","chu","execption"))
class TestXml():
def test001(self):
#拿到实际结果
result = c.cheng(qq,ww)
assert result ==ee
def test002(self):
result = c.chu(rr,tt)
assert result == yy
if __name__ == '__main__':
pytest.main(["--html=./report.html","testxml.py"])
readxml代码块
from xml.dom import minidom
class ReadXml():
def readxml(self,past,firstname,secondname):
#拿到根数据
root = minidom.parse(past)
firstname = root.getElementsByTagName(firstname)[0]
secondname = firstname.getElementsByTagName(secondname)[0].firstChild.data
return secondname
#验证
if __name__ == '__main__':
r = ReadXml()
#打印数据
print(r.readxml())