Junior — Middle
What is the difference between the keywords Yield and Return in the context of testing using PyTest?
sobes.tech AI
Answer from AI
In the context of PyTest, the keywords yield and return are used in fixtures but serve different roles.
-
returnsimply returns a value from the fixture, which will be available to the test. -
yieldis used to split the fixture into two parts: beforeyield— setup, afteryield— cleanup code (teardown). This allows performing actions after the test, such as releasing resources.
Example of a fixture with yield:
import pytest
@pytest.fixture
def resource():
# setup
res = acquire_resource()
yield res
# cleanup
release_resource(res)
If return is used, the code after it will not execute, and cleanup will not happen automatically.
In summary, yield in PyTest fixtures allows convenient management of resource lifecycle, while return simply returns a value.