Python 测试入门
Alexander Levin
Data Scientist
回顾"野餐"类比:
在测试结束时清理环境很重要。若不使用 teardown,可能导致:
何时使用:
autouse何时可不必:
yield 是 Python 关键字,用于创建生成器# Example of generator function
def lazy_increment(n):
for i in range(n):
yield i
f = lazy_increment(5)
next(f) # 0
next(f) # 1
next(f) # 2
使用方法:
yield 替换 returnyield 之后yield 之前@pytest.fixture
def init_list():
return []
@pytest.fixture(autouse=True)
def add_numbers_to_list(init_list):
# Fixture Setup
init_list.extend([i for i in range(10)])
# Fixture output
yield init_list
# Teardown statement
init_list.clear()
def test_9(init_list):
assert 9 in init_list
yield 替代 returnyield 之后编写拆卸代码Python 测试入门