使用 pytest 建立 fixtures
在撰寫單元測試時,你有時需要在開始測試前先做一些設定。如果把這些設定寫在單元測試裡,會讓測試不易閱讀,且可能需要重複好幾次。所幸,pytest 提供了 fixtures,可以解決這些問題。
在本練習中,pandas 已以 pd 匯入,且下方的 extract() 函式可供使用!
def extract(file_path):
return pd.read_csv(file_path)
本練習屬於課程
使用 Python 的 ETL 與 ELT
練習說明
- 匯入
pytest函式庫。 - 建立名為
raw_tax_data的pytestfixture。 - 回傳
raw_dataDataFrame。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import pytest
____
# Create a pytest fixture
@pytest.fixture()
def ____():
raw_data = extract("raw_tax_data.csv")
# Return the raw DataFrame
return ____