공부/QA

[QA] pytest

narlo 2025. 12. 13. 13:23

Pytest

  • 파이썬에서 사용하는 테스팅 프레임워크
  • 단위 테스트를 쉽고 효율적으로 작성하고 실행할 수 있게 해 줌
  • 테스트해야 하는 파일의 이름은 test_*.py 또는 *_test.py 형식으로 작성
  • pytest 설치
pip install pytest

 

  • pytest 실행
pytest test_mod.py # 모듈에서 테스트 실행

pytest testing/ # 디렉토리에서 테스트 실행

pytest tests/test_mod.py::test_func # 모듈 내에서 특정 테스트 실행

pytest tests/test_mod.py::TestClass # 클래스의 모든 테스트 실행

pytest tests/test_mod.p::test_func[x1, y2] # 테스트의 특정 매개변수 설정을 지정

 

Unittest와 Pytest

특성 unittest pytest
기본 포함 여부 파이썬 표준 라이브러리 별도 설치 필요
테스트 방식 클래스 기반 함수 기반
상속 필요 여부 unittest.TestCase 상속 필요 상속 불필요
assertion 메서드 다양한 assertion 제공 기본 assertion 외 확장 가능
실행 명령어 python -m unittest pytest
플러그인 시스템 없음 풍부한 플러그인 시스템
parameterize 지원하지 않음 지원
인기 및 커뮤니티 전통적, 널리 사용됨 현대적, 성장 중인 커뮤니티

 

 

  • assert
# assert 수식, "수식이 False일 때 표시할 메시지"
assert a % 2 == 0, "value was odd, should be even"
  • 정규표현식이 예외의 문자열 표현과 일치하는지 테스트
pytest.raises(ValueError, match=r".* 123 .*")

 

 

Fixture

  • 테스트 전/후에 실행할 코드를 정의하여 테스트 환경을 설정하고 정리하는 데 도움을 줌
  • Test / Fixture는 한 번에 하나 이상의 fixture를 요청할 수 있음
  • autouse 속성을 사용해 모든 테스트에서 해당 fixture를 자동으로 요청하도록 할 수 있음
  • scope 속성을 사용해 호출 기준을 지정할 수 있음
    • function, class, module, package, session
  •  yield
    • return 대신 사용
    • teardown 코드는 yield 뒤에 배치
@pytest.fixture
def sending_user(mail_admin):
    user = mail_admin.create_user() #setup
    yield user
    mail_admin.delete_user(user) #teardown
  • 매개변수 설정 (params)
@pytest.fixture(scope="module", params=["smtp.gmail.com", "mail.python.org"])
def smtp_connection(request):
    smtp_connection = smtplib.SMTP(request.param, 587, timeout=5)
    yield smtp_connection
    print(f"finalizing {smtp_connection}")
    smtp_connection.close()