关于python:真实项目中如何使用pytest进行单元测试结合PyCharm

8次阅读

共计 1397 个字符,预计需要花费 4 分钟才能阅读完成。

应用 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 官网文档

正文完
 0