当您两次同时显式和隐式使用相同的灯具时会发生什么?

问题描述 投票:1回答:1

我有一个函数,它使用了两个夹具'session_id'和'set_namespace'。我最近注意到'set_namespace'固定装置本身正在使用'session_id'固定装置。这两个装置的作用域都设置为会话。这是否意味着我在每个灯具中都会得到不同的结果?

我的代码:

@pytest.fixture(scope='session')
def session_id():
    return random_id(length=5)


@pytest.fixture(scope='session')
def set_namespace(request, session_id, load_config):
    some_dict['namespace'] = session_id


def some_function(session_id, set_namespace):
    does_something
python pytest fixtures
1个回答
0
投票

[不,您将获得相同的会话ID,因为pytest将确保根据scope设置,仅对每个固定装置调用特定的次数。仅仅因为一个灯具使用了另一个灯具就不会改变这一原理。可以使用--setup-show标志pytest --setup-show ./tests/test.py显示按什么顺序确切发生的事情。

测试代码

# tests/test.py
from uuid import uuid4

@pytest.fixture(scope="session")
def session_id():
    return str(uuid4())

@pytest.fixture(scope="session")
def set_namespace(session_id):
    return {"id": session_id}

def test_a(session_id, set_namespace):
    print("\n", session_id, set_namespace, sep="\n")

def test_b(session_id, set_namespace):
    print("\n", session_id, set_namespace, sep="\n")

结果

SETUP    S session_id
SETUP    S set_namespace (fixtures used: session_id)
        tests/test.py::test_a (fixtures used: session_id, set_namespace)

6d3c5d86-4aee-4372-8167-f9c811e69cdc
{'id': '6d3c5d86-4aee-4372-8167-f9c811e69cdc'}
.
        tests/test.py::test_b (fixtures used: session_id, set_namespace)

6d3c5d86-4aee-4372-8167-f9c811e69cdc
{'id': '6d3c5d86-4aee-4372-8167-f9c811e69cdc'}
.
TEARDOWN S set_namespace
TEARDOWN S session_id

Note:pytest还具有--setup-plan标志,该标志不执行任何操作,但是IMHO不考虑范围,因此显示不正确的顺序。

© www.soinside.com 2019 - 2024. All rights reserved.