# pytest ###### tags: `python` pytest是一個測試框架 有別於原生unittest,是非常pythonic的寫法,原來的unittest是仿造Java的JUnit去設計的 整體相比起來也是比較靠近python的寫法一點 安裝 ```bash= pip install pytest pip install pytest-mock # 如果需要asyncio設計 pip install pytest-asyncio ``` ## 實際操作 開始之前可以先在test資料夾創造一個檔案 ``` touch tests/conftest.py ``` 這個檔案主要是來設定全域參數 ### @pytest.fixture 這個裝飾器的用法主要跟unittest的setUp, tearDown function一樣,保持測試環境不會互相影響,不會fixture不要說你會pytest 用法: ```python= import pytest @pytest.fixture def my_fruit(): return "apple" @pytest.fixture def fruit_basket(my_fruit): return ["banana", my_fruit] def test_my_fruit_in_basket(my_fruit, fruit_basket): assert my_fruit in fruit_basket ``` 由上可知,將function作為參數傳入後,可以直接當作接到return的值以繼續往下實作test的部分 另外也可以自己調整影響範圍 ```python= @pytest.fixture(scope="function") # function: 每個func作用完即銷毀 # class: 每個class作用完即銷毀 # module:每個module結束時銷毀 # package:每個pachage結束後銷毀 # session:測試結束時銷毀 ``` 關於fixture可以看[這篇](https://codingnote.cc/zh-tw/p/207951/),講得蠻全面的。 ## 測試 pytest的斷言直接使用python原生斷言即可 ```python= assert True ```