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博客

相关推荐
ZZHow102417 小时前
02OpenCV基本操作
python·opencv·计算机视觉
计算机学长felix17 小时前
基于Django的“酒店推荐系统”设计与开发(源码+数据库+文档+PPT)
数据库·python·mysql·django·vue
站大爷IP17 小时前
Python随机数函数全解析:5个核心工具的实战指南
python
悟乙己18 小时前
使用 Python 中的强化学习最大化简单 RAG 性能
开发语言·python·agent·rag·n8n
max50060018 小时前
图像处理:实现多图点重叠效果
开发语言·图像处理·人工智能·python·深度学习·音视频
AI原吾18 小时前
玩转物联网只需十行代码,可它为何悄悄停止维护
python·物联网·hbmqtt
云动雨颤18 小时前
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
python·单元测试
SunnyDays101118 小时前
Python 实现 HTML 转 Word 和 PDF
python·html转word·html转pdf·html转docx·html转doc
跟橙姐学代码19 小时前
Python异常处理:告别程序崩溃,让代码更优雅!
前端·python·ipython
蓝纹绿茶19 小时前
Python程序使用了Ffmpeg,结束程序后,文件夹中仍然生成音频、视频文件
python·ubuntu·ffmpeg·音视频