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

相关推荐
IVEN_10 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang11 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮11 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling11 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮15 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽15 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers