Pythons: Python 3.6, 3.7, 3.8, 3.9, PyPy3
Platforms: Linux and Windows
pytest 是一个框架,它使构建简单且可扩展的测试变得容易。测试具有表现力和可读性——不需要样板代码。在几分钟内开始对您的应用程序或库进行小型单元测试或复杂的功能测试。
安装pytest
在命令行中运行以下命令:
pip install -U pytest
检查您是否安装了正确的版本:
$ pytest --version
pytest 6.2.4
创建您的第一个测试
只用四行代码创建一个简单的测试函数:
content of test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
这样就可以了。您现在可以执行测试方法:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-6.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR
collected 1 item
test_sample.py F [100%]
================================= FAILURES =================================
_______________________________ test_answer ________________________________
def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
test_sample.py:6: AssertionError
========================= short test summary info ==========================
FAILED test_sample.py::test_answer - assert 4 == 5
============================ 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 子类化技术来发现测试用例。
当从 rootdir 目录执行 pytest 时,在命令行中没有给出特定目录、文件或测试 ID 时,设置应该搜索测试的目录列表。当所有项目测试都在已知位置时很有用,以加快测试用例收集速度并避免意外获取不需要的测试用例。
[pytest]
testpaths = testing doc
这告诉 pytest 在从根目录执行时只在 testing 和 doc 目录中查找测试用例。
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any char not in seq
默认模式是 ‘.egg’、’.‘、’_darcs’、’build’、’CVS’、’dist’、’node_modules’、’venv’、'{arch}’。设置 norecursedirs 替换默认值。以下是如何避免某些目录的示例:
[pytest]
norecursedirs = .svn _build tmp*
这将告诉 pytest 不要查看典型的 subversion 或 sphinx-build 目录或任何 以tmp 为前缀的目录。
此外,pytest 将尝试通过激活脚本的存在智能地识别和忽略 virtualenv。除非给出 ‑‑collect‑in‑virtualenv ,否则在测试用例收集期间不会考虑任何被视为虚拟环境根目录的目录。另请注意, norecursedirs 优先于 ‑‑collect‑in‑virtualenv;例如如果您打算在具有匹配”.*”的基本目录的 virtualenv 中运行测试,除了使用 ‑‑collect‑in‑virtualenv 标志外,您还必须覆盖 norecursedirs。
断言抛出异常
content of test_sysexit.py
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
以”安静”报告模式执行测试功能:
$ pytest -q test_sysexit.py
. [100%]
1 passed in 0.12s
Note: -q/–quiet 标志使本示例和以下示例中的输出保持简短。
在一个class中对多个测试用例进行分组
如果开发了多个测试用例,可能希望将它们分组到一个类中。 pytest 可以轻松创建包含多个测试的类:
content of test_class.py
class TestClass:
def test_one(self):
x = "this"
assert "h" in x
def test_two(self):
x = "hello"
assert hasattr(x, "check")
pytest 按照 Python 测试发现的约定发现所有测试,因此它会找到两个带有 test_ 前缀的函数。没有必要子类化任何东西,但一定要在你的类前加上 Test 否则这个类将被跳过。我们可以通过传递其文件名来简单地运行模块:
$ pytest -q test_class.py
.F [100%]
================================= FAILURES =================================
____________________________ TestClass.test_two ____________________________
self =
def test_two(self):
x = "hello"
> assert hasattr(x, "check")
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
test_class.py:8: AssertionError
========================= short test summary info ==========================
FAILED test_class.py::TestClass::test_two - AssertionError: assert False
1 failed, 1 passed in 0.12s
第一次测试通过,第二次失败。您可以轻松查看断言中的报错语句来了解执行失败的原因。
在以下场景建议对测试用例进行分组:
- 测试用例的组织
- 仅在该特定类中共享的测试fixture
- 在class级别应用mark并将它们隐式应用于所有测试
在类内对测试进行分组时需要注意的是,每个测试用例都有一个不同的类实例。让每个测试用例共享同一个类实例不能保证测试用例的隔离,造成不好的测试实践。概述如下:
content of test_class_demo.py
class TestClassDemoInstance:
value = 0
def test_one(self):
self.value = 1
assert self.value == 1
def test_two(self):
assert self.value == 1
$ pytest -k TestClassDemoInstance -q
.F [100%]
================================= FAILURES =================================
______________________ TestClassDemoInstance.test_two ______________________
self =
def test_two(self):
> assert self.value == 1
E assert 0 == 1
E + where 0 = .value
test_class_demo.py:9: AssertionError
========================= short test summary info ==========================
FAILED test_class_demo.py::TestClassDemoInstance::test_two - assert 0 == 1
1 failed, 1 passed in 0.12s
为功能测试请求一个唯一的临时目录
content of test_tmpdir.py
def test_needsfiles(tmpdir):
print(tmpdir)
assert 0
在测试函数签名中填写参数tmpdir,pytest 将在执行测试函数调用之前查找并调用装置工厂以创建资源。在测试运行之前,pytest 创建一个唯一的每个测试调用临时目录:
`python
$ pytest -q test_tmpdir.py
F [100%]
================================= FAILURES =================================
_____ test_needsfiles ______
tmpdir = local(‘PYTEST_TMPDIR/test_needsfiles0’)
def test_needsfiles(tmpdir):
print(tmpdir)
assert 0
E assert 0
test_tmpdir.py:3: AssertionError
Original: https://blog.csdn.net/m0_57581736/article/details/119755874
Author: m0_57581736
Title: Pytest-安装和入门
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/775601/
转载文章受原作者版权保护。转载请注明原作者出处!