[파이썬] pytest 픽스처 사용법

Introduction

In pytest, fixtures are a powerful feature that allows you to set up and tear down test data or resources. Fixtures are defined as functions, and they can be used to initialize objects, create test data, or establish a testing environment.

In this blog post, we will explore the usage of pytest fixtures in Python and how they can improve the efficiency and readability of your tests.

Installing pytest

Before we get started, let’s make sure you have pytest installed. You can install it using pip:

pip install pytest

Creating a Fixture

To create a fixture, you simply define a function with the @pytest.fixture decorator. This function can then be called by any test function that needs it. Let’s create a simple fixture that returns a list of test data:

import pytest

@pytest.fixture
def test_data():
    data = [1, 2, 3, 4, 5]
    return data

In the above example, the test_data fixture will return the list [1, 2, 3, 4, 5] when called.

Using a Fixture in a Test Function

To use a fixture in a test function, you simply include it as an argument in the test function declaration. pytest will automatically inject the fixture into the test function:

def test_sum(test_data):
    result = sum(test_data)
    assert result == 15

In the test_sum function, the test_data fixture is used as an argument. When the test is run, pytest will call the test_data fixture function and pass the returned value to the test_sum function.

Parametrizing Fixtures

You can also parametrize fixtures to create multiple instances with different inputs. This is useful when you want to test the same functionality with different test data. Let’s modify our previous example to create multiple instances of the test_data fixture:

import pytest

@pytest.fixture(params=["a", "b", "c"])
def test_data(request):
    data = request.param
    return data

In the above example, the test_data fixture is parametrized with three different values: "a", "b", and "c".

Final Thoughts

Using pytest fixtures can greatly simplify your test setup and teardown process. By defining fixtures, you can easily reuse code across multiple tests and make your test functions more concise and focused.

To summarize, pytest fixtures are defined as functions using the @pytest.fixture decorator. They can be injected into test functions as arguments, and you can also parametrize fixtures to create multiple instances with different inputs.

Happy testing!