上一篇介紹了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的內容知識。如果感覺安靜寫的對您有幫助,點個關注~