pytest详解(一)

目录

前言

Pytest是⼀个⽤于编写和执行Python测试的全功能测试框架。它是⼀个第三方库,提供了简洁、灵活和易于使用的方式来编写各种类型的测试,包括单元测试、集成测试和功能测试等。

Pytest是⼀个功能强⼤、易于使用和扩展的Python测试框架,提供了丰富的功能和灵活的测试编写⽅式,使得编写和执行Python测试变得更加⾼效和愉快。

安装

python 复制代码
pip install pytest

检验

python 复制代码
pytest --version
or 
pip show pytest

编写测试文件

测试文件通常以 test_ 开头或以 _test 结尾,测试函数和类也以 test_ 开头。

一个简单完整的pytest的组成结构

1、用例主体部分

2、用例运行语句

python 复制代码
# file name: test_case.py
"""⽤例主体部分"""
# 主体例⼦⼀
def test_case():
 print("⽤例被运⾏")
# 主体例⼦⼆
def test_project_duck():
print("烤鸭店利润计算器开始⼯作")
price1 = int(input("请输⼊你的进货价:")) # input传递来的值,都是str
price2 = int(input("请输⼊你的售卖价:"))
num = int(input("请输⼊你今天卖的鸭⼦数量:"))

result = (price2 - price1) * num
print("今天你的利润额度为{}元".format(result))
python 复制代码
# file name: main.py
"""⽤例运⾏语句"""
import pytest
pytest.main(["-s"])

pytest运行用例时携带的参数(常用)

① -s

表示开启终端交互,其作⽤是可以让打印的内容输出显示在终端中,或者可以在终

端中与⽤例中的输⼊操作进⾏交互

② -v

表示详细输出更详细的输出,包括每个测试⽤例的详细结果和其他相关信息,例如

测试⽤例所在的模块、⽂件路径等。

③ -k

执行用例中包含'关键字'的用例

④ -m

执行'标记'的内容,执行特定的测试用例,执行有相同标记的测试用例

pytest的用例命名规则

在 pytest 中,有关测试用例和测试⽂件的命名规则有⼀些常⻅的约定。以下是

pytest 的命名规则的⼀些建议和最佳实践:

  1. 测试⽂件的命名:
      测试⽂件应以 test_ 开头或以 _test 结尾。这样 pytest 可以自动识别并执行这些⽂件中的测试用例。例如: test_login.pyuser_test.py 。使用有意义的名称来描述被测试的功能或模块。例如: test_authentication.pytest_user_management.py
  2. 测试用例的命名:
      测试⽤例函数应以 test 开头。这样 pytest 可以⾃动识别并执行这些函数作为测试⽤例。例如: def test_login_success():def test_add_product_to_cart(): 。建议使用下划线 _ 分隔单词,而不是使用空格或其他特殊字符。
      例如: def test_calculate_total_amount():def test_validate_user_permissions(): 。使用有意义的名称来描述测试的目的和预期结果。例如: test_login_success() 测试登录功能的成功场景, test_calculate_total_amount() 测试计算总金额的功能。
  3. 测试类的命名(可选):
      如果使⽤类来组织测试⽤例,可以使用驼峰命名法(CamelCase)为测试类命名,且开头需为Test开头。例如: class TestLogin:classTestUserManagement: 。测试类中的测试⽤例函数仍然应遵循以 test 开头的命名规则。

pytest的常用运行方式

python 复制代码
pytest tests/test_module.py::test
pytest tests/test_module.py
pytest tests/

pytest指定运行用例

指定运行一个文件夹中的用例

python 复制代码
#file name: main.py
import pytest
pytest.main(['tests/'])

指定运行一个文件夹中的一个文件中的用例

python 复制代码
# file name: main.py
import pytest
pytest.main(['tests/test_module.py'])

指定运行一个文件夹中的一个文件中的一个用例

python 复制代码
# file name: main.py
import pytest
pytest.main(['tests/test_module.py::test'])

pytest的用例前置和后置处理

pytest 中,你可以使用 setupteardown 函数来定义测试用例的前置和后置

操作。

  1. setup 函数:它会在每个测试⽤例执行之前运行,用于设置测试环境和准备测试数据。
  2. teardown 函数:它会在每个测试用例执行之后运行,⽤于清理测试环境和资源。
    以下是使用 setupteardown 的示例:
python 复制代码
def setup():
	# 前置操作
	print("执⾏前置操作")
	def teardown():
	# 后置操作
	print("执⾏后置操作")
	def test_example():
	# 测试⽤例
	print("执⾏测试⽤例")

pytest 中,除了全局的 setupteardown 函数之外,还可以定义不同级别的
setupteardown 函数,以满足不同的测试需求。这些级别包括:

  1. 模块级别的 setup 和 teardown
       pytest_setup_modulepytest_teardown_module :在整个测试模块的
    开始和结束时运⾏。
    示例:
python 复制代码
def pytest_setup_module():
	# 模块级别的前置操作
	print("执⾏模块级别的前置操作")
def pytest_teardown_module():
	# 模块级别的后置操作
	print("执⾏模块级别的后置操作")
  1. 类级别的 setupteardown
      setup_classteardown_class :在测试类的开始和结束时运行。
    示例:
python 复制代码
class TestClass:
	@classmethod
	def setup_class(cls):
	# 类级别的前置操作
	print("执⾏类级别的前置操作")
	@classmethod
	def teardown_class(cls):
	# 类级别的后置操作
	print("执⾏类级别的后置操作")
  1. ⽅法级别的 setupteardown
      setup_methodteardown_method :在每个测试⽅法的开始和结束时运
    ⾏。
    示例:
python 复制代码
class TestClass:
	def setup_method(self, method):
		# ⽅法级别的前置操作
		print("执⾏⽅法级别的前置操作")
	def teardown_method(self, method):
		# ⽅法级别的后置操作
		print("执⾏⽅法级别的后置操作")
	def test_example(self):
		# 测试⽤例
		print("执⾏测试⽤例")

通过定义不同级别的 setupteardown 函数,你可以灵活地控制测试用例的前置和后置操作,并在不同的级别上进⾏特定的设置和清理工作。这有助于更好地组织和管理测试代码,并提供更细粒度的控制。

pytest的标签使用

Pytest中,标签(也称为标记)是⼀种用于对测试用例进行分类或分组的机制通过为测试用例添加标签,可以在运行测试时选择性地执行特定标签的测试用例,从而方便地控制测试的范围和目标。

Pytest的标签功能基于装饰器来实现。可以使用 @pytest.mark 装饰器为测试函数或测试类添加标签。常见的用法是在测试函数或测试类上方添加装饰器,并指定相应的标签。

以下是使用Pytest标签的示例:

python 复制代码
import pytest
@pytest.mark.smoke
def test_login():
	# 测试登录功能
	assert True
@pytest.mark.regression
def test_registration():
	# 测试注册功能
	assert True
@pytest.mark.smoke
def test_add_to_cart():
	# 测试添加到购物⻋功能
	assert True
@pytest.mark.regression
def test_checkout():
	# 测试结账功能
	assert True

在项目根目录下的 pytest.ini 文件中可以指定全局标记,以应用于整个项⽬:

python 复制代码
iniCopy code
[pytest]
markers =
 smoke: Run smoke tests
 regression: Run regression tests

pytest的conftest的使用

当使用 Pytest 进行测试时, conftest.py 是⼀个特殊的文件,用于管理测试用例中需要通用数据传递。下⾯是⼀些简单的例⼦来说明 conftest.py 的使⽤。

定义⼀个简单的夹具(fixture):

python 复制代码
import pytest
@pytest.fixture
def setup_data():
	return [1, 2, 3, 4, 5]

conftest.py 中定义了⼀个名为 setup_data 的夹具。这个夹具可以在测试中

被使⽤,如下所示:

python 复制代码
def test_sum(setup_data):
	assert sum(setup_data) == 15
def test_traversal(setup_data):
	for i in setup_data:
		assert i in setup_data

pytest.fixturePytest 测试框架中的⼀个装饰器,用于定义测试用例中需要共享的资源、数据或设置的函数。它可以在测试用例执行之前、之后或在每个测试用例之前、之后运行,并提供⼀种方便的方式来管理测试用例的前置条件和后置操作。

使用 pytest.fixture 装饰器,你可以创建⼀个被 Pytest 自动调用的函数,该函数可以为测试用例提供所需的初始化步骤或共享的数据。这个函数可以返回⼀个值,该值将作为参数传递给测试用例函数。

通过使用 pytest.fixture ,你可以更方便地管理测试用例的前置条件和后置操作,实现测试数据的共享和代码的重用,从而使测试代码更加简洁、可维护和可扩展。

pytest.fixture 装饰器可以接受⼀些参数,用于配置和定制 fixture 函数的行为。

以下是⼀些常用的参数:

  1. scope :指定 fixture 的作用域。可以设置为以下几个值之⼀:
    "function" (默认值):每个测试函数都会调用⼀次 fixture。
    "class" :每个测试类都会调用⼀次 fixture。
    "module" :每个测试模块都会调用⼀次 fixture。
    "session" :整个测试会话只会调用⼀次 fixture。

  2. params :参数化 fixture,可以根据不同的参数值生成多个独立的 fixture 实例。
    可以传递⼀个可迭代对象,每个元素都会作为参数值调用fixture。

  3. autouse :自动使用 fixture,无需在测试函数中显式声明使用该 fixture。可以
    设置为 True 或 False 。

  4. name :为 fixture 指定⼀个自定义名称,用于在测试报告和日志中标识 fixture。

  5. 其他参数:可以根据需要添加其他自定义参数,供 fixture 函数使用。

    下面是⼀个例子,展示了如何使用参数来配置 pytest.fixture

python 复制代码
import pytest
	# 指定 fixture 的作⽤域为测试模块
@pytest.fixture(scope="module")
def setup_module():
	print("Module setup")
# 参数化 fixture
@pytest.fixture(params=[1, 2, 3])
def setup_data(request):
	print(f"Setup data: {request.param}")
	return request.param
# ⾃动使⽤ fixture
@pytest.fixture(autouse=True)
def setup_autouse():
	print("Autouse fixture")
# ⾃定义 fixture 名称
@pytest.fixture(name="custom_fixture")
def setup_custom():
	print("Custom fixture")
# 测试函数使⽤ fixture
def test_example(setup_module, setup_data, custom_fixture):
	print(f"Test example: {setup_data}")
# 在测试类中使⽤ fixture
@pytest.mark.usefixtures("setup_module")
class TestClass:
	def test_class_example(self, setup_data):
		print(f"Class example: {setup_data}")

在上述示例中,我们展示了不同参数的用法。 setup_module fixture 的作用域设置为模块级别,因此在测试模块中只会执行⼀次。 setup_data fixture 使用参数化配置,会根据不同的参数值生成多个独立的 fixture 实例。

setup_autouse fixture 设置为自动使用,无需在测试函数中显式声明使用该 fixturecustom_fixture fixture使用自定义名称。 test_example 测试函数使用了多个fixture,并打印出相应的信息。 TestClass 测试类使用了 setup_module fixture,并在测试方法中使用了setup_data fixture

通过使用不同的参数配置,可以灵活地定制和管理 pytest.fixture,以满足测试用例的需求。

pytest的ini文件的使用

Pytest 支持使用 pytest.ini 文件来配置测试运行的各种选项和参数。 pytest.ini 文件位于测试项目的根目录下,可以通过在该文件中设置不同的选项来自定义测试的行为。下面是⼀些 pytest.ini 文件的使用示例和说明:

  1. 配置默认的命令行选项:
python 复制代码
[pytest] [pytest]
addopts = -v -s

上述配置使用 addopts 选项指定了默认的命令行选项, -v 表示启用详细输

出, -s 表示禁止捕获标准输出。

  1. 选择要运行的测试文件或目录:
python 复制代码
[pytest] [pytest]
testpaths = tests/

上述配置使用 testpaths 选项指定了要运行的测试文件或目录的路径。

  1. ⾃定义夹具搜索规则:
python 复制代码
[pytest] [pytest]
addopts = -v -s
[pytest] [pytest]
testpaths = tests/

上述配置使⽤ python_filespython_classespython_functions 选项指定了自定义夹具的搜索规则,分别指定了测试⽂件、测试类和测试函数的名称模式。

  1. 禁用某些插件:
python 复制代码
[pytest] [pytest]
addopts = --disable-warnings

上述配置使⽤ addopts 选项指定了禁用某些插件的选项, --disable-warnings 表示禁⽤警告信息。

这些是⼀些 pytest.ini 文件的示例配置,你可以根据需要设置不同的选项来⾃定义测试的⾏为。通过编辑和配置 pytest.ini ⽂件,你可以⽅便地管理测试项⽬的各种选项和参数,提⾼测试的灵活性和可定制性。

请注意, pytest.ini ⽂件中的选项和参数设置将适⽤于整个测试项⽬,但也可以在命令行中使用选项覆盖部分配置。

相关推荐
FINE!(正在努力!)20 小时前
PyTest框架学习
学习·pytest
程序员杰哥1 天前
接口自动化测试之pytest 运行方式及前置后置封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
测试老哥2 天前
Pytest+Selenium UI自动化测试实战实例
自动化测试·软件测试·python·selenium·测试工具·ui·pytest
水银嘻嘻2 天前
07 APP 自动化- appium+pytest+allure框架封装
python·appium·自动化·pytest
天才测试猿2 天前
接口自动化测试之pytest接口关联框架封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
not coder3 天前
Pytest Fixture 详解
数据库·pytest
not coder4 天前
pytest 常见问题解答 (FAQ)
开发语言·python·pytest
程序员的世界你不懂4 天前
(1)pytest简介和环境准备
pytest
not coder4 天前
Pytest Fixture 是什么?
数据库·oracle·pytest
Tester_孙大壮4 天前
pytest中的元类思想与实战应用
pytest