Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Pytest & fixturesMiddleVery commonPractical

Write a pytest fixture that connects to a device before a test and always disconnects it afterward.

Answer

Use a `yield` fixture: setup runs before `yield`, the yielded object is injected into the test, and teardown resumes after the test finishes. Put critical teardown in a `finally` block when cleanup must run even if setup after connection or the test body raises. This is the standard pytest pattern for resources with a lifecycle.

Strong answer includes

  • uses a yield fixture
  • setup happens before yield and teardown after the test
  • uses finally for guaranteed cleanup when appropriate

Practical example

Yield fixture with guaranteed disconnect
import pytest

@pytest.fixture
def device():
    client = Device()
    client.connect()
    try:
        client.reset()
        yield client
    finally:
        client.disconnect()

def test_device_state(device):
    assert device.status() == "ready"

pytest pauses the fixture at yield while the test runs, then resumes the fixture afterward. finally protects disconnect if reset, the test, or later fixture code raises after connection.

Expected result: The test receives the connected Device instance; disconnect() runs after the test whenever connect() succeeded.

#pytest#fixtures#testing

Sources

pytest documentationpytest · Fixture scope, parametrization, markers and plugin architecture