• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-02-20) 23次浏览 已收录 0个评论
文章目录[隐藏]

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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:关于python:真实项目中如何使用pytest进行单元测试结合PyCharm

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址