pytest.fixture 使用說明:
1,函數之間的通信是通過 pytest.fixture來實現的
2,pytest.fixture 可以實現在函數、類、模塊或整個測試會話范圍內重復使用fixture
3,request 使用fixture標記函數后,函數將默認接入一個request參數,它將包含使用該fixture函數的函數信息
在一個文件之中 pytest 運行流程!(以下步驟是根據以下實例來講解,如果遇到其他,請參考!)
1,首先 尋找 test_ 函數,pytest找到了測試函數 test_say
2,測試函數需要一個名為 what 的函數參數,可以放在本文件之中 也可以放在 conftest.py 之中
3,what 就是 被@pytest.fixture 裝飾的函數!
4,調用 what 來創建一個實例。
在 conftest.py 之中定義 fixture 實例
import pytest
import smtplib
# scope="module" 表明每個測試模塊只能調用一次修飾的smtp fixture函數
# scope='module' 一般用於網絡請求之中
@pytest.fixture(scope="module")
def what():
return 'hello'
# 當所有的測試完成之后會調用 yield(不在使用 return)
@pytest.fixture(scope="module")
def file1():
# 使用 with 完成 連接的關閉!
with open("1.txt", 'wb') as file:
file.write('hello file1')
yield file
print('測試完成')
#也可以使用 request.addfinalizer 來完成 測試完最后的工作!
# request.scope= module 將 fixture參數都封裝為 request 屬性!
# 可以增加 params 屬性實現多次 請求!
@pytest.fixture(scope="module",params=["smtp.qq.com", "mail.python.org"])
def smtp(request):
smtp = smtplib.SMTP(request.param, 587, timeout=5)
def fin():
print("執行結束!")
smtp.close()
def fin1():
print('this ok!')
request.addfinalizer(fin)
request.addfinalizer(fin1) #可以注冊多個 功能比 yield 強大!
return smtp
新建文件 test_fix.py
import pytest
# pytest會從conftest.py文件之中搜索 如果你放在 conftest 之中
# 函數傳參 只能傳 被 fixture 裝飾的函數!這是一個很坑的地方
def test_say(what):
print(what)
assert 1 # for demo purposes
# 在此時就能體現 scope="module" 的作用 重用了當前模塊上一個的實例 速度會加快
#兩個測試函數的運行速度與單個測試函數一樣快
# 一般用在網絡請求之中
def test_say1(what):
print(what)
assert 1 # for demo purposes
def test_ehlo(file1):
print('it come from test_fixture_t')
def test_noop(smtp):
assert 0 # for demo purposes