1.pytest的概念
Pytest是⼀个⽤于编写和执⾏Python测试的全功能测试框架。它是⼀个第三⽅库,提 供了简洁、灵活和易于使⽤的⽅式来编写各种类型的测试,包括单元测试、集成测试 和功能测试等。 Pytest是⼀个功能强⼤、易于使⽤和扩展的Python测试框架,提供了丰富的功能和灵 活的测试编写⽅式,使得编写和执⾏Python测试变得更加⾼效和愉快。
2.pytest的基础
1.⼀个简单完整的pytest组成结构
1、⽤例主体部分
2、⽤例运⾏语句
例子如下
# 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))
# file name: main.py
"""⽤例运⾏语句"""
import pytest
pytest.main(["-s"])
2.pytest运⾏⽤例时携带的参数
-s:表示开启终端交互,其作⽤是可以让打印的内容输出显示在终端中,或者可以在终 端中与 ⽤例中的输⼊操作进⾏交互
-v:表示详细输出更详细的输出,包括每个测试⽤例的详细结果和其他相关信息,例如 测试⽤ 例所在的模块、⽂件路径等。
3.pytest的⽤例命名规则
在 pytest 中,有关测试⽤例和测试⽂件的命名规则有⼀些常⻅的约定。以下是 pytest 的命 名规则的⼀些建议和最佳实践:
1. 测试⽂件的命名:
测试⽂件应以 "test_" 开头或以 "_test" 结尾。这样 pytest 可以⾃动识 别并执⾏这些⽂ 件中的测试⽤例。例如: test_login.py 或 user_test.py 。 使⽤有意义的名称来描述被 测试的功能或模块。例 如: test_authentication.py 或 test_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: 或 class TestUserManagement: 。
测试类中的测试⽤例函数仍然应遵循以 "test" 开头的命名规则
4.pytest的常⽤运⾏⽅式
pytest命令⾏运⾏
命令行的运行方式中:
pytest <===> pytest.main([])
pytest -s <===> pytest.main(["-s"])
pytest -s -v <===> pytest.main(["-s","-v"])
pytest -sv <===> pytest.main(["-sv"])
pytest -vs <===> pytest.main(["-vs"])
pytest test_01.py::Test01::test001 -sv <===> pytest.main(["test_01.py::Test01::test001", "-vs"])
"""
pytest指定运⾏⽤例
指定运⾏⼀个⽂件夹中的⽤例
# file name: main.py
import pytest
pytest.main(['tests/'])
指定运⾏⼀个⽂件夹中的⼀个⽂件中的⽤例
# file name: main.py
import pytest
pytest.main(['tests/test_module.py'])
指定运⾏⼀个⽂件夹中的⼀个⽂件中的⼀个⽤例
# file name: main.py
import pytest
pytest.main(['tests/test_module.py::test'])
pytest运⽤-k筛选⽤例
在Pytest中, -k 选项⽤于通过表达式筛选和运⾏匹配的测试⽤例。使⽤ -k 选项,可 以 指定⼀个字符串表达式,Pytest将根据表达式匹配测试⽤例的名称来执⾏相应的测试。
以下是⼀个例⼦,假设有以下测试⽂件 test_math_functions.py :
# file name: test_file2.py
def test_addition():
assert 2 + 2 == 4
def test_subtraction():
assert 5 - 3 == 2
def test_multiplication():
assert 3 * 4 == 12
def test_division():
assert 10 / 2 == 5
要运⾏匹配名称包含 addition 的测试⽤例,可以使⽤以下命令:
pytest -k "addition"
要运⾏匹配名称以 test_ 开头且进⾏加法测试的测试⽤例,可以使⽤以下命令:
pytest -k "test_addition"
这样,Pytest将运⾏匹配的测试⽤例并输出结果。你可以根据⾃⼰的需求和测试⽤例 的命名⽅式来使⽤ -k 选项进⾏灵活的筛选和执⾏测试⽤例。
5.pytest的⽤例前置和后置处理
用例级别:
模块级(setup_module/teardown_module)开始于模块始末,全局的
函数级(setup_function/teardown_function)只对函数用例生效(不在类中)
类级(setup_class/teardown_class)只在类中前后运行一次(在类中)
方法级(setup_method/teardown_method)开始于方法始末(在类中)
类里面的(setup/teardown)运行在调用方法的前后
1.setup_module/teardown_module:所有用例开始执行前执行一次/所有用例执行结束后执行一次
def setup_module(): # ---> setup
# 前置操作
print("执行模块级别前置操作")
def teardown_module(): # ---> teardown
# 后置操作
print("执行模块级别后置操作")
def test_example1():
# 测试用例
print("执行测试用例test_example1")
def test_example2():
# 测试用例
print("执行测试用例test_example2")
def setup_function():
# 模块级别的前置操作
print("执行函数级别的前置操作")
def teardown_function():
# 模块级别的后置操作
print("执行函数级别的后置操作")
2.类级别的前置操作 前面最好加classmethod
class TestClass:
@classmethod
def setup_class(cls):
# 类级别的前置操作
print("执行类级别的前置操作")
@classmethod
def teardown_class(cls):
# 类级别的后置操作
print("执行类级别的后置操作")
def test0021(self):
print("执行测试用例test0021")
def test0022(self):
print("执行测试用例test0022")
3. ⽅法级别的 setup 和 teardown : setup_method 和 teardown_method :在每个测试⽅法的开始和结束时运 ⾏ 结合类级别和。 示例
class TestClass:
def setup_method(self, method):
# 方法级别的前置操作
print("执行方法级别的前置操作")
def teardown_method(self, method):
# 方法级别的后置操作
print("执行方法级别的后置操作")
def test_example1(self):
# 测试用例
print("执行测试用例test_example1")
def test_example2(self):
# 测试用例
print("执行测试用例test_example2")
def test_example3(self):
# 测试用例
print("执行测试用例test_example3")
@classmethod
def setup_class(cls):
# 类级别的前置操作
print("执行类级别的前置操作")
@classmethod
def teardown_class(cls):
# 类级别的后置操作
print("执行类级别的后置操作")
pytest的标签使⽤
在Pytest中,标签(也称为标记)是⼀种⽤于对测试⽤例进⾏分类或分组的机制。通 过为测试⽤例添加标签,可以在运⾏测试时选择性地执⾏特定标签的测试⽤例,从⽽ ⽅便地控制测试的范围和⽬标。
Pytest的标签功能基于装饰器来实现。可以使⽤ @pytest.mark 装饰器为测试函数或 测试类添加标签。常⻅的⽤法是在测试函数或测试类上⽅添加装饰器,并指定相应的 标签
示例如下
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 ⽂件中可以指定全局标记,以应⽤于整个项⽬:
[pytest]
markers =
smoke: Run smoke tests
regression: Run regression tests
cf: 这是对标签的解释
在上⾯的例⼦中,我们为每个测试函数添加了不同的标签。 @pytest.mark.smoke
和 @pytest.mark.regression 是两个⾃定义的标签,你可以根据项⽬需求定义和使
⽤⾃⼰的标签。
要运⾏特定标签的测试⽤例,可以使⽤ -m 选项并指定标签名称。例如,要运⾏标记
为"smoke"的测试⽤例,可以使⽤以下命令
pytest -m smoke
可以同时指定多个标签,使⽤逻辑运算符组合它们。例如,要运⾏带 有"smoke"或"regression"标签的测试⽤例,可以使⽤以下命令:
pytest -m "smoke or regression"
这将执⾏带有"smoke"或"regression"标签的测试⽤例(在上⾯的示例中,所有四个 测试⽤例)。
标签功能使得对测试⽤例进⾏分组和选择变得更加灵活和⽅便。你可以根据测试⽤例 的特性、优先级或执⾏需求来定义标签,并使⽤相应的命令⾏选项来选择要执⾏的测 试⽤例
部分逻辑如下
import pytest
pytest.main(["-vs", "-m", "smoke"])
# pytest.main(["-vs"])
# pytest.main(["-vs", "-m", "cf"])
"""
标签支持逻辑筛选
"""
# pytest.main(["-vs", "-m", "cf"]) # 是
# pytest.main(["-m", "not cf", "-vs"]) # 非
# pytest.main(["-vs", "-m", "cf or smoke"]) # 或
# pytest.main(["-vs", "-m", "cf and smoke"]) # 和
6.pytest的conftest的使⽤
当使⽤ Pytest 进⾏测试时, conftest.py 是⼀个特殊的⽂件,⽤于管理测试⽤例中需要通⽤数据传递。下⾯是⼀些简单的例⼦来说明 conftest.py 的使⽤。
import pytest
@pytest.fixture
def setup_data():
return [1, 2, 3, 4, 5]
在 conftest.py 中定义了⼀个名为 setup_data 的夹具。这个夹具可以在测试中被使⽤,如下所示:
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.fixture 是 Pytest 测试框架中的⼀个装饰器,⽤于定义测试⽤例中需要共享的资源、数据或设置的函数。它可以在测试⽤例执⾏之前、之后或在每个测试⽤例之前、之后运⾏,并提供⼀种⽅便的⽅式来管理测试⽤例的前置条件和后置操作。
使⽤ pytest.fixture 装饰器,你可以创建⼀个被 Pytest ⾃动调⽤的函数,该函数可以为测试⽤例提供所需的初始化步骤或共享的数据。这个函数可以返回⼀个值,该值将作为参数传递给测试⽤例函数。
通过使⽤ pytest.fixture ,你可以更⽅便地管理测试⽤例的前置条件和后置操作,实现测试数据的共享和代码的重⽤,从⽽使测试代码更加简洁、可维护和可扩展。
pytest.fixture 装饰器可以接受⼀些参数,⽤于配置和定制 fixture 函数的⾏为。以下是⼀些常⽤的参数
1. scope :指定 fixture 的作⽤域。可以设置为以下⼏个值之⼀
"function" (默认值):每个测试函数都会调⽤⼀次 fixture。
"class" :每个测试类都会调⽤⼀次 fixture。"module" :每个测试模块都会调⽤⼀次 fixture。
"session" :整个测试会话只会调⽤⼀次 fixture。
使用yield来实现后置
yield
print("Function teardown")
2.params :参数化 fixture,可以根据不同的参数值⽣成多个独⽴的 fixture 实例。
可以传递⼀个可迭代对象,每个元素都会作为参数值调⽤ fixture。
3. autouse :⾃动使⽤ fixture,⽆需在测试函数中显式声明使⽤该 fixture。可以设置为 True 或 False 。
4. name :为 fixture 指定⼀个⾃定义名称,⽤于在测试报告和⽇志中标识 fixture
5. 其他参数:可以根据需要添加其他⾃定义参数,供 fixture 函数使⽤。
示例如下:
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 设置为⾃动使⽤,⽆需在测试函数中显式声明使⽤该 fixture。 custom_fixture fixture使⽤⾃定义名称。 test_example 测试函数使⽤了多个 fixture,并打印出相应的信息。 TestClass 测试类使⽤了 setup_module fixture,并在测试⽅法中使⽤了setup_data fixture。
7.pytest的ini⽂件的使⽤
Pytest ⽀持使⽤ pytest.ini ⽂件来配置测试运⾏的各种选项和参数。 pytest.ini ⽂件位于测试项⽬的根⽬录下,可以通过在该⽂件中设置不同的选项来⾃定义测试的⾏为。下⾯是⼀些 pytest.ini ⽂件的使⽤示例和说明:
1. 配置默认的命令⾏选项:
[pytest] [pytest]
addopts = -v -s
上述配置使⽤ addopts 选项指定了默认的命令⾏选项, -v 表示启⽤详细输出, -s 表示禁⽌捕获标准输出
2. 选择要运⾏的测试⽂件或⽬录:
[pytest] [pytest]
testpaths = tests/
上述配置使⽤ testpaths 选项指定了要运⾏的测试⽂件或⽬录的路径。
3. ⾃定义夹具搜索规则:
[pytest] [pytest]
python_files = test_*.py
python_classes = Test*
python_functions = test_*
上述配置使⽤ python_files 、 python_classes 和 python_functions 选项指定了⾃定义夹具的搜索规则,分别指定了测试⽂件、测试类和测试函数的名称模式
4. 禁⽤某些插件:
[pytest] [pytest]
addopts = --disable-warnings
上述配置使⽤ addopts 选项指定了禁⽤某些插件的选项, --disablewarnings 表示禁⽤警告信息。
这些是⼀些 pytest.ini ⽂件的示例配置,你可以根据需要设置不同的选项来⾃定义测试的⾏为。通过编辑和配置 pytest.ini ⽂件,你可以⽅便地管理测试项⽬的各种选项和参数,提⾼测试的灵活性和可定制性。