TDD - Pytest Allure Report에 스크린샷 첨부

정태경·2022년 10월 7일
0

TDD

목록 보기
8/10
post-thumbnail

이번 게시글에서는 밋밋한 Allure Report를 조금 더 활용해볼 예정이다.
만약 E2E 테스트 수행 중 스크린샷을 캡처하고 이를 Allure Report에 첨부하고 싶다면 어떻게 할 수 있을까?

Allure Report에 스크린샷 첨부

파이썬 코드 상에서 allure 패키지를 import 한 후 allure.attach() 메서드를 활용하면 테스트 결과 보고서에 텍스트, 이미지 등을 첨부할 수 있다.

import allure
from allure_commons.types import AttachmentType

@pytest.mark.parametrize("username, password, site", get_data(), ids=["google login", "kakao login", "myrealtrip login"])
def test_login(username, password, site):
    driver.find_element(By.ID, "email").send_keys(username)
    driver.find_element(By.ID, "pass").send_keys(password)
    allure.attach(driver.get_screenshot_as_png(), name="Screenshot", attachment_type=AttachmentType.PNG)

그렇다면 조금 더 응용해서 테스트 케이스가 실패했을 때에만 이미지를 첨부하고 싶다면 어떻게 해야할까?
우선 pytest에서 테스트 실행 결과를 받아와야하고, 실행 결과가 Fail일 때만 스크린샷을 캡처해야할 것 같다. 코드로 구현해보자.

1. conftest.py 파일에 pytest_runtest_makereport() 훅을 정의한다.

pytest_runtest_makereport()는 pytest에서 기본적으로 지원하는 hook인데 테스트 결과를 바탕으로 리포트를 만드는 hook이다.

# conftest.py

import pytest


@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    setattr(item, "rep_" + rep.when, rep)
    return rep

2. fixture를 정의한다.

# test_integreation.py

import allure
from allure_commons.types import AttachmentType
import pytest

@pytest.fixture()
def capture_screenshot(request):

    yield
    item = request.node
    if item.rep_call.failed: 
        allure.attach(driver.get_screenshot_as_png(), name="Screenshot", attachment_type=AttachmentType.PNG)

3. 테스트 케이스에 생성한 userfixture를 지정한다.

# test_integreation.py


@pytest.mark.usefixtures("capture_screenshot")
@pytest.mark.parametrize("username, password, site", get_data(), ids=["google login", "kakao login", "myrealtrip login"])
def test_login(username, password, site):
    driver.find_element(By.ID, "email").send_keys(username)
    driver.find_element(By.ID, "pass").send_keys(password)
    assert False

4. 리포트 확인

아래와 같이 테스트 케이스 실패 시에만 스크린샷이 첨부되는 것을 확인할 수 있다.

profile
現 두나무 업비트 QA 엔지니어, 前 마이리얼트립 TQA 엔지니어

0개의 댓글