fixture实现自定义前置、后置
阅读目录:
1. 自定义前置(setup)、后置(teardown)
2. 示例:仅test_a 和test_b 需要前置登录、 后置登出
3. 若yield 前面的代码出现异常,yield后面的代码不会执行
4. 若测试用例出现异常,yield前后的代码都会执行
自定义前置(setup)、后置(teardown)
- fixture 可以实现自定义测试用例的前置、后置,是通过yield来区分的, 前后置均可单独存在
- 写在yield 前面的是 前置条件, 写在yield 后面的是 后置条件
- 如果yield 前面的代码异常,则yield后面的代码不会执行; 但是若测试用例出现异常, yield 前后的代码还是都会运行
示例: 仅提test_a 和 test_b需要 前置登录 后置登出
方法一:yield
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : zcs
# @wx :M_Haynes
# @Blog :
import pytest
import pytest
## 方法一: yield@pytest.fixture()
def setup_teardown():
print(" ------------- 前置")
yield
print(" ------------- 后置")
def test_example5(setup_teardown):
print("--------------- 测试函数是: text_emample5")
class TestTextEmample5:
def test_example_class_1(self, setup_teardown):
print(" --------------------- 测试类是:test_example_class_1")
def test_example_class_2(self):
print("------------------ 测试类是:test_example_class_2")
结果:
扩展 -- yield 在fixture中的作用
- 在Python的unittest框架中,yield关键字用于创建生成器,而在pytest测试框架中,yield被用来创建fixture(固定装置),这是一种特殊的测试函数,用于设置测试环境并提供测试数据。
- 在pytest中,使用yield可以创建一个临时的fixture,它允许你在测试函数执行前后执行代码。这在需要动态地设置和清理测试环境时非常有用。
yield在fixture中的用法
- 在pytest中,一个fixture是一个函数,它通过使用@pytest.fixture装饰器来定义。如果你在fixture函数中使用yield,你可以在yield之前和之后执行代码,这允许你在测试函数执行前后进行设置和清理。
示例
以下是一个使用yield在pytest中创建fixture的示例:
import pytest
@pytest.fixture
def setup_teardown():
print("Setting up the test environment...")
# 这里是设置环境的代码
# 使用yield来暂停fixture的执行,直到测试函数执行完毕
yield
# 测试函数执行完成后,继续执行这里的代码
print("Tearing down the test environment...")
# 这里是清理环境的代码
def test_example(setup_teardown):
print("Running the test...")
在这个例子中,setup_teardown是一个fixture,它使用yield来暂停执行,直到test_example函数执行完毕。
这样,你就可以在测试前后执行一些代码,比如设置和清理测试环境。
使用yield的fixture的优点
- 资源管理:使用yield可以确保资源(如文件句柄、数据库连接等)在使用后得到正确的释放。
- 测试隔离:通过在yield之前和之后执行代码,可以确保每个测试都是独立的,测试之间的状态不会相互影响。
- 动态参数:yield还可以返回动态参数,这些参数可以被测试函数使用,从而提供更灵活的测试配置。
带参数的fixture
yield也可以与参数一起使用,这允许你为测试函数提供动态参数。
import pytest
@pytest.fixture(params=[1, 2, 3])
def setup_teardown1(request):
print("Setting up the test environment with parameter:", request.param)
# 这里是设置环境的代码,可以使用request.param访问参数
yield request.param
print("Tearing down the test environment with parameter:", request.param)
# 这里是清理环境的代码
def test_with_parameter(setup_teardown):
print("Running the test with parameter:", setup_teardown)
这里是测试代码,可以使用setup_teardown变量访问参数
在这个例子中,fixture setup_teardown 接受一个参数列表 [1, 2, 3],
pytest 将为每个参数值运行一次测试函数 test_with_parameter。
fixture中的yield语句返回当前的参数值,测试函数可以使用这个值进行测试。
结果:
方法二:addfinalizer 终结函数
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : zcs
# @wx :M_Haynes
# @Blog :
import pytest
## 带addfinalizer 终结函数
@pytest.fixture()
def setup_teardown2(request):
print(" ------------- 前置")
def after():
print(" ------------- 后置")
request.addfinalizer(after)
def test_example5(setup_teardown2):
print("--------------- 测试函数是: text_emample5")
class TestTextEmample5:
def test_example_class_1(self, setup_teardown2):
print(" --------------------- 测试类是:test_example_class_1")
def test_example_class_2(self):
print("------------------ 测试类是:test_example_class_2")
结果:
扩展 addfinalizer 终结函数在pytest的操作详解
在pytest测试框架中,addfinalizer是一个用于注册一个终结函数(finalizer)的函数,该终结函数将在测试函数执行完成后自动调用
使用addfinalizer的步骤:
导入pytest模块。
在测试函数中,使用addfinalizer注册终结函数。
终结函数将在每个测试函数执行完毕后被调用。
示例: -- pytest中使用 addfinalizer
import pytest
from io import StringIO
def cleanup_stream(stream):
print("Cleaning up StringIO object...")
stream.close()
def test_stringio(request):
stream = StringIO()
# 注册终结函数 -- 这里使用request注册addfinalizer函数
request.addfinalizer(lambda: cleanup_stream(stream))
stream.write("hello")
assert stream.getvalue() == "hello"
print("Test completed successfully.")
# 运行pytest来执行测试
# pytest 会调用 test_stringio 函数,并且在测试完成后调用 cleanup_stream 函数
注解:在这个示例中,test_stringio函数创建了一个StringIO对象,
并使用addfinalizer注册了一个名为cleanup_stream的终结函数,该函数接受stream作为参数,并在测试完成后关闭它。
无论测试成功还是失败,cleanup_stream都会被调用以清理资源。
运行结果:
注意事项
- 终结函数应该能够处理异常,因为即使测试函数抛出异常,终结函数也会被调用。
- 终结函数不应该依赖于测试函数的执行结果,因为它们会在测试函数执行完毕后立即调用。
- 如果测试函数中使用了多个资源,可以为每个资源注册不同的终结函数。
若yield 前面的代码出现异常了,yield后面的代码不会执行
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : zcs
# @wx :M_Haynes
# @Blog : https://blog.csdn.net/Maynes?type=blog
import pytest
@pytest.fixture()
def setup_teardown():
print(" ------------------- 前置环境")
raise Exception("示例异常")
yield
print(" ------------------- 后置环境")
def test_sub_case(setup_teardown):
print(" ------------------------ 执行用例 ")
结果:
若测试用例出现异常,yield前后的代码都会执行
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : zcs
# @wx :M_Haynes
# @Blog : https://blog.csdn.net/Maynes?type=blog
import pytest
@pytest.fixture()
def setup_teardown():
print(" ---------------------- 前置环境")
yield
print(" ---------------------- 后置环境")
def test_example10(setup_teardown):
raise Exception(" 测试用例异常")
结果:
更多交流和持续更新 请扫码 + VX
本文由mdnice多平台发布
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。