测试时常使用的方法

pytest框架

  • 使用pytest框架
import pytest

class TestAddition:
    
    @pytest.fixture
    def setup_values(self):
        # Setup - 初始化
        a, b = 1, 2
        yield a, b  # 提供值给测试函数
        # Teardown - 清理
        a, b = 0, 0
        print(f"清理完成: a={a}, b={b}")
    
    def test_add(self, setup_values):
        a, b = setup_values
        assert a + b == 3

上下文管理器

  • 使用上下文管理器
# 使用上下文管理器
from contextlib import contextmanager

class TestAddition:
    
    @contextmanager
    def values_fixture(self, a_val=1, b_val=2):
        # Setup
        a, b = a_val, b_val
        try:
            yield a, b
        finally:
            # Teardown - 总是执行
            a, b = 0, 0
            print(f"值已重置: a={a}, b={b}")
    
    def test_add(self):
        with values_fixture() as (a, b):
            assert a + b == 3

unittest风格的setup和teardown

  • unittest风格
# 使用unittest风格的SetUp和tearDown
import unittest

class TestAddition(unittest.TestCase):
    
    def setUp(self):
        # 每次测试前运行
        a = 1
        b = 2
    
    def tearDown(self):
        # 每次测试后运行
        a = 0
        b = 0
        print(f"值已重置: a={a}, b={b}")
    
    def test_add(self):
        assert a + b == 3

# 如果要手动运行
if __name__ == '__main__':
    unittest.main()

完全手动测试

  • 手动测试方案
# 完全手动
class TestAddition:
    
    def run_test_with_fixture(self, test_func):
        # Setup
        a, b = 1, 2
        try:
            # 运行测试,传入准备好的值
            test_func(a, b)
            print("测试通过")
        except AssertionError as e:
            print(f"测试失败: {e}")
        finally:
            # Teardown - 无论测试通过还是失败都会执行
            a, b = 0, 0
            print(f"值已重置: a={a}, b={b}")
    
    def test_add(self, a, b):
        assert a + b == 3
    
    def run(self):
        # 手动执行测试
        run_test_with_fixture(test_add)

# 运行测试
if __name__ == "__main__":
    tester = TestAddition()
    tester.run()

使用装饰器

  • 装饰器实现方案

# 使用装饰器实现
import functools


test_values = {"a": 0, "b": 0}

def setup_teardown(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # Setup
        test_values["a"] = 1
        test_values["b"] = 2
        
        # 调用测试函数,传入设置的值
        if args:
            result = func(args[0], test_values["a"], test_values["b"])
        else:
            result = func(test_values["a"], test_values["b"])
       
        
        # Teardown
        test_values["a"] = 0
        test_values["b"] = 0
        print(f"Teardown completed: a={test_values['a']}, b={test_values['b']}")
        
        return result
    return wrapper
posted @ 2025-07-07 15:53  你要去码头整点薯条吗  阅读(17)  评论(0)    收藏  举报