TIL

Playwright Python: Tutorial #2 - Pytest

아람2 2025. 2. 21. 14:56
반응형

Playwright Python: Tutorial #2 - Pytest

Tutorial #1 https://helloahram.tistory.com/221 

 

Pytest Plugin 을 설치해준다 

pip install playwright pytest-playwright
playwright install # Playwright Browser 설치

 

파일명은 제일 앞에 test_ 또는 제일 뒤에 _test 로 만들어준다 

ex. test_webpage.py or webpage_test.py 

 

Test Code 를 작성할 때는 반.드.시!

🔥 테스트 함수의 이름 제일 앞에 test_ 를 적어줘야 한다 🔥

그리고 본문에는 아래와 같은 Test Code 예시를 작성해 준다 

# https://youtu.be/IDrTacdVNRM?si=Z5WA1XasgkPyXM8-

from playwright.sync_api import Page
import pytest

def test_title(page: Page):
    page.goto("https://www.saucedemo.com/")
    assert page.title() == "Swag Labs"

def test_inventory_woLogin(page: Page):
    page.goto("https://www.saucedemo.com/inventory.html")
    assert page.inner_text('h3') == "Epic sadface: You can only access '/inventory.html' when you are logged in."

 

예시로 사용한 https://www.saucedemo.com/ 웹사이트는

주어진 아이디와 패스워드로 로그인을 하면 https://www.saucedemo.com/inventory.html 페이지로 이동하고, 

로그인을 하지 않은 경우에서 URL 로 바로 접속 시도하면 경고 문구가 h3 태그로 출력되는 테스트 사이트이다

 

그리고 pytest (또는 pytest --headed) 로 시험해 보면 결과가 잘 출력된다 

~/Desktop/Playwright  pytest --headed

========================== test session starts ===========================
platform darwin -- Python 3.11.11, pytest-8.3.4, pluggy-1.5.0
rootdir: /Users/ahram/Desktop/Playwright
plugins: playwright-0.7.0, base-url-2.1.0
collected 2 items                                                        

tutorial/03_demo_test.py ..                                        [100%]

=========================== 2 passed in 6.56s ============================

 

Base URL 설정 

동일한 URL 을 반복해서 시험할 경우 base-url 을 설정하면

goto("/") 와 같은 상대 URL 을 사용하여 코드를 간단하게 만들 수 있다 

🐣 --base-url 을 통해 기본 URL을 설정해주면 코드가 더 깔끔하고 유지보수가 용이하다 🐣

# https://youtu.be/IDrTacdVNRM?si=Z5WA1XasgkPyXM8-

from playwright.sync_api import Page
import pytest

def test_title(page: Page):
    page.goto("/")
    assert page.title() == "Swag Labs"

def test_inventory_woLogin(page: Page):
    page.goto("/inventory.html")
    assert page.inner_text('h3') == "Epic sadface: You can only access '/inventory.html' when you are logged in."

 

base-url 설정한 Pytest 실행 결과 

 ~/Desktop/Playwright  pytest --headed --base-url=https://www.saucedemo.com
==================== test session starts ====================
platform darwin -- Python 3.11.11, pytest-8.3.4, pluggy-1.5.0
baseurl: https://www.saucedemo.com
rootdir: /Users/ahram/Desktop/Playwright
plugins: playwright-0.7.0, base-url-2.1.0
collected 2 items                                           

tutorial/04_demo_test.py ..                           [100%]

===================== 2 passed in 5.82s =====================

 

실행할 Browser 설정 

그리고 특정 Browser 로 실행하고 싶은 경우 --browser 을 설정하여 실행할 수 있다 

공식 문서 https://playwright.dev/python/docs/running-tests 

# Chromium
pytest --headed --base-url=https://www.saucedemo.com --browser=chromium
# Firefox 
pytest --headed --base-url=https://www.saucedemo.com --browser=firefox
# Chromium + Firefox
pytest --headed --base-url=https://www.saucedemo.com --browser=chromium --browser=firefox

 

Chrome 도 가능하다 (--browser-channel 이라고 기재해줘야 한다)

# Chrome
pytest --headed --base-url=https://www.saucedemo.com --browser-channel=chrome

 

Skip 할 Browser 설정 

특정 Browser 를 Skip 하고 싶은 Test Case 가 있다면, 해당 Test Code 에 상단에 이렇게 설정하면 된다 

@pytest.mark.skip_browser("chromium")

# https://youtu.be/IDrTacdVNRM?si=Z5WA1XasgkPyXM8-
# pytest --headed --base-url=https://www.saucedemo.com

from playwright.sync_api import Page
import pytest

def test_title(page: Page):
    page.goto("/")
    assert page.title() == "Swag Labs"

@pytest.mark.skip_browser("chromium")
def test_inventory_woLogin(page: Page):
    page.goto("/inventory.html")
    assert page.inner_text('h3') == "Epic sadface: You can only access '/inventory.html' when you are logged in."

 

이렇게 Skip 설정을 해 주면 해당 Test Code 의 Chromium Test 는 Skip 해준다 

~/Desktop/Playwright  pytest --headed --base-url=https://www.saucedemo.com --browser=chromium --browser=firefox
==================== test session starts ====================
platform darwin -- Python 3.11.11, pytest-8.3.4, pluggy-1.5.0
baseurl: https://www.saucedemo.com
rootdir: /Users/ahram/Desktop/Playwright
plugins: playwright-0.7.0, base-url-2.1.0
collected 4 items                                           

tutorial/04_demo_test.py .s..                         [100%]

=============== 3 passed, 1 skipped in 9.14s ================

 

특정 Browser 만 실행 

특정 Browser 만 진행하고 싶은 경우에는 Only 를 써주면, 해당 Test Code 에 대해 다른 Browser Test 가 Skip 된다 

@pytest.mark.only_browser("chromium")

# https://youtu.be/IDrTacdVNRM?si=Z5WA1XasgkPyXM8-
# pytest --headed --base-url=https://www.saucedemo.com

from playwright.sync_api import Page
import pytest

def test_title(page: Page):
    page.goto("/")
    assert page.title() == "Swag Labs"

# @pytest.mark.skip_browser("chromium")
@pytest.mark.only_browser("chromium")
def test_inventory_woLogin(page: Page):
    page.goto("/inventory.html")
    assert page.inner_text('h3') == "Epic sadface: You can only access '/inventory.html' when you are logged in."
~/Desktop/Playwright  pytest --headed --base-url=https://www.saucedemo.com --browser=chromium --browser=firefox
==================== test session starts ====================
platform darwin -- Python 3.11.11, pytest-8.3.4, pluggy-1.5.0
baseurl: https://www.saucedemo.com
rootdir: /Users/ahram/Desktop/Playwright
plugins: playwright-0.7.0, base-url-2.1.0
collected 4 items                                           

tutorial/04_demo_test.py ...s                         [100%]

=============== 3 passed, 1 skipped in 9.83s ================

 

 

Test Result 확인하기

--tracing on 을 붙여서 pytest 를 실행하면 Test Result 를 만들어 준다 

pytest --headed --base-url=https://www.saucedemo.com --browser=chromium --tracing on

 

Test Result 는 Test Code 폴더명 + Test Code 파일명 + Test Code 이름으로 만들어지고 각각의 trace.zip 파일이 생성된다 

 

--tracing retain-on-failure 을 붙이면 전체 실행 결과가 아닌, 실패한 결과에 대한 Test Result 를 얻을 수도 있다 

All Passed 인 경우에는 Test Result 폴더가 생성되지 않고, Failed 건에 대한 항목만 생성된다 

pytest --headed --base-url=https://www.saucedemo.com --browser=chromium --tracing retain-on-failure

 

만들어진 trace.zip 을 https://trace.playwright.dev/ 에 Upload 해서 결과를 확인할 수도 있다 

또는, trace.zip 경로를 복사해서 show-trace 옵션으로 로컬에서 직접 확인할 수도 있다 

playwright show-trace /Users/ahram/Desktop/Playwright/test-results/tutorial-04-demo-test-py-test-inventory-wologin-chromium/trace.zip

 

Network Tab 에서는 어떤 요청이 가로채졌는지 확인할 수도 있고 

Action 을 Click or Hover 하면 Source Tab 에서 어떤 Code Line 을 실행하는지, 어떤 Assert 를 사용했는지 등을 확인할 수 있다 

Metadata, Network Tab
Action, Source Tab

 

pytest.ini 만들기

Command 칠 때마다 옵션을 주기 귀찮으니 Root Directory 에 pytest.ini 을 만들고 원하는 옵션들을 설정해 줄 수 있다 

[pytest]
addopts = --base-url https://www.saucedemo.com --headed --browser chromium --browser firefox --tracing on
[pytest]
addopts = --base-url https://www.saucedemo.com --headed --browser chromium --browser firefox --tracing retain-on-failure

 

이러면 pytest 만으로 내가 원하는 옵션들을 한꺼번에 적용 및 실행할 수 있어 편리하다 

 ~/Desktop/Playwright  pytest
======================= test session starts ========================
platform darwin -- Python 3.11.11, pytest-8.3.4, pluggy-1.5.0
baseurl: https://www.saucedemo.com
rootdir: /Users/ahram/Desktop/Playwright
configfile: pytest.ini
plugins: playwright-0.7.0, base-url-2.1.0
collected 4 items                                                  

tutorial/04_demo_test.py ....                                [100%]

======================== 4 passed in 17.10s ========================

 

 

반응형