r잡초처럼
바른 프로그래밍
r잡초처럼
전체 방문자
오늘
어제
  • 분류 전체보기 (124)
    • FastAPI (7)
    • 끄적끄적 (2)
    • Python (17)
    • Django (31)
    • Database (2)
    • Docker (7)
    • 디자인패턴 (2)
    • CS 공부 (12)
      • 알고리즘 (2)
      • 자료 구조 (1)
      • 네트워크 (7)
      • IT 지식 (1)
      • 운영체제 (1)
    • 기타 팁들 (10)
    • Aws (2)
    • 독서 (1)
    • 코딩테스트 공부 (1)
      • 백준 (0)
      • 프로그래머스 (1)
    • DevOps (13)
    • TIL (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • fastapi
  • validate
  • 전기 신호
  • 랜과 왠
  • dotenv
  • 완벽한 IT 인프라 구축을 위한 Docker
  • 케이블의 종류
  • 상속과 컴포지션
  • preonboarding
  • query param
  • 7장
  • 물리 계층
  • 파이썬 클린 코드
  • 모두의 네트워크
  • poetry
  • encoding
  • pytest
  • 책 리뷰
  • 5장 회사에서 하는 랜 구성
  • CS 지식
  • 네트워크
  • 컴퓨터 기본 지식
  • depends
  • pycharm
  • docker
  • cp949
  • Batch
  • 상속 안티 패턴
  • 랜 카드
  • 6장

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
r잡초처럼

바른 프로그래밍

Python

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

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

'Python' 카테고리의 다른 글

Pytest - 3. Monkeypatching functions  (0) 2023.02.03
Pytest - 2. Fixture 알아보기  (0) 2023.02.01
파이썬으로 배우는 자료구조 핵심 원리  (0) 2023.01.30
Python 3.10 변경점 알아보기 - 1. Parenthesized context managers, Better error messages  (0) 2023.01.28
WSL2 환경에서 Poetry 사용하기  (0) 2023.01.16
    'Python' 카테고리의 다른 글
    • Pytest - 3. Monkeypatching functions
    • Pytest - 2. Fixture 알아보기
    • 파이썬으로 배우는 자료구조 핵심 원리
    • Python 3.10 변경점 알아보기 - 1. Parenthesized context managers, Better error messages
    r잡초처럼
    r잡초처럼
    오늘보다 내일 더 나은 개발자가 되기 위한 노력을 기록하는 블로그 입니다.

    티스토리툴바