python——pytest单元测试

前提:需要安装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)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值