Pytest测试用例使用小

基础使用

Pytest 测试用例实现代码

复制代码
import pytest
from server.service import Service

@pytest.fixture
def service():
    return Service(logger)

class TestService:

    @classmethod
    def setup_class(cls):
        """
        初始化设置一次
        :return:
        """
        logger.info("{}----类初始化设置".format(cls.__name__))

    @classmethod
    def teardown_class(cls):
        """
        结束后,清除设置
        :return:
        """
        logger.info("{}----类清除设置".format(cls.__name__))

    def setup_method(self):
        """
        执行每个方法前,初始化
        :return:
        """
        logger.info("{}----执行每个方法前,初始化".format(self.__module__))

    def teardown_method(self):
        """
        执行每个方法后,清除设置
        :return:
        """
        logger.info("{}----执行每个方法后,清除设置".format(self.__module__)

可在类中添加类前后和方法前后固定执行的操作。

定义一个测试实例

复制代码
@pytest.mark.parametrize(
    ['params', 'expected'],  # 也可使用字符串传入'params, expected'传入
    [
        (
            {
                "title": "测试用例"
            },
            Code.OK
        ),  # 第一组测试参数
    ]
)
def test_add(self, service, params, expected):
    result = dialogue_service.add_dialogue(**params)
    assert result.code == Code.OK

假设TestService类在test_service.py中,运行该类,添加main方法,之后在该文件目录下运行命令python test.service.py

复制代码
if __name__ == '__main__':
    pytest.main()

运行测试类中一个测试用例

可在测试函数函数上添加标识装饰器@pytest.mark.[运行名称],如pytest.marks.add

复制代码
@pytest.mark.add
def test_add(self, service, params, expected):
    result = service.add(**params)
    assert result.code == Code.OK

如果过需要添加参数,则标识按如下方式添加:

复制代码
@pytest.mark.parametrize(
    ['params', 'expected'],
    [
        pytest.param(
            {"title": "测试用例",},
            Code.OK,
            marks=pytest.mark.add
        ),
    ]
)
def test_add(self, service, params, expected):
    result = service.add(**params)
    assert result.code == Code.OK

运行命令:pytest -m add

或直接使用命令,指定要运行的测试用例:pytest test_service.py::TestService:test_add

项目包引入路径问题

复制代码
import os
import sys
current_path = os.getcwd()
sys.path.append(os.path.join(current_path.split('project_name')[0], 'project_name'))  # 不添加测试时无法找到正确路径

将当前项目路径添加到系统中。

参考:

Python自动化测试框架unittest与pytest的区别_pytest和unittest哪个好-CSDN博客

相关推荐
飞翔的佩奇1 小时前
【完整源码+数据集+部署教程】表盘指针检测系统源码和数据集:改进yolo11-CA-HSFPN
python·yolo·计算机视觉·数据集·yolo11·表盘指针检测
larance1 小时前
SQLAlchemy 的异步操作来批量保存对象列表
数据库·python
搏博2 小时前
基于Python3.10.6与jieba库的中文分词模型接口在Windows Server 2022上的实现与部署教程
windows·python·自然语言处理·flask·中文分词
lxmyzzs3 小时前
pyqt5无法显示opencv绘制文本和掩码信息
python·qt·opencv
萧鼎4 小时前
Python pyzmq 库详解:从入门到高性能分布式通信
开发语言·分布式·python
yujkss5 小时前
Python脚本每天爬取微博热搜-终版
开发语言·python
yzx9910135 小时前
小程序开发APP
开发语言·人工智能·python·yolo
飞翔的佩奇5 小时前
【完整源码+数据集+部署教程】二维码与查找模式检测系统源码和数据集:改进yolo11-CSwinTransformer
python·yolo·计算机视觉·数据集·yolo11·二维码与查找模式检测
大霞上仙5 小时前
实现自学习系统,输入excel文件,能学习后进行相应回答
python·学习·excel
Caven775 小时前
【pytorch】reshape的使用
pytorch·python