Skip to content

Commit

Permalink
Merge pull request #2277 from nicoddemus/yield-fixture-docs-2262
Browse files Browse the repository at this point in the history
Improve docs for yield-fixture and with statement a bit
  • Loading branch information
flub committed Mar 1, 2017
2 parents 0a89db2 + bb5f200 commit 3e3f203
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions doc/en/fixture.rst
Expand Up @@ -243,7 +243,9 @@ Fixture finalization / executing teardown code

pytest supports execution of fixture specific finalization code
when the fixture goes out of scope. By using a ``yield`` statement instead of ``return``, all
the code after the *yield* statement serves as the teardown code.::
the code after the *yield* statement serves as the teardown code:

.. code-block:: python
# content of conftest.py
Expand Down Expand Up @@ -275,22 +277,23 @@ occur around each single test. In either case the test
module itself does not need to change or know about these details
of fixture setup.

Note that we can also seamlessly use the ``yield`` syntax with ``with`` statements::
Note that we can also seamlessly use the ``yield`` syntax with ``with`` statements:

.. code-block:: python
# content of test_yield2.py
import smtplib
import pytest
@pytest.fixture
def passwd():
with open("/etc/passwd") as f:
yield f.readlines()
@pytest.fixture(scope="module")
def smtp(request):
with smtplib.SMTP("smtp.gmail.com") as smtp:
yield smtp # provide the fixture value
def test_has_lines(passwd):
assert len(passwd) >= 1
The file ``f`` will be closed after the test finished execution
because the Python ``file`` object supports finalization when
The ``smtp`` connection will be closed after the test finished execution
because the ``smtp`` object automatically closes when
the ``with`` statement ends.


Expand Down

0 comments on commit 3e3f203

Please sign in to comment.