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

Pytest-安装和入门

武飞扬头像
m0_57581736
帮助1

Pythons: Python 3.6, 3.7, 3.8, 3.9, PyPy3

Platforms: Linux and Windows

PyPI package namepytest

Documentation as PDFdownload latest

pytest 是一个框架,它使构建简单且可扩展的测试变得容易。测试具有表现力和可读性——不需要样板代码。在几分钟内开始对您的应用程序或库进行小型单元测试或复杂的功能测试。

安装pytest

在命令行中运行以下命令:

pip install -U pytest

检查您是否安装了正确的版本:

  1.  
    $ pytest --version
  2.  
    pytest 6.2.4

创建您的第一个测试

只用四行代码创建一个简单的测试函数:

  1.  
    # content of test_sample.py
  2.  
    def func(x):
  3.  
    return x 1
  4.  
     
  5.  
     
  6.  
    def test_answer():
  7.  
    assert func(3) == 5

这样就可以了。您现在可以执行测试方法:

  1.  
    $ pytest
  2.  
    =========================== test session starts ============================
  3.  
    platform linux -- Python 3.x.y, pytest-6.x.y, py-1.x.y, pluggy-0.x.y
  4.  
    cachedir: $PYTHON_PREFIX/.pytest_cache
  5.  
    rootdir: $REGENDOC_TMPDIR
  6.  
    collected 1 item
  7.  
     
  8.  
    test_sample.py F [100%]
  9.  
     
  10.  
    ================================= FAILURES =================================
  11.  
    _______________________________ test_answer ________________________________
  12.  
     
  13.  
    def test_answer():
  14.  
    > assert func(3) == 5
  15.  
    E assert 4 == 5
  16.  
    E where 4 = func(3)
  17.  
     
  18.  
    test_sample.py:6: AssertionError
  19.  
    ========================= short test summary info ==========================
  20.  
    FAILED test_sample.py::test_answer - assert 4 == 5
  21.  
    ============================ 1 failed in 0.12s =============================
学新通

[100%] 是指运行所有测试用例的总体进度。完成后,pytest 会显示失败报告,因为 func(3) 不返回 5。

Note:

您可以使用 assert 语句来验证测试预期。 pytest 的高级断言自省将智能地报告断言表达式的中间值,因此您可以避免 JUnit 遗留方法的许多名称。

运行多个测试

pytest 将运行当前目录及其子目录中 test_*.py 或 *_test.py 形式的所有文件。更一般地说,它遵循标准的测试发现规则。

pytest 实现以下标准测试发现规则:

  • 如果未指定参数,则从testpaths(如果已配置)或当前目录开始收集用例。或者,命令行参数可用于目录、文件名或节点 ID 的任意组合。
  • 在目录中递归遍历,直到匹配 norecursedirs。norecursedirs在pytest.ini进行配置。
  • 在这些目录中,搜索 test_*.py 或 *_test.py 文件,按其测试包名称导入。
  • 从这些文件中,收集测试项目:
    • 测试类外的以test为前缀的函数或方法
    • test 为前缀测试函数或 Test 为前缀测试类中的方法( 这些类不能实现__init__ 方法)

有关如何自定义测试发现更改标准 (Python) 测试发现的示例。在 Python 模块中,pytest 还使用标准的 unittest.TestCase 子类化技术来发现测试用例。

testpaths

当从 rootdir 目录执行 pytest 时,在命令行中没有给出特定目录、文件或测试 ID 时,设置应该搜索测试的目录列表。当所有项目测试都在已知位置时很有用,以加快测试用例收集速度并避免意外获取不需要的测试用例。

  1.  
    [pytest]
  2.  
    testpaths = testing doc

这告诉 pytest 在从根目录执行时只在 testing 和 doc 目录中查找测试用例。

norecursedirs

设置目录的basename模式,以避免在递归时进行的测试用例发现。单个(fnmatch 样式)模式应用于目录的基本名称,以决定是否递归进入该目录。模式匹配字符:

  1.  
    * matches everything
  2.  
    ? matches any single character
  3.  
    [seq] matches any character in seq
  4.  
    [!seq] matches any char not in seq

默认模式是 '*.egg'、'.*'、'_darcs'、'build'、'CVS'、'dist'、'node_modules'、'venv'、'{arch}'。设置 norecursedirs 替换默认值。以下是如何避免某些目录的示例:

  1.  
    [pytest]
  2.  
    norecursedirs = .svn _build tmp*

这将告诉 pytest 不要查看典型的 subversion 或 sphinx-build 目录或任何 以tmp 为前缀的目录。

此外,pytest 将尝试通过激活脚本的存在智能地识别和忽略 virtualenv。除非给出 ‑‑collect‑in‑virtualenv ,否则在测试用例收集期间不会考虑任何被视为虚拟环境根目录的目录。另请注意, norecursedirs 优先于 ‑‑collect‑in‑virtualenv;例如如果您打算在具有匹配“.*”的基本目录的 virtualenv 中运行测试,除了使用 ‑‑collect‑in‑virtualenv 标志外,您还必须覆盖 norecursedirs。


断言抛出异常

使用 raises 来断言某些代码引发了异常:

  1.  
    # content of test_sysexit.py
  2.  
    import pytest
  3.  
     
  4.  
     
  5.  
    def f():
  6.  
    raise SystemExit(1)
  7.  
     
  8.  
     
  9.  
    def test_mytest():
  10.  
    with pytest.raises(SystemExit):
  11.  
    f()

以“安静”报告模式执行测试功能:

  1.  
    $ pytest -q test_sysexit.py
  2.  
    . [100%]
  3.  
    1 passed in 0.12s

Note: -q/--quiet 标志使本示例和以下示例中的输出保持简短。

在一个class中对多个测试用例进行分组

如果开发了多个测试用例,可能希望将它们分组到一个类中。 pytest 可以轻松创建包含多个测试的类:

  1.  
    # content of test_class.py
  2.  
    class TestClass:
  3.  
    def test_one(self):
  4.  
    x = "this"
  5.  
    assert "h" in x
  6.  
     
  7.  
    def test_two(self):
  8.  
    x = "hello"
  9.  
    assert hasattr(x, "check")

pytest 按照 Python 测试发现的约定发现所有测试,因此它会找到两个带有 test_ 前缀的函数。没有必要子类化任何东西,但一定要在你的类前加上 Test 否则这个类将被跳过。我们可以通过传递其文件名来简单地运行模块:

  1.  
    $ pytest -q test_class.py
  2.  
    .F [100%]
  3.  
    ================================= FAILURES =================================
  4.  
    ____________________________ TestClass.test_two ____________________________
  5.  
     
  6.  
    self = <test_class.TestClass object at 0xdeadbeef>
  7.  
     
  8.  
    def test_two(self):
  9.  
    x = "hello"
  10.  
    > assert hasattr(x, "check")
  11.  
    E AssertionError: assert False
  12.  
    E where False = hasattr('hello', 'check')
  13.  
     
  14.  
    test_class.py:8: AssertionError
  15.  
    ========================= short test summary info ==========================
  16.  
    FAILED test_class.py::TestClass::test_two - AssertionError: assert False
  17.  
    1 failed, 1 passed in 0.12s
学新通

第一次测试通过,第二次失败。您可以轻松查看断言中的报错语句来了解执行失败的原因。

在以下场景建议对测试用例进行分组:

  • 测试用例的组织
  • 仅在该特定类中共享的测试fixture
  • 在class级别应用mark并将它们隐式应用于所有测试

在类内对测试进行分组时需要注意的是,每个测试用例都有一个不同的类实例。让每个测试用例共享同一个类实例不能保证测试用例的隔离,造成不好的测试实践。概述如下:

  1.  
    # content of test_class_demo.py
  2.  
    class TestClassDemoInstance:
  3.  
    value = 0
  4.  
     
  5.  
    def test_one(self):
  6.  
    self.value = 1
  7.  
    assert self.value == 1
  8.  
     
  9.  
    def test_two(self):
  10.  
    assert self.value == 1
  1.  
    $ pytest -k TestClassDemoInstance -q
  2.  
    .F [100%]
  3.  
    ================================= FAILURES =================================
  4.  
    ______________________ TestClassDemoInstance.test_two ______________________
  5.  
     
  6.  
    self = <test_class_demo.TestClassDemoInstance object at 0xdeadbeef0002>
  7.  
     
  8.  
    def test_two(self):
  9.  
    > assert self.value == 1
  10.  
    E assert 0 == 1
  11.  
    E where 0 = <test_class_demo.TestClassDemoInstance object at 0xdeadbeef0002>.value
  12.  
     
  13.  
    test_class_demo.py:9: AssertionError
  14.  
    ========================= short test summary info ==========================
  15.  
    FAILED test_class_demo.py::TestClassDemoInstance::test_two - assert 0 == 1
  16.  
    1 failed, 1 passed in 0.12s
学新通

为功能测试请求一个唯一的临时目录

pytest 提供内置装置/函数参数来请求任意资源,像一个独立的临时目录:

  1.  
    # content of test_tmpdir.py
  2.  
    def test_needsfiles(tmpdir):
  3.  
    print(tmpdir)
  4.  
    assert 0

在测试函数签名中填写参数tmpdir,pytest 将在执行测试函数调用之前查找并调用装置工厂以创建资源。在测试运行之前,pytest 创建一个唯一的每个测试调用临时目录:

  1.  
    $ pytest -q test_tmpdir.py
  2.  
    F [100%]
  3.  
    ================================= FAILURES =================================
  4.  
    _____________________________ test_needsfiles ______________________________
  5.  
     
  6.  
    tmpdir = local('PYTEST_TMPDIR/test_needsfiles0')
  7.  
     
  8.  
    def test_needsfiles(tmpdir):
  9.  
    print(tmpdir)
  10.  
    > assert 0
  11.  
    E assert 0
  12.  
     
  13.  
    test_tmpdir.py:3: AssertionError
  14.  
    --------------------------- Captured stdout call ---------------------------
  15.  
    PYTEST_TMPDIR/test_needsfiles0
  16.  
    ========================= short test summary info ==========================
  17.  
    FAILED test_tmpdir.py::test_needsfiles - assert 0
  18.  
    1 failed in 0.12s
学新通

有关 tmpdir 处理的更多信息可在临时目录和文件中找到。

使用以下命令列出存在pytest 支持的内置fixture:

pytest --fixtures   # shows builtin and custom fixtures

请注意,除非添加了 -v 选项,否则此命令会忽略带有前导 _ 的测试fixture。

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

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