Python

Pytest 사용하기 - 1. 간단한 예제

r잡초처럼 2023. 1. 31. 20:13

pytest를 활용하여 테스트 코드를 짜보자

설치

우선 가상환경에 진입해서 pytest를 install 하자

pip install pytest

테스트 파일 작성하기

1. 함수형 타입

그런 다음 test_ 로 시작하는 테스트 코드를 실행한 파이썬 실행 파일을 만들자.

# test_demo.py
def test_success_sum():  
    x = 4
    y = 3
    assert x + y == 7


def test_fail_sum():
    x = 4
    y = 3
    assert x + y != 6

각각 더하기를 실행했을 때 성공 케이스(test_success_sum())와 합산이 잘못된 케이스(test_fail_sum())를 작성하였다. 이렇게 작성해도 테스트는 잘 동작하지만, x와 y는 두 함수에서 공통적으로 사용하고 있다. 이것을 공유하는 방법을 사용해 보자

@pytest.fixture
def sum_var():
    return 3 + 4


def test_success_sum(sum_var):
    assert sum_var == 7


def test_fail_sum(sum_var):
    assert sum_var != 6

sum_var라는 함수를 pytest.fixture 데코레이터로 선언해서 변수를 공유할 수 있다. 그런 다음 test case의 매개 변수로 해당 함수를 사용하면 위와 같이 테스트 코드를 작성할 수 있다.
fixture는 사용방법이 다양하므로 해당 문서를 참고하자.

2. 클래스형

class TestClass:
    @pytest.fixture
    def sum_value(self):
        return 7

    def test_success_sum(self, sum_value):
        assert sum_value == 7

    def test_fail_sum(self, sum_var):
        assert sum_var != 6

fixture, teardown 알아보기

해당 문서 참고

1. fixture

fixture는 테스트를 위한 데이터 셋업과 데이터 클리닝이 반복적, 독립적으로 사용될 때 이용한다.
fixture의 실제 사용 예는 다음과 같다.

  • 테스트를 위한 특정 파일과 디렉터리를 만들고 테스트 종료 시 해당 파일과 디렉토리를 삭제한다.
  • DB를 연결하고 테스트 종료 시 DB 연결을 정상적으로 종료한다.

2. teardown

teardown은 각 테스트가 끝난 이후에 호출되는 메서드이다. fixture에서 yield를 활용해서 teardown을 실행한다. pytest에서 권장되는 방식이다.

3. 코드로 살펴보기

공식문서의 예제를 살펴보자. email 라이브러리에 대한 테스트 코드이다

# content of emaillib.py
class MailAdminClient:
    def create_user(self):
        return MailUser()

    def delete_user(self, user):
        # do some cleanup
        pass


class MailUser:
    def __init__(self):
        self.inbox = []

    def send_email(self, email, other):
        other.inbox.append(email)

    def clear_mailbox(self):
        self.inbox.clear()


class Email:
    def __init__(self, subject, body):
        self.subject = subject
        self.body = body

테스트 코드를 작성해 보자. 우선 Admin이 User에게 이메일을 보내고 mailbox를 확인한다는 시나리오를 써보자

from emaillib import Email, MailAdminClient

import pytest


# mail admin 생성
@pytest.fixture
def mail_admin():
    return MailAdminClient()



@pytest.fixture
def sending_user(mail_admin):
    user = mail_admin.create_user()  # user에게 메일을 보내기 위해 user 생성
    yield user
    mail_admin.delete_user(user)  # teardown 실행



@pytest.fixture
def receiving_user(mail_admin):
    user = mail_admin.create_user()  # 메일을 받을 유저 생성
    yield user 
    # teardown 실행
    user.clear_mailbox()  
    mail_admin.delete_user(user)


def test_email_received(sending_user, receiving_user):
    email = Email(subject="Hey!", body="How's it going?")
    sending_user.send_email(email, receiving_user)
    assert email in receiving_user.inbox

참고

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

How to use fixtures — pytest documentation

Autouse fixtures (fixtures you don’t have to request) Sometimes you may want to have a fixture (or even several) that you know all your tests will depend on. “Autouse” fixtures are a convenient way to make all tests automatically request them. This c

docs.pytest.org

https://jangseongwoo.github.io/test/pytest_basic/

PyTest 프레임워크 기초 사용법

이 문서는 Pytest framework에 관하여 학습한 내용을 정리하기 위해 작성되었다.

jangseongwoo.github.io