Python 測試入門
Alexander Levin
Data Scientist
回想「野餐」的比喻:
在測試結束時,清理環境 很重要。若不使用 teardown,可能造成嚴重問題:
何時使用:
autouse何時可不必使用:
yield 是 Python 關鍵字,可用來建立產生器(generator)。# 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
如何使用:
return 換成 yieldyield 之後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 測試入門