Programming/Pytest

@pytest.fixture

c29130811 2024. 7. 14. 13:02

Pytest Fixture란?

fixture는 setup과 teardown 작업을 수행하는 데 사용되는 데코레이터로 사용된다.

즉, 아래와 같은 형태로 sampe_fixture에서 return한 data 를 test_sample의 인자로 전달 후, 사용할 수 있다는 의미

import pytest

@pytest.fixture
def sample_fixture():
    data = {"key": "value"}
    return data

def test_sample(sample_fixture):
    assert sample_fixture["key"] == "value"

 

어떻게 보면 cypress 등에 beforeEach 등으로 보면 될 듯. 말그대로 테스트 시작전 setup을 하거나 하는 형태로, 물론 위에 써둔 것처럼 테스트를 종료 하고 나서 teardown 정리하는 것 까지..


정말 쉽게 예를 들면, 신규 유저 정보 관련 api를 테스트 한다고 했을 때,

가입을 해야 신규 유저 정보를 테스트 할 수 있으니

@pytest.fixture를 작성한 함수에 유저를 가입한 정보를 return 하게 한다.

느낌적인 너낌

Fixture의 범위 설정

fixture의 기본 범위(scope)는 함수 단위 이지만, scope 값을 통해 조정이 가능하다.

  • function: (기본값) 각 테스트 함수마다 실행
  • class: 각 테스트 클래스마다 실행
  • module: 각 테스트 모듈마다 실행
  • session: 테스트 세션 전체에서 한 번만 실행
import pytest

# funtion
@pytest.fixture(scope="function")
def scope_fixture():
    return {"scope": "function"}

def test_scope(scope_fixture):
    assert scope_fixture["scope"] == "function"


# class
@pytest.fixture(scope="class")
def class_scope_fixture():
    return {"scope": "class"}

class TestClassScope:
    def test_class_scope_1(self, class_scope_fixture):
        assert class_scope_fixture["scope"] == "class"
        
        ...

 

이러하다.

 

yield

간단히 yield는 제너레이터(iteration)을 구현하는 함수로 만나면 함수가 잠시 멈추고, 값을 반환한다.

그리고 함수는 yield 이후의 상태를 기억하고, 다음 호출 시 그 지점부터 다시 시작.

즉 pytest에서의 yield는 설정 작업을 하고, 테스트 함수에 값을 전달한 후, 테스트가 끝나면 정리 작업을 합니다.

import pytest
import requests

@pytest.fixture(scope="session")
def user_data():
    # Setup: create a user
    response = requests.post('http://yourapi.com/user/create', json={
        "username": "test_user",
        "password": "secure_password"
    })
    response.raise_for_status()
    user = response.json()
    yield user
    # Teardown: delete the user
    response = requests.delete('http://yourapi.com/user/delete', json={
        "username": "test_user",
        "password": "secure_password"
    })
    response.raise_for_status()

 

가입하고 user를 테스트 함수에 전달 후, scope에 따라 session에 대한 테스트가 전체 종료되면,
그 다음 코드를 통해 유저를 지운다. 

 

참고

https://docs.pytest.org/en/stable/how-to/fixtures.html

 

728x90

'Programming > Pytest' 카테고리의 다른 글

pytest pytest.ini, conftest.py  (0) 2024.10.27
Requests API 테스트  (0) 2024.08.15
Assertion  (0) 2024.07.13
Pytest  (1) 2024.07.12