真实项目中如何使用pytest进行单元测试(结合PyCharm)

370 阅读1分钟

真实项目中如何使用pytest进行单元测试(结合PyCharm)

目的

网上很多介绍pytest的文章,但是很少结合实际开发,多为简单demo。以下介绍结合实际项目如何使用。

主要内容

  • 创建普通项目
  • 添加pytest依赖
  • 创建测试目录
  • 执行测试
  • 结合PyCharm
  • 参考文献

创建普通项目

创建一个项目根目录"pytest-demo"

添加项目文件,目录结构如下


pytest-demo

  • demo
    • __init__.py
      • utils
        • __init__.py
        • math_helper.py

math_helper.py如下

class MathHelper(object):
    def addition(self, first, second):
        """
        加法
        :param first: 第一个参数
        :param second: 第二个参数
        :return: 相加后的结果
        """
        # 先判断传入类型
        if not isinstance(first, (int, float)):
            raise ValueError("first参数必须为数值")
        if not isinstance(second, (int, float)):
            raise ValueError("second参数必须为数值")
        # 返回结果
        return first + second

添加pytest依赖

$ pip install pytest

添加单元测试目录

在根目录下创建单元测试目录"tests"(注意要创建成package,方便全量测试)

对应添加测试类,测试类文件名必须为test_*.py 或 *_test.py,命名规则可查看pytest官方文档

最终目录结构如下


pytest-demo

  • demo
    • __init__.py
      • utils
        • __init__.py
        • math_helper.py
  • tests
    • demo
      • __init__.py
        • utils
          • __init__.py
          • test_math_helper.py

test_math_helper.py如下

import pytest
from demo.utils.math_helper import MathHelper


def test_addition():
    # 初始化
    helper = MathHelper()
    # 输入错误类型,预期接收ValueError的报错
    with pytest.raises(ValueError):
        helper.addition("1", 2)
    with pytest.raises(ValueError):
        helper.addition(1, "2")
    # 正确调用
    result = helper.addition(1, 2)
    # 使用assert判断结果
    assert result == 3

执行测试用例

$ pytest

即可执行所有测试,并给出结果

结合PyCharm

  • 设置PyCharm默认测试类型
  1. 打开 File > Settings > Tools > Python Integrated Tools > Testing > Default test runner
  2. 修改下拉框,改为"pytest"
  3. 右键单元测试文件,点击"run",即可执行测试,在下方的"Run"窗口也有相应的测试结果
  • 设置执行所有测试
  1. 右键"tests"文件夹,选择"Run"
  2. 接下来就直接跑目录下所有的测试用例了,在下方的"Run"窗口可以看到测试信息
  3. 如果报错找不到模块时,需要打开右上角的编辑启动项,先删除旧信息,否则会有缓存

参考文献

pytest官方文档