什么是confte.py
可以理解為 是一個專門存放 fixture的配置文件
實際開發場景
多個測試用例文件(tets_*.py)的所有用例都需要用登錄功能來作為前置操作, 那就不能把登錄功能寫到某個用例文件中去了
如何解決上述場景問題?
conftest.py的出現,就是為了解決上述問題,單獨管理一些全局的fixture
conftest.py配置fixture注意事項
- pytest會默認讀取conftest.py里面的所有fixture
- conftest.py 文件名稱是固定的,不能改動
- conftest.py只對同一個package下的所有測試用例生效
- 不同目錄可以有自己的conftest.py,一個項目中可以有多個conftest.py
- 測試用例文件中不需要手動import conftest.py,pytest會自動查找
實際案例:
目錄方式:
test_case001目錄下
conftest.py代碼
最頂層的conftest,一般寫全局的fixture,在Web UI自動化中,可能會初始化driver,在API中登錄初始化
import pytest
@pytest.fixture(scope="session")
def login():
print("====登錄功能,返回token,token===")
name = "testxxx"
token = "1234qwer"
yield name, token
print("====退出登錄!!!====")
@pytest.fixture(autouse=True)
def get_info(login):
name, token = login
print(f"== 每個用例都調用的外層fixture:打印用戶token: {token}")
test_001 案例
import pytest
def test_get_info(login):
name, token = login
print("***基礎用例:獲取用戶個人信息***")
print(f"用戶名:{name}, token:{token}")
if __name__ == '__main__':
pytest.main(["-s", "../test_001/"])
tets_case002的conftest
import pytest
@pytest.fixture(scope="module")
def open_51(login):
name, token = login
print(f"用戶 {name} 打開51job網站")
test_002 案例
def test_case2_01(open_51):
print("51job,列出所有職位用例")
def test_case2_02(open_51):
print("51job,找出所有python崗位")
testcase_003 中無init 無conftest
def test_no_fixture(login):
print("==沒有__init__測試用例,", login)
testcase004中的conftest
import pytest
@pytest.fixture(scope="function")
def open_weibo(login):
name, token = login
print(f"&&& 用戶 {name} 返回微博首頁 &&&")
test_004 案例
class TestWeibo:
def test_case1_01(self, open_weibo):
print("查看微博熱搜")
def test_case1_02(self, open_weibo):
print("查看微博評論")
跑所有案例:在最頂層的目錄下 run.py
import pytest
if __name__ == '__main__':
pytest.main(["-s", "../test_case001/"])