Python 访问@pytest.fixture中的testcase名称

Python 访问@pytest.fixture中的testcase名称,python,pytest,Python,Pytest,我正在写一个@pytest.fixture,我需要一种方法来访问使用fixture的testcase名称的信息 我刚找到一篇文章,内容涵盖了这个主题:-谢谢你,丹 import pytest @pytest.fixture(scope='session') def my_fixture(request): print request.function.__name__ # I like the module name, too! # request.module.__

我正在写一个@pytest.fixture,我需要一种方法来访问使用fixture的testcase名称的信息

我刚找到一篇文章,内容涵盖了这个主题:-谢谢你,丹

import pytest


@pytest.fixture(scope='session')
def my_fixture(request):
    print request.function.__name__
    # I like the module name, too!
    # request.module.__name__
    yield


def test_name(my_fixture):
    assert False
问题是它不适用于会话范围:

E AttributeError:函数在会话作用域上下文中不可用

我认为拥有一个会话范围的固定装置没有意义,因为
@pacbo\u session
(from)在每个函数调用中都有效。因此,我建议简单地这样做:

@pytest.fixture(scope='function')
def placebo_session(request):
    session_kwargs = {
        'region_name': os.environ.get('AWS_DEFAULT_REGION', 'us-east-1')
    }
    profile_name = os.environ.get('PLACEBO_PROFILE', None)
    if profile_name:
        session_kwargs['profile_name'] = profile_name

    session = boto3.Session(**session_kwargs)

    prefix = request.function.__name__

    base_dir = os.environ.get(
        "PLACEBO_DIR", os.path.join(os.getcwd(), "placebo"))
    record_dir = os.path.join(base_dir, prefix)

    if not os.path.exists(record_dir):
        os.makedirs(record_dir)

    pill = placebo.attach(session, data_path=record_dir)

    if os.environ.get('PLACEBO_MODE') == 'record':
        pill.record()
    else:
        pill.playback()

    return session
但是如果您仍然希望在每个会话和每个测试用例中都完成一些事情,那么您可以将其分成两个装置(然后使用
func_session
fixture)


正如作用域所描述的,它在整个测试会话中运行一次,然后在每个测试用例中重复使用。你到底想做什么?也许一种不同的方法可以解决你的问题。拜托,我不想开始pytest vs.讨论,但因为你问:安慰剂组假设你使用鼻测试,所以我使用pytest夹具来做同样的事情。它需要模块和testcase名称来编写文件哦,不,我不是想用其他东西替换pytest(它是最好的:))。我只是想有一个更大的图景,这样会更容易帮助你。这是一个很酷的模式。我没有想到。。。谢谢:)
@pytest.fixture(scope='session')
def session_fixture():
  # do something one per session
  yield someobj

@pytest.fixture(scope='function')
def func_session(session_fixture, request):
  # do something with object created in session_fixture and
  # request.function
  yield some_val