W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵(lì)
除了在測試函數(shù)中使用??fixture
??外,??fixture
??函數(shù)還可以使用其他??fixture
??本身。這有助于??fixture
??的模塊化設(shè)計(jì),并允許在許多項(xiàng)目中重用特定于框架的??fixture
??。作為一個(gè)簡單的例子,我們可以擴(kuò)展前面的例子,實(shí)例化一個(gè)對象應(yīng)用程序,我們將已經(jīng)定義的??smtp_connection
??資源插入其中:
# content of test_appsetup.py
import pytest
class App:
def __init__(self, smtp_connection):
self.smtp_connection = smtp_connection
@pytest.fixture(scope="module")
def app(smtp_connection):
return App(smtp_connection)
def test_smtp_connection_exists(app):
assert app.smtp_connection
這里我們聲明一個(gè)應(yīng)用程序??fixture
??,它接收前面定義的??smtp_connection fixture?
?,并使用它實(shí)例化一個(gè)?app?對象。讓我們運(yùn)行:
$ pytest -v test_appsetup.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 2 items
test_appsetup.py::test_smtp_connection_exists[smtp.gmail.com] PASSED [ 50%]
test_appsetup.py::test_smtp_connection_exists[mail.python.org] PASSED [100%]
============================ 2 passed in 0.12s =============================
由于??smtp_connection
??的參數(shù)化,測試將使用兩個(gè)不同的?App?實(shí)例和各自的smtp服務(wù)器運(yùn)行兩次。應(yīng)用程序??fixture
??不需要知道??smtp_connection
??參數(shù)化,因?yàn)閜ytest將全面分析??fixture
??依賴關(guān)系圖。
請注意,應(yīng)用程序??fixture
??有一個(gè)模塊范圍,并使用一個(gè)模塊范圍的??smtp_connection fixture
??。如果??smtp_connection
??被緩存在一個(gè)會話作用域上,這個(gè)例子仍然可以工作:對于??fixture
??來說,使用更廣泛作用域的??fixture
??是可以的,但反過來不行:一個(gè)會話作用域的??fixture
??不能以有意義的方式使用一個(gè)模塊作用域的??fixture
??。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: