fixture的作用范圍(scope)


一、前言

fixture里面有個scope參數可以控制fixture的作用范圍:

session > module > class > function

二、fixture作用范圍

  • function:每一個函數或方法都會調用
  • class:每一個類調用一次,一個類可以有多個方法
  • module:每一個.py文件調用一次,該文件內又有多個function和class
  • session:是多個文件調用一次,可以跨.py文件調用,每個.py文件就是module
fixture(scope="function", params=None, autouse=False, ids=None, name=None):
    """使用裝飾器標記fixture的功能
     ** 作者:上海-悠悠 QQ交流群:588402570**
     可以使用此裝飾器(帶或不帶參數)來定義fixture功能。 fixture功能的名稱可以在以后使用
     引用它會在運行測試之前調用它:test模塊或類可以使用pytest.mark.usefixtures(fixturename標記。 
     測試功能可以直接使用fixture名稱作為輸入參數,在這種情況下,夾具實例從fixture返回功能將被注入。
    :arg scope: scope 有四個級別參數 "function" (默認), "class", "module" or "session".
 
    :arg params: 一個可選的參數列表,它將導致多個參數調用fixture功能和所有測試使用它
 
    :arg autouse:  如果為True,則為所有測試激活fixture func 可以看到它。 如果為False(默認值)則顯式需要參考來激活fixture
 
    :arg ids: 每個字符串id的列表,每個字符串對應於params 這樣他們就是測試ID的一部分。 如果沒有提供ID它們將從params自動生成
 
    :arg name:   fixture的名稱。 這默認為裝飾函數的名稱。 如果fixture在定義它的同一模塊中使用,夾具的功能名稱將被請求夾具的功能arg遮蔽; 解決這個問題的一種方法是將裝飾函數命名
                       “fixture_ <fixturename>”然后使用”@ pytest.fixture(name ='<fixturename>')“”。

scope="function"

@pytest.fixture()如果不寫參數,默認就是scope="function",它的作用范圍是每個測試用例來之前運行一次,銷毀代碼在測試用例運行之后運行。

import pytest
 
@pytest.fixture()
def first():
    print("\n獲取用戶名")
    a = "yoyo"
    return a
 
@pytest.fixture(scope="function")
def sencond():
    print("\n獲取密碼")
    b = "123456"
    return b
 
def test_1(first):
    '''用例傳fixture'''
    print("測試賬號:%s" %first)
    assert first == "yoyo"
 
def test_2(sencond):
    '''用例傳fixture'''
    print("測試密碼:%s" %sencond)
    assert sencond == "123456"
 
if __name__ == "__main__":
    pytest.main(["-s", "test_fixture7.py"])

運行結果:

D:\Users\hgh\AppData\Local\Programs\Python\Python36\python.exe C:/Users/hgh/PycharmProjects/untitled1/testcase/test_hest.py
============================= test session starts =============================
platform win32 -- Python 3.6.5, pytest-4.5.0, py-1.8.0, pluggy-0.12.0
rootdir: C:\Users\hgh\PycharmProjects\untitled1\testcase
plugins: allure-pytest-2.8.2, html-1.22.0, metadata-1.8.0, rerunfailures-7.0, shutil-1.7.0
collected 2 items

test_hest.py 
獲取用戶名
測試賬號:yoyo
.
獲取密碼
測試密碼:123456
.

========================== 2 passed in 0.12 seconds ===========================

進程已結束,退出代碼0

scope="class"

fixture為class級別的時候,如果一個class里面有多個用例,都調用了此fixture,那么此fixture只在該class里所有用例開始前執行一次

import pytest
 
@pytest.fixture(scope="class")
def first():
    print("\n獲取用戶名,scope為class級別只運行一次")
    a = "yoyo"
    return a
 
class TestCase():
    def test_1(self, first):
        '''用例傳fixture'''
        print("測試賬號:%s" % first)
        assert first == "yoyo"
 
    def test_2(self, first):
        '''用例傳fixture'''
        print("測試賬號:%s" % first)
        assert first == "yoyo"

if __name__ == "__main__":
    pytest.main(["-s", "test_hest.py"])

運行結果:

============================= test session starts =============================
platform win32 -- Python 3.6.5, pytest-4.5.0, py-1.8.0, pluggy-0.12.0
rootdir: C:\Users\hgh\PycharmProjects\untitled1\testcase
plugins: allure-pytest-2.8.2, html-1.22.0, metadata-1.8.0, rerunfailures-7.0, shutil-1.7.0
collected 2 items

test_hest.py 
獲取用戶名,scope為class級別只運行一次
測試賬號:yoyo
.測試賬號:yoyo
.

========================== 2 passed in 0.11 seconds ===========================

進程已結束,退出代碼0

scope="module"

fixture為module級別時,在當前.py腳本里面所有用例開始前只執行一次


import pytest
 
@pytest.fixture(scope="module")
def first():
    print("\n獲取用戶名,scope為module級別當前.py模塊只運行一次")
    a = "yoyo"
    return a
 
 
def test_1(first):
    '''用例傳fixture'''
    print("測試賬號:%s" % first)
    assert first == "yoyo"
 
class TestCase():
    def test_2(self, first):
        '''用例傳fixture'''
        print("測試賬號:%s" % first)
        assert first == "yoyo"
 
if __name__ == "__main__":
    pytest.main(["-s", "test_hest.py"])

運行結果:

============================= test session starts =============================
platform win32 -- Python 3.6.5, pytest-4.5.0, py-1.8.0, pluggy-0.12.0
rootdir: C:\Users\hgh\PycharmProjects\untitled1\testcase
plugins: allure-pytest-2.8.2, html-1.22.0, metadata-1.8.0, rerunfailures-7.0, shutil-1.7.0
collected 2 items

test_hest.py 
獲取用戶名,scope為module級別當前.py模塊只運行一次
測試賬號:yoyo
.測試賬號:yoyo
.

========================== 2 passed in 0.09 seconds ===========================

進程已結束,退出代碼0

scope="session"

fixture為session級別是可以跨.py模塊調用的,也就是當我們有多個.py文件的用例時候,如果多個用例只需調用一次fixture,那就可以設置為scope="session",並且寫到conftest.py文件里

conftest.py文件名稱是固定的,pytest會自動識別該文件。放到工程的根目錄下,就可以全局調用了,如果放到某個package包下,那就只在該package內有效

conftest.py
 
import pytest
 
@pytest.fixture(scope="session")
def first():
    print("\n獲取用戶名,scope為session級別多個.py模塊只運行一次")
    a = "yoyo"
    return a

test_fixture11.py和test_fixture12.py用例腳本

test_fixture11.py
 
import pytest
def test_1(first):
    '''用例傳fixture'''
    print("測試賬號:%s" % first)
    assert first == "yoyo"
 
if __name__ == "__main__":
    pytest.main(["-s", "test_fixture11.py"])
    
import pytest
 
def test_2(first):
    '''用例傳fixture'''
    print("測試賬號:%s" % first)
    assert first == "yoyo"
 
if __name__ == "__main__":
    pytest.main(["-s", "test_fixture12.py"])

運行結果:

如果想同時運行test_fixture11.py和test_fixture12.py,在cmd執行

pytest -s test_fixture11.py test_fixture12.py
================================================= test session starts =================================================
platform win32 -- Python 3.6.5, pytest-4.5.0, py-1.8.0, pluggy-0.12.0
rootdir: C:\Users\hgh\PycharmProjects\untitled1\demo
plugins: allure-pytest-2.8.2, html-1.22.0, metadata-1.8.0, rerunfailures-7.0, shutil-1.7.0
collected 2 items

test_fixture11.py
獲取用戶名,scope為session級別多個.py模塊只運行一次
測試賬號:yoyo
.
test_fixture12.py 測試賬號:yoyo
.

============================================== 2 passed in 0.12 seconds ===============================================


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM