thinwybk
thinwybk

Reputation: 4753

How can I define a setup and teardown function for a specific method or function in pytest?

Pytest supports classical xunit style setup and teardown on the module/class/method/function level (in addition to pytests dependency injection mechanism). The function level setup and teardown functions are invoked for every test function in the module. How can I define setup and teardown functions for specific test functions?

Upvotes: 2

Views: 2025

Answers (1)

xverges
xverges

Reputation: 4718

import pytest

@pytest.fixture
def resource():
   resource = foo()

   yield resource

   resource.cleanup()

def test_feature(resource):
   assert bar(resource) == 27

Using fixtures for setup and cleanup is a better approach that the try...finally suggested in the question comments, even when there is no code reuse goal: your single test is focused on asserting the appropriate conditions, and not on resource cleanup.

Upvotes: 1

Related Questions