自动化测试-Pytest测试

目录

pytest简介

基本测试实例

编写测试文件

执行测试

pytest运行时参数

mark标记

Fixture

pytest插件

Allure测试报告

测试步骤


pytest简介

Pytest‌是一个非常流行的Python测试框架,它支持简单的单元测试和复杂的功能测试,具有易于上手、功能强大、灵活配置等特点,已经成为最流行的测试框架之一‌。

|-----------|-----------------------------------------------------------------------------------|
| 简单易用‌ | Pytest的API设计简洁,使得编写测试用例非常容易 |
| 功能强大‌ | 支持参数化测试、断言、fixture等功能,能够满足各种复杂的测试需求。 |
| 灵活配置‌ | 可以通过插件扩展功能,支持与Selenium、Requests、Appium等工具集成,实现Web自动化、接口自动化和App自动化。 |
| 报告生成‌ | 结合Allure,可以生成美观的测试报告。 |
| 插件丰富‌ | 拥有大量的插件,如pytest-ordering、pytest-rerunfailures、pytest-xdist等,支持用例管理、执行、跳过、失败重跑等功能‌ |

安装 pip install pytest 版本检查 pytest --version

基本测试实例

pytest测试文件的命名规则和基本使用方法:1)测试文件命名‌ :测试文件通常以test_ 开头或以**_test** 结尾。‌2)测试函数命名‌ :测试函数应以test开头。3)运行测试用例‌:在命令行中使用pytest命令可以自动发现并运行所有的测试用例。也可以指定要运行的测试文件或测试函数‌

编写测试文件

sub_test.py 与test_example.py

python 复制代码
#sub_test.py
def sub_num(a,b):
    return a-b
def test_sub():
    assert sub_num(2,3)==5
#test_example.py
def add_num(a,b):
    return a+b
def test_add():
    assert add_num(2,3)==5

执行测试

命令行执行 pytest 会过滤所有以test开头或结尾的文件,然后执行文件,匹配所有以test开头的类然后匹配所有以test开头的测试函数并执行

或者pytest ./文件目录 去解析特定文件

pytest运行时参数

|-------------------------------------------------------------|
| -k:根据表达式选择测试用例。 -m:只运行带有标记的测试用例 |
| -s:当测试失败时,打印出错误信息。 --ff:先运行之前失败的测试用例 |
| -x:在第一个测试失败时退出测试运行。 --lf:运行上次失败的测试用例 |
| --collect-only:仅收集测试用例,不运行它们。 --maxfail:指定在失败指定数量的测试用例后停止测试 |
| -v:输出更详细的测试信息,包括测试用例名称及其所在的类。 |
| --tb=style:控制台中的错误信息输出格式,例如--tb=line仅显示错误的那一行 |

mark标记

python 复制代码
import pytest
def sub_num(a,b):
    return a-b
def test_sub1():
    assert sub_num(2,3)==-1
@pytest.mark.skip('pytest skip')
def test_sub2():
    assert sub_num(2,2)==0
@pytest.mark.skipif(condition=(1==1),reason='True pytest skipif')
def test_sub3():
    assert sub_num(2,1)==1
@pytest.mark.skipif('1==2')
def test_sub4():
    assert sub_num(3,1)==2
@pytest.mark.xfail  #预期到的结果
def test_sub5():
    assert sub_num(3,1)==23
@pytest.mark.xfail
def test_sub6():
    assert sub_num(3,1)==2
ls=[(1,2,3),(1,2,3),(2,4,6)]
@pytest.mark.parametrize('n1,n2,sum',ls)
def test_sub7(n1,n2,sum):
    assert n1+n2 == sum
#pytest -v -m smoke
#sub_test.py::test_example1 PASSED                                                                        [ 50%] 
#sub_test.py::test_example2 PASSED   
@pytest.mark.smoke
def test_example1():
    assert True
@pytest.mark.smoke
def test_example2():
    assert 1 + 1 == 2

Fixture

pytest的fixture是一个非常强大的功能,主要用于在测试用例执行前后进行初始化和清理操作(类似setup、teardown)。通过使用@pytest.fixture()装饰器,可以将一个函数声明为fixture。该fixture的名字默认为函数名,也可以通过name参数指定别名。测试用例可以通过在参数列表中包含fixture的名字来使用它,pytest会在测试函数运行之前执行该fixture‌。

参数

|-------------|----------------------------------------------------------------------------------------------------------------------------------------|
| scope | 定义夹具的作用域,决定夹具的生命周期。可选值包括: 'function':每个测试函数调用时都会创建新的夹具(默认值)。 'class':每个测试类调用时创建一次夹具。 'module':每个模块调用时创建一次夹具。 'session':整个测试会话中只创建一次夹具。 |
| autouse | 默认为 False。如果设置为 True,则夹具会自动应用于所有测试,而不需要在测试中显式声明 |
| params | 允许为夹具提供多个参数值,测试函数将会被多次调用,每次使用不同的参数。 |
| name | 为夹具指定一个名称,默认情况下使用函数名 |

python 复制代码
import pytest
@pytest.fixture()
def fix_prepare():
    print('this is fixture prepare')
def test_fixture1(fix_prepare):
    print('test_fix1')
def test_fixture2(fix_prepare):
    print('test_fix2')
@pytest.fixture(scope='module')
#db_connection 夹具在整个模块中只会创建一次,两个测试函数都共享这个连接。
def db_connection():
    connection = "Database Connection"
    yield connection  # 提供夹具的值
    print("Closing the database connection")  # 清理工作

# 使用夹具的测试函数
def test_db1(db_connection):
    assert db_connection == "Database Connection"

def test_db2(db_connection):
    assert db_connection == "Database Connection"
@pytest.fixture(autouse=True) # 定义一个自动使用的夹具
def setup_environment(): 
    #会在每个测试函数运行前自动调用,无需在测试函数中显式声明
    print("Setting up the environment")
    yield  #测试固件需要yeild支持teardown
    print("Tearing down the environment")
# 测试函数
def test_example1():
    assert True
def test_example2():
    assert True
# 定义一个参数化的夹具
@pytest.fixture(params=["apple", "banana", "cherry"])
def fruit(request):
    return request.param
def test_fruit(fruit): # 使用夹具的测试函数
    #fruit 夹具会为每个测试函数提供不同的参数值,测试函数将会被调用三次,
    # 分别使用 "apple"、"banana" 和 "cherry"。
    assert fruit in ["apple", "banana", "cherry"]
if __name__=='__main__':
    pytest.main(['-vs','test_fixture.py'])

pytest插件

|--------------------------|-------------------------------------------------------------|
| pytest-ordering | 这个插件允许你控制测试函数的运行顺序,通过使用@pytest.mark.run(order=1)这样的装饰器 |
| pytest-assume | 这个插件引入了一个新的pytest.assume()函数,它允许你在一个测试中进行多次断言,并在第一次失败后停止测试。 |
| pytest-xdist | 这个插件增加了对并行测试的支持,可以通过不同的CPU或者机器并行运行测试。 |
| pytest-instafail | 这个插件在测试失败时提供实时的失败信息,而不是等到测试结束。 |
| pytest-rerunfailures | 这个插件可以在测试失败后重新运行它们。 |
| pytest-html | 这个插件生成美观的HTML测试报告。 |
| pytest-metadata | 这个插件允许你在测试结束后添加元数据。 |
| pytest-cov | 这个插件提供了代码覆盖率的报告。 |
| pytest-forked | 这个插件是pytest-xdist的一部分,但也可以单独使用,提供了一种在多个进程中运行测试的方法 |
| pytest-sugar | 这个插件提供了一种更好的控制台输出,可以显示测试进度。 |

Allure测试报告

测试步骤

1)allure的官网下载地址:https://github.com/allure-framework/allure2/releases

2)解压、配置环境变量,cmd 输入allure 检验安装配置

3)pip install allure-pytest 执行命令运行测试case pytest --alluredir ./result/ 生成许多json文件等

4)allure generate .\result\ -o ./report/ --clean

5)windows下 allure generate ./path/to/your/test_results -o ./path/to/report --clean (-O可以写成--report--dir或--output 生成测试报告路径, generate生成测试报告,--clear清楚报告生成一个新的 )

6)查看测试报告: windows下可以 allure open -h localhost -p 8083 ./report/ (页面加载index.html一致loading,当然还可以使用别的方法)

相关推荐
笨鸟先飞,勤能补拙29 分钟前
AI 赋能网络安全:技术全景、成熟度评估与实战案例
人工智能·python·安全·web安全·网络安全·sqlite·github
长和信泰光伏储能1 小时前
京津冀光伏发电:绿色能源的未来之路
python·能源
浦信仿真大讲堂2 小时前
从重复操作到自动化闭环:如何让 CST 与 Python 真正协同起来
python·自动化·cst·仿真软件·达索软件
Gu Gu Study2 小时前
ScoutLoop开放域深度研究引擎(agent的初步设计想法)
人工智能·python
卷无止境3 小时前
写代码这件事,到底该讲究点什么?
后端·python
卷无止境3 小时前
循环复杂度到底在算什么,Python 代码怎么才能写得让人一看就懂
后端·python
lpfasd1233 小时前
MediaCrawler 项目深度分析
chrome·python·chrome devtools
Dxy12393102164 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python
bamb004 小时前
一个项目带你入门AI应用开发01
python
0566464 小时前
Python康复训练——常用标准库
开发语言·python·学习