Python自动化测试装饰器面试题
时间: 2025-04-20 11:03:57 AIGC 浏览: 39
### Python 自动化测试中装饰器相关的面试题目
#### 装饰器的基础概念及其应用
在Python自动化测试领域,理解装饰器的工作原理至关重要。装饰器本质上是一个接受函数作为参数并返回新函数的对象[^1]。
```python
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
```
#### 使用装饰器增强单元测试的功能
对于`unittest`框架而言,虽然其本身并不提供数据驱动的支持,但是可以通过第三方库如ddt来扩展这一能力。此外,在编写复杂的测试逻辑时,利用自定义的装饰器能够简化代码结构,提高可维护性和重用率[^2]。
```python
import unittest
import ddt
@ddt.ddt
class TestMathOperations(unittest.TestCase):
@ddt.data(
(2, 2),
(-1, -1),
(0, 0)
)
@ddt.unpack
def test_addition(self, a, b):
self.assertEqual(a + b, sum([a,b]))
```
#### 数据准备与清理工作中的装饰器运用
当涉及到接口测试特别是那些依赖于特定状态的应用场景下,可以在测试前后执行必要的准备工作(setup)和收尾工作(teardown),这通常会采用带有上下文管理功能的装饰器来完成。例如,在每次API调用之前设置初始条件并在之后恢复环境至原始状态[^3]。
```python
from contextlib import contextmanager
@contextmanager
def db_transaction(connection):
try:
yield connection.begin()
finally:
connection.rollback()
# 应用于具体的测试方法上
@test_with_db(db_session)
def test_api_endpoint(session):
pass
```
#### 参数化测试案例的设计模式
为了更灵活地应对不同输入组合下的行为验证需求,可以设计专门针对参数传递机制优化过的装饰器。这类装饰器允许开发者更加方便快捷地指定多组入参,并自动迭代运行对应的测试实例[^4]。
```python
@pytest.mark.parametrize('input_data', [
{'username': 'test_user_1'},
{'username': 'test_user_2'}
])
def test_login(input_data):
response = login(**input_data)
assert response.status_code == 200
```
阅读全文
相关推荐




















