上一篇介紹了fixture的簡單用法,也介紹了如何使用fixture的內容,舉了個例子,不同的用例使用到登錄的場景,如果不同檔案夾的用例使用到相同的fixture應該怎么辦呢?如果再寫一個fixture就會比較麻煩,那么強大的pytest肯定不會讓我們這樣麻煩的,只會讓我們更加方便,這里就要引入新的知識點conftest.py檔案
conftest.py
conftest.py檔案屬于fixture中的共享組態檔,有以下幾個特點:
- conftest.py檔案必須命名這個,不能隨便改名
- conftest.py檔案雖然屬于pytest檔案,但是不用匯入即可使用
- conftest.py檔案可以存放多個fixture方法
- conftest.py和執行的用例要在同一個pakage下,并且有__init__.py檔案
- 不同目錄可以有單獨的 conftest.py,一個專案中可以有多個 conftest.py
比如:有一個測驗場景,存在兩個用例目錄,這兩個目錄下的用例,有的使用到了登錄方法和清除資料的方法,有的沒有用到,這里就可以通過把兩個方法都放到conftest.py檔案中
# conftest.py import pytest @pytest.fixture() def login(): print('輸入用戶名,密碼,完成登陸') @pytest.fixture() def clear(): print('清除用例資料內容!!')
創建好兩個fixture內容后,然后直接在我們的用例中呼叫就行了
先看下目錄內容,這樣更加清楚conftest.py執行內容
auto_test # 專案名稱 --- test_01 # 用例檔案夾 --- test__01.py # 用例檔案 --- __init__.py ---test_02 # 用例檔案夾 --- test__02.py # 用例檔案 --- __init__.py conftest.py # conftest.py檔案

然后分別在兩個用例檔案下撰寫測驗用例
# test__01.py import pytest class Test_01: def test_01(self,login): print('需要用到登錄功能') print('----用例01---') def test_02(self,clear): print('不需要登錄功能') print('----用例02---') def test_03(self, login): print('需要用到登錄功能') print('----用例03---') if __name__ == '__main__': pytest.main(['-s','test__01.py'])
# test__02.py import pytest class Test_02: def test_01(self, login): print('需要用到登錄功能') print('----用例01---') def test_02(self, clear): print('不需要登錄功能') print('----用例02---') def test_03(self, login): print('需要用到登錄功能') print('----用例03---') if __name__ == '__main__': pytest.main(['-s','test__02.py'])
然后進入到auto目錄下,直接執行代碼pytest -s 查看執行結果,

發現配置conftest.py中fixture已經全部都生效了,我們也可以通過--setup--show來查看詳細的執行程序

無論是單獨執行用例還是全部執行用例,都可以進行執行fixture內容
今天簡單的介紹了conftest.py檔案的作用,其實主要還是fixture的內容知識,如果感覺安靜寫的對您有幫助,點個關注~
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/248424.html
標籤:其他
下一篇:如何創建Mock介面并測驗
