Pytest测试框架4

news2024/10/6 6:26:14

目录:

  1. pytest配置文件
  2. pytest插件
  3. pytest测试用例执行顺序自定义pytest-ordering
  4. pytest测试用例并行运行与分布式运行
  5. pytest内置插件hook体系
  6. pytest插件开发

1.pytest配置文件

pytest.ini 是什么?

  • pytest.ini 是 pytest 的配置文件
  • 可以修改  pytest  的默认行为
  • 不能使用任何中文符号,包括汉字、空格、引号、冒号等等

pytest.ini

  • 修改用例的命名规则
  • 配置日志格式,比代码配置更方便
  • 添加标签,防止运行过程报警告错误
  • 指定执行目录
  • 排除搜索目录

 pytest 配置- 改变运行规则(pytest放置在项目根路径下)

[pytest]
;执行check_开头和 test_开头的所有的文件,后面一定要加*
python_files = check_* test_*
;执行所有的以Test和Check开头的类
python_classes = Test*  Check*
;执行所有以test_和check_开头的方法
python_functions = test_* check_* 

pytest 配置- 添加默认参数

[pytest]
;执行check_开头和 test_开头的所有的文件,后面一定要加*
python_files = check_* test_*
;执行所有的以Test和Check开头的类
python_classes = Test*  Check*
;执行所有以test_和check_开头的方法
python_functions = test_* check_*
;pytest 配置- 添加默认参数
addopts = -v -s --alluredir=./results

pytest 配置- 指定/忽略执行目录

[pytest]
;执行check_开头和 test_开头的所有的文件,后面一定要加*
python_files = check_* test_*
;执行所有的以Test和Check开头的类
python_classes = Test*  Check*
;执行所有以test_和check_开头的方法
python_functions = test_* check_*
;pytest 配置- 添加默认参数
addopts = -v -s --alluredir=./results
;设置执行的路径
;testpaths = bilibili baidu
;忽略某些文件夹/目录
norecursedirs = result logs datas test_demo*

pytest 配置- 日志 

[pytest]
;执行check_开头和 test_开头的所有的文件,后面一定要加*
python_files = check_* test_*
;执行所有的以Test和Check开头的类
python_classes = Test*  Check*
;执行所有以test_和check_开头的方法
python_functions = test_* check_*
;pytest 配置- 添加默认参数
addopts = -v -s --alluredir=./results
;设置执行的路径
;testpaths = bilibili baidu
;忽略某些文件夹/目录
norecursedirs = result logs datas test_demo*

;日志开关 true false
log_cli = true
;日志级别
log_cli_level = info
;打印详细日志,相当于命令行加 -vs
addopts = --capture=no
;日志格式
log_cli_format = %(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)
;日志时间格式
log_cli_date_format = %Y-%m-%d %H:%M:%S
;日志文件位置
log_file = ./log/test.log
;日志文件等级
log_file_level = info
;日志文件格式
log_file_format = %(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)
;日志文件日期格式
log_file_date_format = %Y-%m-%d %H:%M:%S

2.pytest插件

pytest 插件分类

  • 外部插件:pip install 安装的插件
  • 本地插件:pytest 自动模块发现机制(conftest.py 存放的)
  • 内置插件:代码内部的_pytest 目录加载

pytest常用的插件

pip install pytest-ordering  控制用例的执行顺序(重点)
pip install pytest-xdist    分布式并发执行测试用例(重点)
pip install pytest-dependency   控制用例的依赖关系 (了解)
pip install pytest-rerunfailures   失败重跑(了解)
pip install pytest-assume          多重较验(了解)
pip install pytest-random-order  用例随机执行(了解)
pip install pytest-html            测试报告(了解)

3.pytest测试用例执行顺序自定义pytest-ordering

pytest 执行顺序控制

场景: 

对于集成测试,经常会有上下文依赖关系的测试用例。

比如 10 个步骤,拆成 10 条 case,这时候能知道到底执行到哪步报错。

用例默认执行顺序:自上而下执行

解决:

可以通过 setup,teardown 和 fixture 来解决。也可以使用对应的插件。

安装:pip install pytest-ordering

用法:@pytest.mark.run(order=2)

注意:多个插件装饰器(>2)的时候,有可能会发生冲突

代码示例一: 

import pytest

@pytest.mark.run(order=2)
def test_foo():
    assert True

@pytest.mark.run(order=1)
def test_bar():
    assert True

代码示例二:

import pytest


@pytest.mark.third
def test_three():
    assert True


@pytest.mark.seconed
def test_two():
    assert True


@pytest.mark.first
def test_one():
    assert True

4.pytest测试用例并行运行与分布式运行

est 并行与分布式执行

场景 1:

测试用例 1000 条,一个用例执行 1 分钟,一个测试人员执行需要 1000 分钟。

通常我们会用人力成本换取时间成本,加几个人一起执行,时间就会 缩短。

如果 10 人一起执行只需要 100 分钟,这就是一种分布式场景。

场景 2:

假设有个报名系统,对报名总数统计,数据同时进行修改操作的时候有可能出现问题,

需要模拟这个场景,需要多用户并发请求数据。

解决:

使用分布式并发执行测试用例。分布式插件:pytest-

xdist

安装及运行: pip install pytest-xdist

注意: 用例多的时候效果明显,多进程并发执行,同时支持 allure

 pytest -n auto

5.pytest内置插件hook体系

pytest hook 介绍

  • 是个函数,在系统消息触时被系统调用
  • 自动触发机制
  • Hook 函数的名称是确定的
  • pytest 有非常多的勾子函数
  • 使用时直接编写函数体

代码示例:

conftest.py

from typing import Optional

def pytest_collection_modifyitems(session,config,items:list):
    for item in items:
        item.name = item.name.encode('utf-8').decode('unicode-escape')
        item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')
def pytest_runtest_setup(item: "Item") -> None:
    print('hook : setup')
def pytest_runtest_teardown(item: "Item", nextitem: Optional["Item"]) -> None:
    print('hook : teardown')

test_order.py

def test_demo1():
    print('test hook')

 运行结果:

查看hook函数: 

.pytest hook函数的执行顺序:文字版顺序:

root
└── pytest_cmdline_main
├── pytest_plugin_registered
├── pytest_configure
│ └── pytest_plugin_registered
├── pytest_sessionstart
│ ├── pytest_plugin_registered
│ └── pytest_report_header
├── pytest_collection
│ ├── pytest_collectstart
│ ├── pytest_make_collect_report
│ │ ├── pytest_collect_file
│ │ │ └── pytest_pycollect_makemodule
│ │ └── pytest_pycollect_makeitem
│ │ └── pytest_generate_tests
│ │ └── pytest_make_parametrize_id
│ ├── pytest_collectreport
│ ├── pytest_itemcollected
│ ├── pytest_collection_modifyitems
│ └── pytest_collection_finish
│ └── pytest_report_collectionfinish
├── pytest_runtestloop
│ └── pytest_runtest_protocol
│ ├── pytest_runtest_logstart
│ ├── pytest_runtest_setup
│ │ └── pytest_fixture_setup
│ ├── pytest_runtest_makereport
│ ├── pytest_runtest_logreport
│ │ └── pytest_report_teststatus
│ ├── pytest_runtest_call
│ │ └── pytest_pyfunc_call
│ ├── pytest_runtest_teardown
│ │ └── pytest_fixture_post_finalizer
│ └── pytest_runtest_logfinish
├── pytest_sessionfinish
│ └── pytest_terminal_summary
└── pytest_unconfigure

简单的例子

def pytest_runtest_setup(item):    
  # 执行测试用例前执行的setup方法    
  print("setting up", item)

def pytest_runtest_call(item):    
  # 调用执行测试的用例
  print("pytest_runtest_call")

def pytest_runtest_teardown(item):   
  #  执行测试用例后执行的teardown
  print("pytest runtest teardown",item)

总结

  • 1、hook 函数名字固定
  • 2、hook 函数会被自动执行
  • 3、执行是有先后顺序的
  • 4、pytest 定义了很多 hook 函数,可以在不同阶段实现不同的功能

6.pytest插件开发

pytest 编写自己的插件

Pytest 编写插件 1 - 修改默认编码

pytest_collection_modifyitems 收集上来的测试用例实现定制化功能

解决问题:

  • 自定义用例的执行顺序
  • 解决编码问题 (中文的测试用例名称)
  • 自动添加标签

conftest.py

from typing import Optional


def pytest_collection_modifyitems(session, config, items: list):
    print(items)
    for item in items:
        item.name = item.name.encode('utf-8').decode('unicode-escape')
        item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')


def pytest_runtest_setup(item: "Item") -> None:
    print('hook : setup')


def pytest_runtest_teardown(item: "Item", nextitem: Optional["Item"]) -> None:
    print('hook : teardown')

test_order.py

import pytest


@pytest.mark.parametrize('name', ['百度', '测试'])
def test_demo1(name):
    print(f'name:{name}')

运行结果:

Pytest 编写插件 1 - 修改默认编码 (含有中文的测试用例名称,改写编码格式:)

def pytest_collection_modifyitems(session, config, items):
  for item in items:
    item.name = item.name.encode('utf-8').decode('unicode-escape')
    item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')

Pytest 编写插件 2 - 添加命令行参数

conftest.py

import pytest
import yaml


# 定义一个命令行参数
def pytest_addoption(parser):
    mygroup = parser.getgroup("hdc")  # group 将下面所有的 option都展示在这个group下。
    mygroup.addoption("--env",  # 注册一个命令行选项
                      default='test',  # 参数的默认值
                      dest='env',  # 存储的变量,为属性命令,可以使用Option对象访问到这个值,暂用不到
                      help='set your run env'  # 帮助提示 参数的描述信息
                      )
    mygroup.addoption("--env1",  # 注册一个命令行选项
                      default='test1',  # 参数的默认值
                      dest='env1',  # 存储的变量,为属性命令,可以使用Option对象访问到这个值,暂用不到
                      help='set your run env'  # 帮助提示 参数的描述信息
                      )

# 如何针对传入的不同参数完成不同的逻辑处理
@pytest.fixture(scope='session')
def cmdoption(request):
    myenv = request.config.getoption("--env", default='test')
    if myenv == 'test':
        datapath = 'datas/test/data.yml'
    elif myenv == 'dev':
        datapath = 'datas/dev/data.yml'

    with open(datapath) as f:
        datas = yaml.safe_load(f)
    return myenv, datas

test_order.py

def test_addoption(cmdoption):
    print(cmdoption)

运行结果:

 

项目结构:

打包发布到 pypi

  • 发布到:www.pypi.org
  • 代码上传到:github 

打包项目构成

  • 源码包
  • setup.py
  • 测试包

setup.py 配置

from setuptools import setup, find_packages

setup(
    name='pack',
    url='https://github.com/',
    version='1.0',
    author="tom",
    author_email='123456@qq.com',
    description='set your encoding and logger',
    long_description='Show Chinese for your mark.parametrize(). Define logger variable for getting your log',
    classifiers=[  # 分类索引 ,pip 对所属包的分类
        'Framework :: Pytest',
        'Programming Language :: Python',
        'Topic :: Software Development :: Testing',
        'Programming Language :: Python :: 3.8',
    ],
    license='proprietary',
    packages=find_packages(),  # ['pytest_encode'],
    keywords=[
        'pytest', 'py.test', 'pytest_encode',
    ],

    # 需要安装的依赖
    install_requires=[
        'pytest'
    ],
    # 入口模块 或者入口函数
    entry_points={
        'pytest11': [
            'pytest_encode = pytest_encode.main',
        ]
    },
    zip_safe=False
)

打包命令

依赖包安装:
pip install setuptools  python 的包管理工具,负责 安装和发布,尤其是安装拥有信赖关系的包。
pip install wheel       生成 *.whl 格式的安装包,本质上也是一个压缩包

打包命令:
python setup.py sdist bdist_wheel

发布命令

py -m pip install --upgrade twine      ## 安装 twine 工具
py -m twine upload --repository testpypi dist/*     ## 上传代码

python打包官网:Packaging Python Projects — Python Packaging User Guide

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/851556.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Sql server还原失败(数据库正在使用,无法获得对数据库的独占访问权)

一.Sql server还原失败(数据库正在使用,无法获得对数据库的独占访问权) 本次测试使用数据库实例SqlServer2008r2版 错误详细: 标题: Microsoft SQL Server Management Studio ------------------------------ 还原数据库“Mvc_HNHZ”时失败。 (Microsoft.SqlServer.…

Java笔记(三十一):MySQL(中)--查询DQL、单表查询、函数、多表查询、查询结果合并

六、查询DQL⭐⭐⭐⭐⭐(SELECT) 0、查询书写顺序&执行顺序 当selcet中有聚合函数时,看起来是 select 先执行,因为后面having可以用到selcet聚合函数后面的别名 但实际上还是select 后执行,如果不是聚合函数或者其…

C#,数值计算——基于模拟退火的极小化问题单纯形(下山)算法的计算方法与C#源程序

1 模拟退火 模拟退火算法其实是一个类似于仿生学的算法,模仿的就是物理退火的过程。 我们炼钢的时候,如果我们急速冷凝,这时候的状态是不稳定的,原子间杂乱无章的排序,能量很高。而如果我们让钢水慢慢冷凝&#xff0c…

PowerDesigner使用实践

PowerDesigner使用实践 一、前言 1.简介 PowerDesigner DataArchitect 是业界领先的数据建模工具。 它提供了一种模型驱动的方法来增强业务和 IT 的能力并使其保持一致。 PowerDesigner 使企业能够更轻松地可视化、分析和操作元数据,以实现有效的企业信息架构。 …

通向架构师的道路之weblogic的集群与配置

一、Weblogic的集群 还记得我们在第五天教程中讲到的关于Tomcat的集群吗? 两个tomcat做node即tomcat1, tomcat2,使用Apache HttpServer做请求派发。 现在看看WebLogic的集群吧,其实也差不多。 区别在于: Tomcat的集群的实现为两个物理上…

Kotin协程的基础

协程是什么? 就是同步方式去编写异步执行的代码。协程是依赖于线程,但是协程挂起的时候不需要阻塞线程。几乎没有任何代价。 协程的创建 一个线程可以创建多个协程。协程的创建是通过CoroutineScope创建,协程的启动方式有三种。 runBlockin…

湘大oj1088 N!:求阶乘 数据太大怎么处理 常规的递归求阶乘

一、链接 N&#xff01; 二、题目 Description 请求N&#xff01;&#xff08;N<10000&#xff09;&#xff0c;输出结果对10007取余 输入 每行一个整数n&#xff0c;遇到-1结束。 输出 每行一个整数&#xff0c;为对应n的运算结果。 Sample Input 1 2 -1 Sample Outp…

【数据结构与算法】左叶子之和

左叶子之和 递归三部曲 确定递归函数的参数和返回值 int sumOfLeftLeaves(TreeNode* root)确定终止条件 遍历遇到空节点 if (root NULL) return 0;单层的递归逻辑 遍历顺序&#xff1a;左右中&#xff08;后序遍历&#xff09; 选择后序遍历的原因&#xff1a;要通过递归函…

【Linux操作系统】深入了解系统编程gdb调试工具

在软件开发过程中&#xff0c;调试是一个非常重要的步骤。无论是在开发新的软件还是维护现有的代码&#xff0c;调试都是解决问题的关键。对于Linux开发者来说&#xff0c;GDB是一个非常有用的调试工具。在本文中&#xff0c;我们将探讨Linux中使用GDB进行调试的方法和技巧。 …

C# OpenCvSharp 读取rtsp流

效果 项目 代码 using OpenCvSharp; using OpenCvSharp.Extensions; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using Syste…

HTTPS安全通信

HTTPS,TLS/SSL Hyper Text Transfer Protocol over Secure Socket Layer,安全的超文本传输协议,网景公式设计了SSL(Secure Sockets Layer)协议用于对Http协议传输的数据进行加密,保证会话过程中的安全性。 使用TCP端口默认为443 TLS:(Transport Layer Security,传输层…

30、Flink SQL之SQL 客户端(通过kafka和filesystem的例子介绍了配置文件使用-表、视图等)

Flink 系列文章 1、Flink 部署、概念介绍、source、transformation、sink使用示例、四大基石介绍和示例等系列综合文章链接 13、Flink 的table api与sql的基本概念、通用api介绍及入门示例 14、Flink 的table api与sql之数据类型: 内置数据类型以及它们的属性 15、Flink 的ta…

【移动机器人运动规划】03 —— 基于运动学、动力学约束的路径规划

文章目录 前言相关代码整理:相关文章&#xff1a; 介绍什么是kinodynamic&#xff1f;为什么需要kinodynamic&#xff1f;模型示例unicycle model&#xff08;独轮车模型&#xff09;differential model&#xff08;两轮差速模型&#xff09;Simplified car model (简化车辆模型…

YOLO相关原理(文件结构、视频检测等)

超参数进化(hyperparameter evolution) 超参数进化是一种使用了genetic algorithm&#xff08;GA&#xff09;遗传算法进行超参数优化的一种方法。 YOLOv5的文件结构 images文件夹内的文件和labels中的文件存在一一对应关系 激活函数&#xff1a;非线性处理单元 activation f…

WWW 23 | Facebook Marketplace的意图理解:用双塔模型处理结构化的产品目录

©PaperWeekly 原创 作者 | 何允中 单位 | Meta 研究方向 | Information Retrieval 摘要 本文介绍了 Facebook Marketplace 团队提出的 HierCat 构架&#xff0c;以解决电商搜索中的意图理解难题。HierCat 利用线上产品交互挖掘弱监督数据&#xff0c;并通过基于 Transfor…

sqlserver 数据库显示 正在还原

问题描述之前不太会搞差异备份的恢复&#xff0c;然后恢复发生了失败之后这个数据库一直处于(正在还原……状态 并且出现数据库无法访问的情况 尝试解决1执行查询Restore Database 数据库名称 with Recovery然后不太能行 2执行查询Restore Database 数据库名称 with NoRecovery…

10个最流行的免费3D模型下载网站

作为一名独立游戏开发者&#xff0c;自己创建图形、配乐、动画和更多东西是相当具有挑战性的。 创建资产所需的成本和时间有时是许多游戏开发商无法承受的。 这就是他们选择在互联网上搜索免费内容的原因。 现在&#xff0c;在浩瀚的内容海洋中获得如此免费的东西有点困难。 本…

uniapp 微信小程序 使用高德地图 定制气泡

前言 我们常说的uniapp或者原生微信小程序框架使用高德地图&#xff0c;并不是ui就是高德地图&#xff0c;而是api用的高德地图&#xff0c;ui仍然是框架内置的地图&#xff0c;也就是说&#xff0c;地图和api是分开&#xff0c;微信小程序的内置地图自然是腾讯地图。 高德地…

SpringBoot第34讲:SpringBoot集成ShardingJDBC - 基于JPA的DB隔离多租户方案

SpringBoot第34讲&#xff1a;SpringBoot集成ShardingJDBC - 基于JPA的DB隔离多租户方案 本文是SpringBoot第34讲&#xff0c;主要介绍ShardingJDBC的分片算法和分片策略&#xff0c;并在此基础上通过SpringBoot集成ShardingJDBC的几种策略&#xff08;标准分片策略&#xff0c…

DevOps最佳实践和工具在本地环境中的概述

引言 最近&#xff0c;我进行了一次网上搜索&#xff0c;以寻找DevOps的概述&#xff0c;尽管有大量的DevOps工具和实践&#xff0c;但我无法找到一个综合的概述。因此&#xff0c;我开始了对DevOps生态系统和最佳实践的梳理&#xff0c;以创建一个整体视图,方便后续研究实践 C…