mark mark - 3 months ago 34
Python Question

access testcase name in @pytest.fixture

I am writing a @pytest.fixture and I need a way to get access to the information of the name of the testcase where the fixture is used.

I just found an article that covers the topic: - Thank you Dan!

import pytest

def my_fixture(request):
print request.function.__name__
# I like the module name, too!
# request.module.__name__

def test_name(my_fixture):
assert False

Problem is it does not work with session scope:

E AttributeError: function not available in session-scoped context


I think that there is no point in have a session scoped fixture, because the @placebo_session (from here) works per function call. So i suggest to simply do it like that:

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):

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

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

    return session

But if you will want to still have something done per session and both per testcase, you can split into two fixtures (and then use func_session fixture).

def session_fixture():
  # do something one per session
  yield someobj

def func_session(session_fixture, request):
  # do something with object created in session_fixture and
  # request.function
  yield some_val