mark mark - 1 month ago 14
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: http://programeveryday.com/post/pytest-creating-and-using-fixtures-for-streamlined-testing/ - Thank you Dan!

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


Problem is it does not work with session scope:

E AttributeError: function not available in session-scoped context

Answer

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:

@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

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

@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
Comments