使用 Pytest 进行测试

介绍

使用 Pytest 进行测试

pytest可用于所有类型和级别的软件测试。许多项目——包括 Mozilla 和 Dropbox——从 unittest 或nose 切换到 pytest。

使用 Pytest 的简单第一个示例

pytest 用于测试的测试文件必须以 test_ 开头或以 _test.py 结尾 我们将通过为文件 fibonacci.py 编写测试文件 test_fibonacci.py 来演示工作方式。两个文件都在一个目录中:

第一个文件是应该测试的文件。我们假设它被保存为 fibonacci_p.py:

def fib(n):
    旧的,新的 = 0, 1
    对于 _ 范围(n):
        旧,新 = 新,旧 + 新
    返老还童

现在,我们必须提供文件 test_fibonacci.py 的代码。’pytest’ 将使用此文件:

从 fibonacci_p 导入 fib
def test_fib():
    断言 fib(0) == 0
    断言 fib(1) == 1
    断言 fib(10) == 55

我们在上面显示的两个文件所在的目录中的命令 shell 中调用 pytest:

pytest

这段代码的结果如下所示:

============================ 测试会话开始 ================== ============
linux 平台——Python 3.7.1、pytest-4.0.2、py-1.7.0、pluggy-0.8.0
rootdir: /home/bernd/, inifile:
插件:remotedata-0.3.1、openfiles-0.3.1、doctestplus-0.2.0、arraydiff-0.3
收集了 1 项
test_fibonacci.py 。[100%]
============================ 1 在 0.01 秒内通过 ================== ==========

我们现在创建了一个错误的 fib 版本。我们将两个起始值从 0 和 1 更改为值 2 和 1。这是卢卡斯数列的开始,但由于我们要实现斐波那契数列,这是错误的。这样,我们可以研究 pytest 在这种情况下的行为:

def fib(n):
    旧的,新的 = 2, 1
    对于 _ 范围(n):
        旧,新 = 新,旧 + 新
    返老还童

使用斐波那契的这种错误实现调用 ‘pytest’ 会得到以下结果:

$ pytest ============================== 测试会话开始 ================ ==============
linux 平台——Python 3.7.1、pytest-4.0.2、py-1.7.0、pluggy-0.8.0
rootdir: /home/bernd/, inifile:
插件:remotedata-0.3.1、openfiles-0.3.1、doctestplus-0.2.0、arraydiff-0.3
收集了 1 项
test_fibonacci.py F [100%]
====================================失败============== ======================
___________________________________ test_fib ___________________________________
    def test_fib():
> 断言 fib(0) == 0
E 断言 2 == 0
E + 其中 2 = fib(0)
test_fibonacci.py:5: 断言错误
========================== 0.03 秒内失败 1 ================== ==========

另一个 Pytest 示例 (1)

在下一个示例中,我们将更接近”现实”。在现实生活中,我们通常会有多个文件,对于每个文件,我们可能有一个对应的测试文件。每个测试文件可能包含各种测试。我们的示例文件夹 ex2 中有各种文件:

需要测试的文件:

  • 斐波那契.py
  • foob​​ar_plus.py
  • foob​​ar.py

测试文件:

  • test_fibonacci.py
  • test_foobar_plus.py
  • test_foobar.py

我们在目录 ‘ex2’ 中启动 ‘pytest’ 并得到以下结果:

$ pytest
==================== 测试会话开始 ======================
linux 平台——Python 3.7.3、pytest-4.3.1、py-1.8.0、pluggy-0.9.0
rootdir: /home/bernd/ex2, inifile:
插件:remotedata-0.3.1、openfiles-0.3.2、doctestplus-0.3.0、arraydiff-0.3
收集 4 项
test_fibonacci.py 。[ 25%]

Original: https://blog.csdn.net/pydby01/article/details/122313122
Author: IT娜娜
Title: 使用 Pytest 进行测试

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/772567/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球