[英]Using function scoped fixture to setup a class
我在conftest.py
中有一個夾具,帶有 function scope。
@pytest.fixture()
def registration_setup(
test_data, # fixture 1
credentials, # fixture 2
deployment # fixture 3
deployment_object # fixture 4
):
# pre-test cleanup
do_cleanup()
yield
# post-test cleanup
do_cleanup()
我在這樣的測試 class 中使用它:
class TestClass:
@pytest.fixture(autouse=True)
def _inventory_cleanup(self, registration_setup):
log('Cleanup Done!')
def test_1():
...
def test_2():
...
def test_3():
...
現在我想創建一個新測試 class,我在其中為整個 class 運行一次registartion_setup
fixture。這里期望的行為是,首先執行預測試清理,然后執行新測試 class 中的所有測試,然后執行 post - 測試清理。 我怎樣才能做到這一點,感謝您的幫助。
您可以使用與其他測試 class 相同的方法,但將夾具 scope 設置為class
:
class TestClass:
@pytest.fixture(scope='class', autouse=True)
def _inventory_cleanup(self, registration_setup):
log('Cleanup Done!')
def test_1():
...
def test_2():
...
def test_3():
...
但是您隨后需要將夾具registration_setup
的 scope 更改為class
以避免ScopeMismatch
錯誤。
為了繼續將它與function
scope 一起使用,我建議使用兩個行為相同但作用域不同的燈具,如下所示:
@pytest.fixture()
def registration_setup_for_function(
test_data, # fixture 1
credentials, # fixture 2
deployment # fixture 3
deployment_object # fixture 4
):
# pre-test cleanup
do_cleanup()
yield
# post-test cleanup
do_cleanup()
@pytest.fixture(scope='class')
def registration_setup_for_class(
test_data, # fixture 1
credentials, # fixture 2
deployment # fixture 3
deployment_object # fixture 4
):
# pre-test cleanup
do_cleanup()
yield
# post-test cleanup
do_cleanup()
如果您的其他燈具 1、2、3 和 4 有function
scope,您也必須更改它們。
如果您不想擁有兩個具有不同范圍的相同燈具,您可以執行以下操作:
在項目根目錄下的conftest.py
文件中:
def pytest_configure(config):
config.first_test_executed = False
然后,無論你有什么夾具:
@pytest.fixture()
def registration_setup(
test_data, # fixture 1
credentials, # fixture 2
deployment, # fixture 3
deployment_object, # fixture 4
request # Note the request fixture here
):
if 'TestClassWhereFixtureShouldRunOnlyOnce' in request.node.nodeid:
if not request.config.first_test_executed:
# pre-test cleanup
do_cleanup()
yield
# post-test cleanup
do_cleanup()
request.config.first_test_executed = True
else:
# pre-test cleanup
do_cleanup()
yield
# post-test cleanup
do_cleanup()
我知道它仍然有點重復,但這樣你在 class 中的測試將只為整個 class 調用registration_setup
fixture 一次,而其他測試將始終調用它。 也許您現在會找到更好的方法來了解這一點。
有關文檔的更多信息:
非常感謝@Marco.S 的回答。 只需進行少量額外檢查即可使其正常工作
def reg_setup(request):
if 'TestClassWhereFixtureShouldRunOnlyOnce' in request.node.nodeid:
if not request.config.first_test_executed:
# pre-test cleanup
do_cleanup()
request.config.first_test_executed = True
yield
if 'test_last' in request.node.nodeid: # Check for the last test case.
# post-test cleanup
do_cleanup()
else:
# pre-test cleanup
do_cleanup()
yield
# post-test cleanup
do_cleanup()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.