1. 程式人生 > 實用技巧 >pytest(二十三)--conftest.py作用範圍

pytest(二十三)--conftest.py作用範圍

前言

一個測試工程下是可以有多個conftest.py的檔案,一般在工程根目錄放一個conftest.py起到全域性作用。

在不同的測試子目錄也可以放conftest.py,作用範圍只在該層級及以下目錄生效。

conftest層級關係

在web_item_py專案工程下建兩個子專案(包)QQ、UC,並且每個目錄下都放一個conftest.py和__init__.py(python的每個package必須要有__init__.py)

案例分析

web_item_py工程下conftest.py檔案程式碼如下:

#web_item_py/conftest.py
# coding:utf-8
import pytest
@pytest.fixture(scope="session")
def begin():
    print("\n開啟首頁")

QQ目錄下conftest.py檔案程式碼如下:

#web_item_py/qq/conftest.py
# coding:utf-8
import pytest

@pytest.fixture(scope="session")
def open_baidu():
    print("開啟百度頁面_session")  

QQ目錄下test_1_qq.py程式碼如下;

#web_item_py/qq/test_1_qq.py
# coding:utf-8
import pytest
def test_q1(begin,open_baidu):
    print("測試用例test_q1")
    assert 1
def test_q2(begin,open_baidu):
    print("測試用例test_q2")
    assert 1
if __name__=="__main__":
    pytest.main(["-s","test_1_QQ.py"])  

執行QQ目錄下test_1_qq.py,結果可以看出,begin和open_baidu是session級別的,只執行一次。

UC目錄下conftest.py和test_1_UC.py程式碼如下

#web_item_py/UC/conftest.py
# coding:utf-8
import pytest
@pytest.fixture(scope="function")
def go():
    print("開啟搜狗頁面")
#web_item_py/UC/test_1_UC.py
# coding:utf-8
import pytest
def test_u1(begin,go):
    print("測試用例u1")
    assert 1
def test_u2(begin,go):
    print("測試用例u2")
    assert 2
def test_u3(begin,open_baidu):
    print("測試用例u3")
    assert 2
if __name__=="__main__":
    pytest.main(["-s","test_1_UC.py"]) 

執行結果:begin起到全域性作用,UC目錄下的go是function級別,每個用例呼叫一次。

test_u3(begin,open_baidu)用例不能誇模組呼叫QQ模組下的open_baidu,所以test_u3用例會執行失敗。

同時指向web_item_py工程下的所有用例