目錄
1.?基本使用
1--安裝
2--pytest書寫規則
3--為pycharm設置? 以 pytest的方式運行
4--setup和teardown
5--setup_class和teardown
2.?pytest生成測試報告
-
基本使用
-
安裝
- pytest文檔地址
- pytest documentation
- pytest documentation
- ?pip install pytest
- 點擊pycharm左邊的控制臺按鈕
- 輸入pip install pytest
- 出現下面的情況就算成功了
- pytest文檔地址
-
pytest書寫規則
- 測試的文件名必須以test開頭,或者結尾
- test_12312_demo.py
- asd_112_demo_test.pyy
- 測試類必須以Test開頭
- TestLoginApi
- 測試的文件名必須以test開頭,或者結尾
-
為pycharm設置? 以 pytest的方式運行
- 使用快捷鍵 ctrl + alt +s 呼出pycharm設置面板
- 找tools
- python integrated tools
- 找到Default test Runner?
- 設置pytest
- 最后點擊ok按鈕
- 設置pytest
- 找到Default test Runner?
- python integrated tools
- 找tools
- 使用快捷鍵 ctrl + alt +s 呼出pycharm設置面板
- 編寫一個簡單的例子
-
class TestDemo:# 定義一個測試用例def test_demo_001(self):print("這是一個測試test_demo_001")def test_demo_002(self):print("test_demo_002")
- 測試結果如下
- 命令行執行
- pytest -s .\test_demo.py
- pytest -s .\test_demo.py
-
-
setup和teardown
-
def setup(self):print("前置處理")
-
def teardown(self):print("后置處理")
- 在執行的過程中
- 發現這些函數并沒有執行
- 這個的原因是因為setup 和 teardown在pytest 8.0 以后的版本已經廢棄了
- 可以使用setup_method和 teardown_method
-
def setup_method(self):print("前置處理\n")def teardown_method(self):print("后置處理")
-
- 運行結果
- 可以看到在每個方法執行前后都會執行
- pytest8.0以前的版本使用setup和teardown。pytest8.0以后的版本使用setup_method和teardown_method
-
-
setup_class和teardown
-
def setup_class(self):print("--------類級別的前置處理器---------")def teardown_class(self):print("--------類級別的后置處理器---------")
- ?
- 可以看到只會運行一次
-
-
-
pytest生成測試報告
- 安裝測試報告插件
- pip install pytest-html
- 出現下面的情況就算安裝完成了
- 使用指令生成測試報告
- pytest --html=.\reports.html .\test_demo.py
- pytest --html=生成報告的路徑 執行測試用例的路徑
- 打開測試報告
- 找到reports.html文件?
- 鼠標右鍵
- Open in
- Brower
- Chrome
- 這里可以選擇你安裝的瀏覽器去打開
- 我這里安裝了Chrome,就選擇了Chrome
- Brower
- Open in
- 鼠標右鍵
- 找到reports.html文件?
- 可以看到生成的測試報告
- 可以看到這些結果展示還是很直觀 的
- 安裝測試報告插件