上个博客里我们已经讲述了单元测试的介绍,这次就不在介绍了,主要是讲写单元测试的另一个方法,用pytest来写。
一、pytest,简介
1.pytest是一个非常成熟的python的单元框架,比unittest更灵活,容易上手。
2.pytest可以和selenium、requests、appium结合实现自动化、接口自动化、app自动化。
3.pytest可以实现测试用例的跳过以及reruns失败用例重试
4.pytest可以和allure生成非常美观的测试报告
5.pytest可以和jenkins持续集成
6.pytest有很多非常强大的插件,并且这些插件能够实现很多的使用的操作
例如
pytest-html 生成html格式的自动化测试报告
pytest – rerunfailures 用例失败后重跑
allure-pytest 用于生成美观的测试报告
二、安装
pip install pytest 和 pip install pytest-html
在pytharm里的黑窗口里输入这条命令,等待一会就可以,如果报错,可能是网络原因,重新下载就行。
三、命名规则:
Pytest 单元测试中的类名和方法名必须是以 test 开头 , 执行中只能找到 test 开头的类和方法,比 unittest更加严谨
unittest : Setup>> setupclass , teardown >> teardownclass (课堂作业)
Pytest: setup, setup_class 和 teardown, teardown_class 函数 ( 和 unittest 执行效果一样 )
运行于测试方法的始末,即 : 运行一次测试函数会运行一次 setup 和 teardown
运行于测试方法的始末 , 但是不管有多少测试函数都只执行一次 setup_class 和 teardown_class
四、pytest 生成自带的html测试报告
不过需要下载pytest-html模块(python自带的生成测试报告模块)
指定用例
pytest . main ([ ‘ — html =. / report . html’ , ‘ 模块 . py :: 类 :: test_a_001 ‘])
pytest的运行方式
. 点号,表示用例通过
F 表示失败 Failure
E 表示用例中存在异常 Error
五、文件读取
读取csv文件
import csv #导入csv模块
class ReadCsv():
def read_csv(self):
item =[] #定义一个空列表
c = csv.reader(open("../commonDemo/test1.csv","r")) #得到csv文件对象
for csv_i in c:
item.append(csv_i) #将获取的数据添加到列表中
return item
r = ReadCsv()
print(r.read_csv())
读取xml文件
from xml.dom import minidom
class Readxml():
def read_xml(self,filename,onename,twoname):
root =minidom.parse(filename)
firstnode =root.getElementsByTagName(onename)[0]
secondnode=firstnode.getElementsByTagName(twoname)[0].firstChild.data
return secondnode
六、allure
Allure 是一款轻量级并且非常灵活的开源测试报告框架。 它支持绝大多数测试框架, 例如 TestNG 、Pytest、 JUint 等。它简单易用,易于集成。
首先需要配置 allure 的环境变量
配置好后,验证是否成功
其次要在python里安装allure
pip install allure-pytest
allure-pytest 是 Pytest 的一个插件,通过它我们可以生成 Allure 所需要的用于生成测试报告的数据
allure 常用的几个特性
1、@allure.feature # 用于描述被测试产品需求
2、@allure.story # 用于描述 feature 的用户场景,即测试需求
3、with allure.step (): # 用于描述测试步骤,将会输出到报告中
4、allure.attach # 用于向测试报告中输入一些附加的信息,通常是一些测试数据,截图等
1和2
代码:
class Testma():
# @pytest.mark.skip
@allure.feature("用户登录功能") # 用于定义被测试的功能,被测产品的需求点
@allure.story("登录成功") # 用于定义被测功能的用户场景,即子功能点
def test001(self):
assert 1 == 1
@allure.feature("用户登录功能") # 用于定义被测试的功能,被测产品的需求点
@allure.story("登录失败") # 用于定义被测功能的用户场景,即子功能点
def test002(self):
assert 1 == 2
结果
3和4
代码:
class Testshop():
@allure.feature("购物车")
@allure.story("产品展示")
def testshow(self):
with allure.step("查看吉利系列车信息"):
allure.attach("H7","哈弗")
with allure.step("查看哈弗系列车信息"):
allure.attach("哈弗","H7")
结果:
Original: https://blog.csdn.net/weixin_45517799/article/details/117570817
Author: 清见欢
Title: 单元测试(2) ——- pytest
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/776482/
转载文章受原作者版权保护。转载请注明原作者出处!