python——pytest单元测试

python——pytest单元测试,第1张

前提:需要安装pytest和pytest-html(生成html测试报告)
pip install pytest 和 pip install pytest-html


案例一
pytest.main(“模块.py”)【运行指定模块下,运行所有test开头的类和测试用例】

import pytest
class TestDemo():
    def test001(self):
        print("我是test001")

if __name__ == '__main__':
    pytest.main(["--html=./哈哈哈2.html", "demo1_test.py"])


使用@pytest.mark.skip()跳过该用例(函数)

import pytest
class TestDemo():
    def test001(self):
        assert 2==2
    def test002(self):
        print("我是test002")
    def test003(self):
        print("我是test003")
    @pytest.mark.skip()        #跳过该用例(函数)
    def test004(self):
        print("我是test004")
if __name__ == '__main__':
    # pytest.main(["--html=./哈哈哈2.html", "demo1_test.py"])
    pytest.main()


Pytest生成测试报告
1.前提:需要下载pytest-html模块(python自带的生成测试报告模块)
2.命令:pip install pytest-html
3.案例:
方式一:运行指定模块下,所有以test开头的类和测试用例

if __name__ == '__main__':
    pytest.main(["--html=生成测试报告的路径.html","模块名.py"])

方式二:运行指定模块的指定类的指定测试用例,用双冒号分割,并生成测试报告

if __name__ == '__main__':
    pytest.main(["--html=生成测试报告的路径.html","模块名.py::类名::方法名"])

方式二:运行指定模块的指定类的指定测试用例,用双冒号分割,并生成测试报告

if __name__ == '__main__':
    pytest.main(["--html=./report.html"])

读取文件数据
读取xml文件

#导入读取xml文件的模块
from xml.dom import minidom
 
class ReadXmlClass():
    def read_xml(self,filename,firstname,secondname):
        #解析xml文件数据
        root =minidom.parse(filename)
        #根据标签名和索引获取元素
        firstnode =root.getElementsByTagName(firstname)[0]
        #根据父标签获取子标签,根据子标签的名称和索引获取元素
        secondnode=firstnode.getElementsByTagName(secondname)[0].firstChild.data
        return secondnode

读取csv文件

#导入csv模块
import csv
 
class ReadCsvClass():
    def read_csv(self):
        #定义一个空列表
        item =[]
        #得到csv文件对象
        c = csv.reader(open("../data/csvData.csv","r"))
        for csv_i in c:`在这里插入代码片`
            #将获取的数据添加到列表中
            item.append(csv_i)
        return item

Allure
使用Pytest结合Allure生成测试报告:
①下载allure:Central Repository: io/qameta/allure/allure-commandline
②配置环境变量:系统变量的Path中,添加allure本地的bin路径
③验证:在cmd窗口中输入allure
④安装allure-pytest:命令 pip install allure-pytest
⑤安装完成后重启PyCharm
⑥生成测试报告:

if __name__ == '__main__':
    #allure生成json类型的测试报告
    pytest.main(['--alluredir', 'report/result', '模块名.py'])
    #将测试报告转为html格式
    split = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean'
    #system函数可以将字符串转化成命令在服务器上运行
    os.system(split)

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/725000.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存