1. 程式人生 > >Pytest學習(八) - 自定義標記mark的使用

Pytest學習(八) - 自定義標記mark的使用

## 一、前言: pytest 支援自定義標記,自定義標記方便用例模組劃分,也可以理解方便管理,配合標記引數 -m使用 ## 二、示例程式碼 ```python # -*- coding: utf-8 -*- # @Time : 2020/11/15 9:51 # @Author : longrong.lang # @FileName: test_mark.py # @Software: PyCharm # @Cnblogs :https://www.cnblogs.com/longronglang import pytest @pytest.mark.mylogin def test_login(): print('登入成功!') @pytest.mark.query def test_query(): print('檢索商品成功!') @pytest.mark.addcart def test_addcart(): print('加入購物車') if __name__ == '__main__': # pytest -s -m query test_mark.py pytest.main(['-s', '-m query', 'test_mark.py']) ``` ## 三、命令列執行 ```python pytest -s -m query test_mark.py ``` 可能看到這的同學會問了,為什麼不用main方法執行,我程式碼裡雖然寫了,但是main執行就變成了了全部執行,這點我也很迷糊,為什麼不行呢。有解決的同學,請在文末留言,我也學習下。 執行結果如下: ![](https://img2020.cnblogs.com/blog/718867/202011/718867-20201115115005499-284138496.png) ## 四、解決執行的warnings提示 建立一個pytest.ini檔案,檔案需要和執行的測試用例同一個目錄,或在根目錄下作用於全域性。 加上自定義mark,內容如下: ```python [pytest] markers = mylogin: this is mylogin page query: this is query page addcart: this is addcart page ``` ## 五、如果不想標記query的用例 執行命令如下: ```python pytest -s -m "not query" test_mark.py ``` 執行結果如下: ![](https://img2020.cnblogs.com/blog/718867/202011/718867-20201115133412117-982351943.png) ## 六、執行多個自定義標記的用例 執行命令如下: ```python pytest -s -m "query or mylogin" test_mark.py ``` 執行結果如下: ![](https://img2020.cnblogs.com/blog/718867/202011/718867-20201115133625024-305176193.png) 系列參考文章: https://www.cnblogs.com/poloyy/category/1690