簡體   English   中英

pytest中的夾具執行順序

[英]Fixture order of execution in pytest

我是使用 Pytest 的新手。 我對我的項目中正確使用固定裝置和依賴注入的方法感到有些困惑。 我的框架如下:

conftest.py

@pytest.fixture(scope="session")
def test_env(request):
//some setup here for the entire test module test_suite.py

@pytest.fixture(scope="function")
def setup_test_suite(test_env): 
//some setup that needs to be done for each test function
//eventually parameterize? for different input configuration


test_suite.py
def test_function(setup_test_suite)
//some testing code here
  1. 將設置 function 放在 conftest.py 或測試套件本身有什么區別?
  2. 我希望為整個 session 設置一次測試環境。 如果 setup_test_suite 依賴於 test_env,test_env 會執行多次嗎?
  3. 如果我要參數化 setup_test_suite,調用夾具的順序是什么?
  1. conftest.py和本地測試模塊中的夾具之間的區別在於可見性。 夾具將對同一級別的所有測試模塊以及該級別以下的模塊可見。 如果夾具設置為autouse=True ,它將為這些模塊中的所有測試執行。
    有關更多信息,請查看conftest.py 文件的用途

  2. 如果test_env是基於會話的,那么它只會在 session 中執行一次,即使它在多個測試中被引用。 如果它產生 object,則相同的 object 將傳遞給所有引用它的測試。 例如:

@pytest.fixture(scope="session")
def global_fixt():
    print('global fixture')
    yield 42

@pytest.fixture(scope="function")
def local_fixt(global_fixt):
    print('local fixture')
    yield 5

def test_1(global_fixt, local_fixt):
    print(global_fixt, local_fixt)

def test_2(global_fixt, local_fixt):
    print(global_fixt, local_fixt)

給出 pytest -svv 的pytest -svv

...
collected 2 items

test_global_local_fixtures.py::test_1 global fixture
local fixture
42 5
PASSED
test_global_local_fixtures.py::test_2 local fixture
42 5
PASSED
...
  1. 夾具參數按照它們提供給夾具的順序被調用。 例如,如果您有:
@pytest.fixture(scope="session", params=[100, 1, 42])
def global_fixt(request):
    yield request.param


def test_1(global_fixt):
    assert True

def test_2(global_fixt):
    assert True

測試將按以下順序執行:

test_1 (100)
test_2 (100)
test_1 (1)
test_2 (1)
test_1 (42)
test_2 (42)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM