pytest自动化测试框架基础篇

上一篇 / 下一篇  2022-08-03 15:28:15 / 个人分类:自动化测试

一、单元测试框架

1.什么是单元测试框架

单元测试框架是在自动化测试或者白盒测试中对软件的最小单元(函数,方法)进行测试的框架。

2.单元测试框架分类

python:unittest、pytest

3.单元测试框架主要做什么?

发现测试用例

执行测试用例

判断测试结果

生成测试报告

二、pytest简介以及常用插件安装

1、pytest是一个非常成熟的单元测试框架,灵活和简单。

2、它可以结合selenium、request、appium完成各种不同的自动化。

3、它还可以生成自定义allure报告以及Jenkins持续集成。

4、pytest还有很多强大的插件:

pytest

pytest-html(生成html报告的插件)

pytest-xdist(多线程运行的插件)

pytest-ordering(改变用例的执行顺序的插件)

pytest-rerunfailures(失败用例重新执行的插件)

allure-pytest(生成美观的自定义的allure报告)

通过在项目的根目录下新建一个:requirements.txt文件保持插件。然后通过以下命令安装:

pip install -r requirements.txt

三、pytest默认测试用例的规则以及基础应用

1、模块名必须以test_或者_test结尾。

2、测试类必须以Test开头,并且不能带有init方法。

3、测试用例必须以test_开头。

执行:Alt+enter自动导包

1.通过命令方式执行

pytest

执行的参数:

-vs        -v输出详细信息。 -s输出调试信息。如 :pytest -vs

-n          多线程运行。(提前安装插件:pytest-xdist)如:pytest -vs -n=2

-reruns num   失败重跑 (提前安装插件:pytest-rerunfailres)如:pytest -vs -reruns=2

                        raise Exception()抛出异常

                        try except                解决异常

-x                出现一个用例失败则停止测试。如:pytest -vs -x

--maxfail        出现几个用例失败才停止,如:pytest -vs --maxfail=2

--html        生成html的测试报告(提前安装插件:pytest-html)如:pytest -vs --html/.reports/result.html

-k                运行测试用例名称中包含某个字符串的测试用例。如:pytest -vs -k "demo1"

-m "smoke"        只执行冒烟用例                如:pytest -vs -m "smoke"               

2.通过主函数main方式执行。

if __name__ == '__main__':
    pytest.main(["-vs"])

3.通过全局配置文件pytest.ini文件执行。

注意:

一般放在项目的根目录下,名称必须是pytest.ini

编码格式为ANSI,当有中文时可能需要改变编码格式为GB2312

pytest.ini文件可以改变默认的测试用例规则

不管是命令行运行还是主函数运行,都会加载这个配置文件

[pytest]
# 参数
# 具体传参
addopts = -vs   
# 执行的测试用例的路径
testpaths = ./testcase
# 执行的模块
python_files = test_*.py
# 执行的类
python_classes = Test*
# 执行的函数
python_functions = test_*
# 测试用例分组执行进行标记
markers =
    smoke : 冒烟用例
    authority_manage : 权限管理
    menu_manage : 菜单管理

四、pytest跳过测试用例

(1)无条件跳过

@pytest.mark.skip(reason="无理由跳过")

(2)有条件跳过

@pytest.mark.skipif(time_age<10, reason="年龄小于10跳过")

五、pytest测试用例的前后置,固件

class CommonUtil:
 
    def setup_class(self):
        print("每个类之前执行一次")
 
    def teardown_class(self):
        print("每个类之后执行一次")
 
    def setup(self):
        print("每个用例之前执行一次")
 
    def teardown(self):
        print("每个用例之后执行一次")

用例demo:

import pytest
import time
 
from common.common_util import CommonUtil
 
class TestCeshi(CommonUtil):
    time_age = 8
 
    @pytest.mark.smoke
    def test_demo1(self):
        print("测试第一条用例")
        raise Exception("这条用例挂了")
 
    def test_demo2(self):
        print("测试第二条用例")
 
    @pytest.mark.skip(reason="无理由跳过")
    def test_demo3(self):
        print("测试第三条用例")
 
    @pytest.mark.skipif(time_age < 10, reason="年龄小于10跳过")
    def test_demo4(self):
        print("测试第四条用例")
        
    def test_demo5(self):
        print("测试第五条用例")

TAG:

 

评分:0

我来说两句

Open Toolbar