• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

python unittest和pytest,选哪个?

武飞扬头像
诸葛老刘
帮助1

1.背影

近期项目中,纠结使用unittest 还是pytest, 这篇博文将解决这个问题,
测试过程中, 有两种方式:

  • 自动化测试 (automated testing)
  • 手动测试(manual testing)

我想你会毫不犹豫的选择自动化测试

2. pytest VS unittest的区别

2.1 pytest (推荐使用)

  • 仅需要编写函数,并断言验证功能即可
  • 更易用使用, 代码简单,紧凑,高效

2.2 unittest

python unittest 是受到了java的 junit 启发开发的,

  • 必须编写类, 在类中编写函数,并断言验证功能
  • python 内置默认的测试框架
  • 必须导入模块,创建一个类, 并在类中定义测试功能

3. 使用方法

3.1 pytest

  • 安装及验证安装是否成功
(sse38)  mac$ pip install -U pytest
(sse38)  mac$ pytest --version
pytest 7.0.1
(sse38)  mac$ pytest -V
pytest 7.0.1
  • 最简单的使用方法
# 这是正常的代码
(sse38)  mac$ cat mycode.py 
def add(x:int, y:int)->int:
    return x y

# 这是测试的代码,也就是判断输入和预期输出是否一致
(sse38)  mac$ cat test_mycode.py 
from mycode import add


def test_add():
    assert(add(3,5), 8)  # 这里用到了断言

# 单独运行这一个测试文件
(sse38)  mac$ pytest test_mycode.py
========================================================================= test session starts =========================================================================
platform darwin -- Python 3.8.13, pytest-7.0.1, pluggy-1.0.0
rootdir: /Users/mac/projects/
collected 1 item                                                                                                                                                      

test_mycode.py .                                                                                                                                                [100%]

========================================================================== 1 passed in 0.01s ==========================================================================

# 可以执行这个目录下所有的测试文件
(sse38)  mac$ pytest test/
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhhkbfhj
系列文章
更多 icon
同类精品
更多 icon
继续加载