pytest测试框架中的setup和tearDown - 0

本文简要介绍了pytest测试框架中的setup和tearDown概念,重点在于它们在经典xunit风格中的应用。作者分享了自己对pytest的兴趣,并提到pytest官方虽然支持此经典方式,但更推荐使用fixture特性。文章预告下篇将探讨如何使用pytest.fixture来替代setup/tearDown。

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

最近对pytest比较感兴趣,看了pytest的文档classic xunit-style setup,这里做个小结,直接看代码。

# content of test_websites.py

'''
Setup/teardown in pytest, see https://docs.pytest.org/en/3.5.1/xunit_setup.html

Remarks:
1. setup/teardown的结对函数在测试进程中可以被调用多次的。
2. 如果setup函数在执行时失败或被skipped了,相应的tearDown函数不会被调用。
'''

import pytest

def setup_module(module):
    """
    这是一个module级别的setup,它会在本module(test_website.py)里
    所有test执行之前,被调用一次。
    注意,它是直接定义为一个module里的函数"""
    print()
    print("-------------- setup before module --------------")


def teardown_module(module):
    """
    这是一个module级别的teardown,它会在本module(test_website.py)里
    所有test执行完成之后,被调用一次。
    注意,它是直接定义为一个module里的函数"""
    print("-------------- teardown after module --------------")


class TestBaidu(object):

    def test_login(self):
        print("test baidu login function")
        assert True == True


class TestSohu(object):

    @classmethod
    def setup_class(cls):
        """ 这是一个class级别的setup函数,它会在这个测试类TestSohu里
        所有test执行之前,被调用一次.
        注意它是一个@classmethod
        """
        print("------ setup before class TestSohu ------")

    @classmethod
    def teardown_class(cls):
         """ 这是一个class级别的teardown函数,它会在这个测试
         类TestSohu里所有test执行完之后,被调用一次.
        注意它是一个@classmethod
        """
        print("------ teardown after class TestSohu ------")

    def setup_method(self, method):
        """ 这是一个method级别的setup函数,它会在这个测试
         类TestSohu里,每一个test执行之前,被调用一次.
        """
        print("--- setup before each method ---")

    def teardown_method(self, method):
        """ 这是一个method级别的teardown函数,它会在这个测试
         类TestSohu里,每一个test执行之后,被调用一次.
        """
        print("--- teardown after each method ---")

    def test_login(self):
        print("sohu login")
        assert True == True

    def test_logout(self):
        print("sohu logout")
        pytest.skip()

pytest中的setup/teardown还有一支更推荐的实现方法是用pytest.fixture特性,上面这种经典的setup/teardown,pytest表示也会继续支持。下一篇blog准备总结下用pytest.fixture实现setup/teardown的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值