Pytest测试用例之setup与teardown方法(二)

本文详细介绍了Pytest框架中不同级别的setup与teardown方法的使用及执行顺序,包括类级、方法级和类内级,帮助理解如何有效组织测试用例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

日常积累 | 初识Pytest  | 日常积累 | 初识pytest (二) | Pytest测试用例之setup与teardown方法(一)继续分享, 今天继模块级以及函数式setup与teardown之外的2种类与方法级的写法与执行顺序

回顾

pytest框架用例运行级别

>>模块级(setup_module/teardown_module)开始于横块始末,全局的 

>>函数级(setup_function/teardown_function)只对函数用例生效(不在类中)

>>类级(setup_class/teardown_calss)只在类中前后运行一次(在类中)

>>方法级(setup_method/teardown_method)开始于方法始末(在类中)

>>类里面的(setup/teardown)运行在调用方法前后

接下来我们进入今天的小猪脚类与方法的setup、teardown

01类里面的

pytest 框架类里面的前置与后置用法setup、teardown ]

以下代码是类里面的前置后置简要代码,我们一起看看他的执行顺序

# coding=utf-8# authou:shichao# python测试社区学习记录
import pytest

class Testcaselist():
    # 类里面的    def setup(self):        print('setup:每个用例前开始执行')
    def teardown(self):        print('teardown:每个用例后开始执行')
    # 测试用例    def test_001(self):        print("正在执行第一条用例")        p = "Python"        assert "h" in p
    def test_002(self):        print("正在执行第二条用例")        p = 'test'        assert 't' in p
    if __name__ == '__main__':        pytest.main(['-s', 'test_fixtclass.py'])



以下是代码执行后控制台输出

Testing started at 17:29 ...F:\python3\python_code\venv\Scripts\python.exe "F:\PyCharm\PyCharm Community Edition 2019.2.2\helpers\pycharm\_jb_pytest_runner.py" --path F:/python3/python_code/Study/API_AutoTest_Pytest/test_fixtclass.pyLaunching pytest with arguments F:/python3/python_code/Study/API_AutoTest_Pytest/test_fixtclass.py in F:\python3\python_code\Study\API_AutoTest_Pytest
============================= test session starts =============================platform win32 -- Python 3.7.4, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- F:\python3\python_code\venv\Scripts\python.execachedir: .pytest_cacherootdir: F:\python3\python_code\Study\API_AutoTest_Pytestcollecting ... collected 2 items
test_fixtclass.py::Testcaselist::test_001 setup:每个用例前开始执行PASSED                         [ 50%]正在执行第一条用例teardown:每个用例后开始执行
test_fixtclass.py::Testcaselist::test_002 setup:每个用例前开始执行PASSED                        [100%]正在执行第二条用例teardown:每个用例后开始执行

============================== 2 passed in 0.02s ==============================
Process finished with exit code 0

>>类里面的setup、teardown控制台输出解析

# 类里面的 [ 可以看到控制台输出的结果执行顺序 ]

test_fixtclass.py : test_001 >>setup:每个用例前开始执行>>PASSED>> [ 50%]正在执行第一条用例>>teardown:每个用例后开始执行

test_fixtclass.py : test_002 >>setup:每个用例前开始执行>>PASSED>> [100%]正在执行第二条用例>>teardown:每个用例后开始执行

这是我们的类里面的setup、teardown作用对类里的测试用例生效

* 类里面的在每条测试用例执行前都会去执行一次

图例01

02类级

接着我们在看看[ 类级setup_class、teardown_class前置与后置用法 ]

以下代码是类级的前置后置简要代码,我们一起看看他的执行顺序

# coding=utf-8
# authou:shichao
# python测试社区学习记录
import pytest




class Testcaselist():
    print('setup_class:所有用例执行之前')


# 类级
def setup_class(self):
    print('setup_class:所有用例执行之前')


def teardown_class(self):
    print('teardown_class:所有用例执行结束之后')


# 测试用例
def test_001(self):
    print("正在执行第一条用例")
    p = "Python"
    assert "h" in p


def test_002(self):
    print("正在执行第二条用例")
    p = 'test'
    assert 't' in p
    
if __name__ == '__main__':
    pytest.main(['-s', 'test_fixtclass.py'])


以下是代码执行后控制台输出

Testing started at 20:12 ...
F:\python3\python_code\venv\Scripts\python.exe "F:\PyCharm\PyCharm Community Edition 2019.2.2\helpers\pycharm\_jb_pytest_runner.py" --path F:/python3/python_code/Study/API_AutoTest_Pytest/test_fixtclass.py
Launching pytest with arguments F:/python3/python_code/Study/API_AutoTest_Pytest/test_fixtclass.py in F:\python3\python_code\Study\API_AutoTest_Pytest


============================= test session starts =============================
platform win32 -- Python 3.7.4, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- F:\python3\python_code\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: F:\python3\python_code\Study\API_AutoTest_Pytest
collecting ... collected 2 items


test_fixtclass.py::Testcaselist::test_001 setup_class:所有用例执行之前
PASSED                         [ 50%]正在执行第一条用例


test_fixtclass.py::Testcaselist::test_002 PASSED                         [100%]正在执行第二条用例
teardown_class:所有用例执行结束之后




============================== 2 passed in 0.02s ==============================


Process finished with exit code 0


>>类级setup_class、teardown_class控制台输出解析

# 类级 [ 我们可以看到控制台输出的结果执行顺序 ]

>>test_fixtclass.py:Testcaselist: >>setup_class:所有用例执行之前>>test_001 >>[ 50%]正在执行第一条用例>>PASSED  >>test_002>>[100%]正在执行第二条用例>>PASSED >>teardown_class:所有用例执行结束之后

* 类级前置后置只打开一次就执行所有的测试用例

图例02

03方法级

接着我们在看看[ 方法级setup_method、teardown_method在一个测试用例文件里一起写前置与后置用法 看看它的执行顺序 ]

以下代码是模块级的前置后置简要代码,我们一起看看他的执行顺序

# coding=utf-8# authou:shichao# python测试社区学习记录
import pytest

class Testcaselist():
    # 方法级    def setup_method(self):        print('setup_method:每个用例开始之前执行')
    def teardown_method(self):        print('teardown_method:每个用例结束后执行')
    # 测试用例    def test_001(self):        print("正在执行第一条用例")        p = "Python"        assert "h" in p
    def test_002(self):        print("正在执行第二条用例")        p = 'test'        assert 't' in p
    if __name__ == '__main__':        pytest.main(['-s', 'test_fixtclass.py'])

以下是代码执行后控制台输出

Testing started at 17:48 ...F:\python3\python_code\venv\Scripts\python.exe "F:\PyCharm\PyCharm Community Edition 2019.2.2\helpers\pycharm\_jb_pytest_runner.py" --path F:/python3/python_code/Study/API_AutoTest_Pytest/test_fixtclass.pyLaunching pytest with arguments F:/python3/python_code/Study/API_AutoTest_Pytest/test_fixtclass.py in F:\python3\python_code\Study\API_AutoTest_Pytest
============================= test session starts =============================platform win32 -- Python 3.7.4, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- F:\python3\python_code\venv\Scripts\python.execachedir: .pytest_cacherootdir: F:\python3\python_code\Study\API_AutoTest_Pytestcollecting ... collected 2 items
test_fixtclass.py::Testcaselist::test_001 setup_method:每个用例开始之前执行PASSED                         [ 50%]正在执行第一条用例teardown_method:每个用例结束后执行
test_fixtclass.py::Testcaselist::test_002 setup_method:每个用例开始之前执行PASSED                         [100%]正在执行第二条用例teardown_method:每个用例结束后执行

============================== 2 passed in 0.02s ==============================
Process finished with exit code 0

>>方法级的setup_method、teardown_method控制台输出解析

# 类里面的 [ 可以看到控制台输出的结果执行顺序 ]

test_fixtclass.py : test_001 >>setup_method:每个用例开始之前执行>>PASSED>> [ 50%]正在执行第一条用例>>teardown_method:每个用例结束后执行

test_fixtclass.py : test_002 >>setup_method:每个用例开始之前执行>>PASSED>> [100%]正在执行第二条用例>>teardown_method:每个用例结束后执行

* 方法级的在每条测试用例执行前都会去执行一次

图例03

04类级+方法级+类里面的

接着我们在看看[ 类级+方法级setup、teardown、setup_class、teardown_class、setup_method、teardown_method在一个测试用例文件里一起写前置与后置用法 看看它的执行顺序 ]

以下代码是类级+模块级的前置后置简要代码,我们一起看看他的执行顺序

# coding=utf-8# authou:shichao# python测试社区学习记录
import pytest

class Testcaselist():
    # 类里面的    def setup(self):        print('setup:每个用例前开始执行')
    def teardown(self):        print('teardown:每个用例后开始执行')
    # 类级    def setup_class(self):        print('setup_class:所有用例执行之前')
    def teardown_class(self):        print('teardown_class:所有用例执行结束之后')
    # 方法级    def setup_method(self):        print('setup_method:每个用例开始之前执行')
    def teardown_method(self):        print('teardown_method:每个用例结束后执行')
    # 测试用例    def test_001(self):        print("正在执行第一条用例")        p = "Python"        assert "h" in p
    def test_002(self):        print("正在执行第二条用例")        p = 'test'        assert 't' in p
    if __name__ == '__main__':        pytest.main(['-s', 'test_fixtclass.py'])

以下是代码执行后控制台输出

Testing started at 17:57 ...F:\python3\python_code\venv\Scripts\python.exe "F:\PyCharm\PyCharm Community Edition 2019.2.2\helpers\pycharm\_jb_pytest_runner.py" --path F:/python3/python_code/Study/API_AutoTest_Pytest/test_fixtclass.pyLaunching pytest with arguments F:/python3/python_code/Study/API_AutoTest_Pytest/test_fixtclass.py in F:\python3\python_code\Study\API_AutoTest_Pytest
============================= test session starts =============================platform win32 -- Python 3.7.4, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- F:\python3\python_code\venv\Scripts\python.execachedir: .pytest_cacherootdir: F:\python3\python_code\Study\API_AutoTest_Pytestcollecting ... collected 2 items
test_fixtclass.py::Testcaselist::test_001 setup_class:所有用例执行之前setup_method:每个用例开始之前执行setup:每个用例前开始执行PASSED                         [ 50%]正在执行第一条用例teardown:每个用例后开始执行teardown_method:每个用例结束后执行
test_fixtclass.py::Testcaselist::test_002 setup_method:每个用例开始之前执行setup:每个用例前开始执行PASSED                         [100%]正在执行第二条用例teardown:每个用例后开始执行teardown_method:每个用例结束后执行teardown_class:所有用例执行结束之后

============================== 2 passed in 0.02s ==============================
Process finished with exit code 0

>>类里面的+类级+方法级前置后置控制台输出解析

# 类里面的+类级+方法级 [ 我们可以看到控制台输出的结果执行顺序 ]

>>test_fixtclass.py::Testcaselist:setup_class:所有用例执行之前>>比如:所有用例开始前只打开一次浏览器

setup:每个用例前开始执行>>setup_method:每个用例开始之前执行>>test_001>>[ 50%]正在执行第一条用例>>PASSED >>teardown:每个用例后开始执行>>teardown_method:每个用例结束后执行

setup:每个用例前开始执行>>setup_method:每个用例开始之前执行>>test_002>>[ 50%]正在执行第一条用例>>PASSED >>teardown:每个用例后开始执行>>teardown_method:每个用例结束后执行

>>teardown_class:所有用例执行结束之后>>比如:所有用例结束只最后关闭浏览器

从结果看出,运行的优先级:setup_class>>setup_method>

setup >用例>teardown>teardown_method>>teardown_class

图例04

以上就是今天给大家介绍的pytest前置后置[ 类级以及方法级] 的用法以及在实际代码中他们的执行优先级,小小的顺序结构可能会影响你这条case是否执行通过,希望本次分享对大家有所帮助

注:本文内容来源于网络相关知识点综合总结,只作为知识分享,如有侵权可联系删除

日常积累,支持作者,可以将文章分享到朋友圈或点个在看,感谢大家的阅读!Bey , 下期再见

识别下方二维码,后台回复 "989" "Python" 领取 4G 入门到进阶成长资料

<think>嗯,用户之前问过关于Python自动化测试员需要哪些证书的问题,现在又转向了pytest的基础测试写法和深度操作。看起来他们可能正在学习自动化测试,尤其是使用Python和pytest框架。用户可能已经从了解证书转向了实际技能的学习,现在需要具体的代码示例和高级技巧。 首先,我需要确定用户的基础。他们可能已经掌握了Python的基础,但对pytest还不熟悉。用户需要基础测试写法,这可能包括如何编写测试函数、断言使用、夹具(fixtures)等。然后,深度操作可能涉及参数化测试、标记(markers)、插件使用、钩子函数(hooks)、自定义报告等高级功能。 接下来,我要考虑用户的实际应用场景。作为自动化测试员,他们可能需要在项目中快速编写可维护的测试用例,处理复杂的测试环境,或者集成到CI/CD流程中。因此,除了基础语法,还需要覆盖如何组织测试代码、处理依赖、使用插件增强功能。 用户可能没有明确说出来的需求包括如何管理测试数据,如何处理测试前后的设置和清理,以及如何生成测试报告。这些都是实际项目中常见的问题,需要涵盖在回答中。 另外,用户之前的问题涉及证书,现在转向技术细节,可能是在准备面试或实际项目,需要快速掌握pytest的核心功能。因此,回答需要结构清晰,示例丰富,便于理解和应用。 我需要确保回答包含基础部分,如测试函数结构、断言、夹具,以及高级部分如参数化、标记、插件、自定义钩子、分布式测试等。同时,提供实际代码示例,让用户可以直接复制和修改使用。还要强调最佳实践,比如测试命名、组织方式、避免重复代码,帮助用户写出更好的测试。 最后,总结部分应该强调pytest的优势,如简洁、灵活、插件生态,以及如何结合项目需求选择合适的特性。这可以帮助用户理解如何在实际工作中有效应用pytest,提升测试效率和质量。</think>好的!以下是 **pytest 的基础测试写法及深度操作**的详细介绍,包含代码示例和关键技巧: --- ### **一、基础测试写法** #### **1. 基本测试函数** - **规则**:测试文件以 `test_` 开头,函数以 `test_` 开头。 - **示例**: ```python # test_math.py def test_addition(): assert 1 + 1 == 2 def test_subtraction(): assert 5 - 3 == 2 ``` - **运行测试**: ```bash pytest test_math.py # 运行指定文件 pytest -v # 显示详细信息 ``` --- #### **2. 断言(Assert)** - **直接使用 `assert`**:无需复杂语法,失败时自动显示详细错误。 ```python def test_string(): s = "hello" assert s.upper() == "HELLO" assert "h" in s ``` --- #### **3. 测试类(Test Class)** - **类名以 `Test` 开头**,方法以 `test_` 开头: ```python class TestMath: def test_multiply(self): assert 2 * 3 == 6 def test_division(self): assert 6 / 2 == 3 ``` --- #### **4. Fixtures(夹具)** - **作用**:管理测试依赖(如数据库连接、初始化数据)。 - **定义使用**: ```python import pytest @pytest.fixture def database_connection(): conn = create_connection() # 假设的初始化方法 yield conn conn.close() # 测试后清理资源 def test_query(database_connection): result = database_connection.execute("SELECT 1") assert result == 1 ``` --- ### **、深度操作高级技巧** #### **1. 参数化测试(Parametrize)** - **同一测试覆盖多组输入**: ```python import pytest @pytest.mark.parametrize("a, b, expected", [ (1, 2, 3), (5, -1, 4), (0, 0, 0) ]) def test_add(a, b, expected): assert a + b == expected ``` --- #### **2. 标记(Markers)** - **分类测试**:如跳过测试、标记为冒烟测试等。 ```python import pytest @pytest.mark.smoke def test_login(): assert True @pytest.mark.skip(reason="功能未实现") def test_logout(): assert False @pytest.mark.xfail # 预期失败 def test_buggy_feature(): assert False ``` - **运行标记测试**: ```bash pytest -m smoke # 只运行标记为smoke的测试 ``` --- #### **3. 临时目录文件(tmp_path)** - **处理临时文件**: ```python def test_create_file(tmp_path): file = tmp_path / "test.txt" file.write_text("Hello") assert file.read_text() == "Hello" ``` --- #### **4. 插件钩子(Hooks)** - **扩展功能**:如生成HTML报告、控制测试流程。 - **常用插件**: - `pytest-html`:生成HTML测试报告。 - `pytest-cov`:覆盖率检查。 - `pytest-xdist`:分布式测试。 - **安装使用**: ```bash pip install pytest-html pytest --html=report.html ``` --- #### **5. 动态生成测试用例** - **灵活构造测试**: ```python def generate_cases(): return [("case1", 1, 2), ("case2", 3, 4)] @pytest.mark.parametrize("name, a, b", generate_cases()) def test_dynamic(name, a, b): assert a < b ``` --- #### **6. 自定义 Fixture 作用域** - **控制 Fixture 生命周期**: ```python @pytest.fixture(scope="module") # 作用域:模块级(每个模块只执行一次) def shared_resource(): return expensive_initialization() ``` --- #### **7. 异常测试** - **验证代码是否抛出预期异常**: ```python import pytest def test_divide_by_zero(): with pytest.raises(ZeroDivisionError): 1 / 0 ``` --- ### **三、最佳实践** 1. **命名规范**:测试文件和函数名清晰表达意图。 2. **测试隔离**:每个测试独立运行,不依赖外部状态。 3. **使用 Fixture 复用代码**:减少重复初始化逻辑。 4. **断言明确**:避免复杂断言,必要时自定义错误消息: ```python assert len(result) == 5, "结果长度应为5" ``` --- ### **四、复杂场景示例** #### **Web自动化测试(结合Selenium)** ```python import pytest from selenium import webdriver @pytest.fixture(scope="module") def browser(): driver = webdriver.Chrome() yield driver driver.quit() def test_login(browser): browser.get("https://example.com/login") browser.find_element("id", "username").send_keys("admin") browser.find_element("id", "password").send_keys("secret") browser.find_element("id", "submit").click() assert "Dashboard" in browser.title ``` --- ### **总结** pytest 的核心优势在于 **简洁性** 和 **灵活性**,通过掌握 Fixtures、参数化、插件等高级功能,可以轻松应对复杂测试场景。建议结合具体项目需求逐步深入,例如: - 使用 `pytest-xdist` 加速大规模测试。 - 通过 `pytest.ini` 文件配置默认参数。 - 自定义插件处理项目特有逻辑。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值