Skip to content

Why does @pytest.fixture(autouse=True) not populate namespace of test function? #13171

@ego-thales

Description

@ego-thales

Hi everyone 👋

I'm quite new to pytest and I love it, so... thanks!! I recently understood -- or so I though -- how to use @pytest.fixture(autouse=True) with the setup and teeardown logics separated with yield .

However, I was surprised to discover that the yield statement does not add the fixture to the namespace of the test function. For example, I expected the following to work.

# conftest.py
@pytest.fixture(autouse=True)
def tmp():
    print("setup")
    yield "tmp"
    print("teardown")
    return
# test_file.py
def test_autouse_in_namespace():
    assert tmp == "tmp"

But as you probably know, it fails.

_______________ test_autouse_in_namespace _______________

    def test_autouse_in_namespace():
>       assert tmp == "tmp"
E       NameError: name 'tmp' is not defined

test/test_file.py:2: NameError
----------------- Captured stdout setup -----------------
setup
--------------- Captured stdout teardown ----------------
teardown

My questions are then:

  1. Is there a good reason for pytest not to behave like this?
  2. Is there an elegant pythonic way to emulate this?

Thanks for your time!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions