如果你還想從頭學起Pytest,可以看看這個系列的文章哦!
https://www.cnblogs.com/poloyy/category/1690628.html
什么是conftest.py
可以理解成一個專門存放fixture的配置文件
實際開發場景
多個測試用例文件(test_*.py)的所有用例都需要用登錄功能來作為前置操作,那就不能把登錄功能寫到某個用例文件中去了
如何解決上述場景問題?
conftest.py的出現,就是為了解決上述問題,單獨管理一些全局的fixture
conftest.py配置fixture注意事項
- pytest會默認讀取conftest.py里面的所有fixture
- conftest.py 文件名稱是固定的,不能改動
- conftest.py只對同一個package下的所有測試用例生效
- 不同目錄可以有自己的conftest.py,一個項目中可以有多個conftest.py
- 測試用例文件中不需要手動import conftest.py,pytest會自動查找
實際項目中的小案例
這是一個目錄
06conftest目錄下
conftest.py代碼
最頂層的conftest,一般寫全局的fixture,在Web UI自動化中,可能會初始化driver

#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = __Time__ = 2020-04-08 21:22 __Author__ = 小菠蘿測試筆記 __Blog__ = https://www.cnblogs.com/poloyy/ """ import pytest @pytest.fixture(scope="session") def login(): print("====登錄功能,返回賬號,token===") name = "testyy" token = "npoi213bn4" yield name, token print("====退出登錄!!!====") @pytest.fixture(autouse=True) def get_info(login): name, token = login print(f"== 每個用例都調用的外層fixture:打印用戶token: {token} ==")
test_1.py代碼
同級目錄下的第一條測試用例

def test_get_info(login): name, token = login print("***基礎用例:獲取用戶個人信息***") print(f"用戶名:{name}, token:{token}")
06_run.py代碼
運行06conftest目錄下所有測試用例

import pytest if __name__ == '__main__': pytest.main(["-s", "../06conftest/"])
test_51job目錄下
conftest.py代碼
配置一些針對51job這個網站的測試用例獨有的fixture,譬如:打開51job網站

import pytest @pytest.fixture(scope="module") def open_51(login): name, token = login print(f"###用戶 {name} 打開51job網站###")
test_case1.py代碼
某個功能模塊下的測試用例

def test_case2_01(open_51): print("51job,列出所有職位用例") def test_case2_02(open_51): print("51job,找出所有python崗位")
test_toutiao目錄下
test_case1.py代碼
包沒有__init__.py文件也沒有conftest.py文件

def test_no_fixture(login): print("==沒有__init__測試用例,我進入頭條了==", login)
test_weibo目錄下
conftest.py代碼
配置一些針對weibo這個網站的測試用例獨有的fixture,譬如:打開weibo網站

import pytest @pytest.fixture(scope="function") def open_weibo(login): name, token = login print(f"&&& 用戶 {name} 返回微博首頁 &&&")
test_case1.py代碼
某個功能模塊下的測試用例

class TestWeibo: def test_case1_01(self, open_weibo): print("查看微博熱搜") def test_case1_02(self, open_weibo): print("查看微博范冰冰")
運行06_run.py的結果