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

相关推荐
aiguangyuan4 小时前
基于BERT的中文命名实体识别实战解析
人工智能·python·nlp
喵手4 小时前
Python爬虫实战:知识挖掘机 - 知乎问答与专栏文章的深度分页采集系统(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集知乎问答与专栏文章·采集知乎数据·采集知乎数据存储sqlite
铉铉这波能秀4 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple
kali-Myon4 小时前
2025春秋杯网络安全联赛冬季赛-day2
python·安全·web安全·ai·php·pwn·ctf
Olamyh5 小时前
【 超越 ReAct:手搓 Plan-and-Execute (Planner) Agent】
python·ai
deepxuan5 小时前
Day7--python
开发语言·python
曲幽5 小时前
FastAPI不止于API:手把手教你用Jinja2打造动态Web页面
python·fastapi·backend·jinja2·full stack·template engine·web development
禹凕5 小时前
Python编程——进阶知识(多线程)
开发语言·爬虫·python
Ulyanov5 小时前
基于Pymunk物理引擎的2D坦克对战游戏开发
python·游戏·pygame·pymunk
铉铉这波能秀5 小时前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary