Pytest學習之fixture作用范圍(scope)


'''
fixture作用范圍
fixture里面有個scope參數可以控制fixture的作用范圍:session > module > class > function
- function 每一個函數或方法都會調用
- class  每一個類調用一次,一個類可以有多個方法
- module,每一個.py文件調用一次,該文件內又有多個function和class
- session 是多個文件調用一次,可以跨.py文件調用,每個.py文件就是module
'''

import pytest

'scope為function級別'
@pytest.fixture()
def first():
print("\n獲取用戶名")
a="nuo"
return a
@pytest.fixture(scope="function")
def second():
print("\n獲取密碼")
b="123455"
return b

def test_1(first):
'''用例傳fixture'''
print("測試賬號:%s"%first)
assert first=="nuo"

def test_2(second):
'''用例傳fixture'''
print("測試密碼:%s"%second)
assert second=="123455"

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


'fixture放到類里'
@pytest.fixture()
def first():
print("\n獲取用戶名")
a ="nuo"
return a

@pytest.fixture(scope="function")
def second():
print("\n獲取密碼")
b="123456"
return b

class TestCase():
def test_1(self,first):
'''用例傳fixture'''
print("測試賬號:%s"%first)
assert first =="nuo"
def test_2(self,second):
'''用例傳fixture'''
print("測試密碼:%s"%second)
assert second=="123456"

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


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

@pytest.fixture(scope="class")
def first():
print("\n獲取用戶名,scope為class級別只運行一次")
a="nuo"
return a

class TestCase():
def test_1(self,first):
'用例傳fixture'
print("測試賬號:%s"%first)
assert first == "nuo"

def test_2(self,first):
'用例傳fixture'
print("測試賬號:%s"%first)
assert first == "nuo"

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


'scope=module'
'''fixture為module級別時在當前.py腳本里面所有用例開始前只執行一次'''
@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","fixtureandscope.py"])
 
        
'''scope=session'''
'''fixture為session級別是可以跨.py模塊調用的,也就是當我們有多個.py文件的用例時候,如果多個用例只需調用一次fixture,那就可以設置為scope="session",並且寫到conftest.py文件里'''
'''conftest.py文件名稱是固定的,pytest會自動識別該文件。放到工程的根目錄下,就可以全局調用了,如果放到某個package包下,那就只在該package內有效'''
'''如果想同時運行test_fixture11.py和test_fixture12.py,在cmd執行
> pytest -s test_fixture11.py test_fixture12.py
'''


免責聲明!

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



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