当前位置: 首页 > 工具软件 > Playwright > 使用案例 >

Web自动化测试[playwright结合pytest使用]

程正阳
2023-12-01

安装配置环境

PS D:\Programs\Python\com.davieyang.demo> pip install pytest-playwright
Collecting pytest-playwright
  Downloading pytest_playwright-0.3.0-py3-none-any.whl (10 kB)
Requirement already satisfied: pytest in c:\program files\python37\lib\site-packages (from pytest-playwright) (7.1.2)
Collecting pytest-base-url
  Downloading pytest_base_url-2.0.0-py3-none-any.whl (4.6 kB)
Requirement already satisfied: playwright>=1.18 in c:\program files\python37\lib\site-packages (from pytest-playwright) (1.22.0)
Collecting python-slugify
  Downloading python_slugify-6.1.2-py2.py3-none-any.whl (9.4 kB)
Requirement already satisfied: greenlet==1.1.2 in c:\program files\python37\lib\site-packages (from playwright>=1.18->pytest-playwright) (1.1.2)
Requirement already satisfied: websockets==10.1 in c:\program files\python37\lib\site-packages (from playwright>=1.18->pytest-playwright) (10.1)
Requirement already satisfied: typing-extensions in c:\program files\python37\lib\site-packages (from playwright>=1.18->pytest-playwright) (4.2.0)
Requirement already satisfied: pyee==8.1.0 in c:\program files\python37\lib\site-packages (from playwright>=1.18->pytest-playwright) (8.1.0)
Requirement already satisfied: py>=1.8.2 in c:\program files\python37\lib\site-packages (from pytest->pytest-playwright) (1.11.0)
Requirement already satisfied: iniconfig in c:\program files\python37\lib\site-packages (from pytest->pytest-playwright) (1.1.1)
Requirement already satisfied: importlib-metadata>=0.12 in c:\program files\python37\lib\site-packages (from pytest->pytest-playwright) (4.11.4)
Requirement already satisfied: pluggy<2.0,>=0.12 in c:\program files\python37\lib\site-packages (from pytest->pytest-playwright) (1.0.0)
Requirement already satisfied: attrs>=19.2.0 in c:\program files\python37\lib\site-packages (from pytest->pytest-playwright) (21.4.0)
Requirement already satisfied: atomicwrites>=1.0 in c:\program files\python37\lib\site-packages (from pytest->pytest-playwright) (1.4.0)
Requirement already satisfied: packaging in c:\program files\python37\lib\site-packages (from pytest->pytest-playwright) (21.3)
Requirement already satisfied: tomli>=1.0.0 in c:\program files\python37\lib\site-packages (from pytest->pytest-playwright) (2.0.1)
Requirement already satisfied: colorama in c:\program files\python37\lib\site-packages (from pytest->pytest-playwright) (0.4.4)
Requirement already satisfied: requests>=2.9 in c:\program files\python37\lib\site-packages (from pytest-base-url->pytest-playwright) (2.28.0)
Collecting text-unidecode>=1.3
  Downloading text_unidecode-1.3-py2.py3-none-any.whl (78 kB)
     ---------------------------------------- 78.2/78.2 kB 432.6 kB/s eta 0:00:00
Requirement already satisfied: zipp>=0.5 in c:\program files\python37\lib\site-packages (from importlib-metadata>=0.12->pytest->pytest-playwright) (3.8.0)
Requirement already satisfied: charset-normalizer~=2.0.0 in c:\program files\python37\lib\site-packages (from requests>=2.9->pytest-base-url->pytest-playwright) (2.0.12)
Requirement already satisfied: certifi>=2017.4.17 in c:\program files\python37\lib\site-packages (from requests>=2.9->pytest-base-url->pytest-playwright) (2022.5.18.1)
Requirement already satisfied: idna<4,>=2.5 in c:\program files\python37\lib\site-packages (from requests>=2.9->pytest-base-url->pytest-playwright) (3.3)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\program files\python37\lib\site-packages (from requests>=2.9->pytest-base-url->pytest-playwright) (1.26.9)
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in c:\program files\python37\lib\site-packages (from packaging->pytest->pytest-playwright) (3.0.9)
Installing collected packages: text-unidecode, python-slugify, pytest-base-url, pytest-playwright
Successfully installed pytest-base-url-2.0.0 pytest-playwright-0.3.0 python-slugify-6.1.2 text-unidecode-1.3

命令行运行

创建一个Py文件,并在文件中写入如下代码

# test_my_application.py
def test_example_is_working(page):
    page.goto("https://example.com")
    assert page.inner_text('h1') == 'Example Domain'
    page.click("text=More information")

在命令行中执行:

# Run tests (Chromium and headless by default)
pytest
# Run tests in headed mode
pytest --headed
# Run tests in a different browser (chromium, firefox, webkit)
pytest --browser firefox
# Run tests in multiple browsers
pytest --browser chromium --browser webkit

命令行参数介绍

–headed: Run tests in headed mode (default: headless).
–browser: Run tests in a different browser chromium, firefox, or webkit. It can be specified multiple times (default: all browsers).
–browser-channel Browser channel to be used.
–slowmo Run tests with slow mo.
–device Device to be emulated.
–output Directory for artifacts produced by tests (default: test-results).
–tracing Whether to record a trace for each test. on, off, or retain-on-failure (default: off).
–video Whether to record video for each test. on, off, or retain-on-failure (default: off).
–screenshot Whether to automatically capture a screenshot after each test. on, off, or only-on-failure (default: off).

Slow 模式运行

创建一个Py文件,命名为PlaywrightPytest.py,在文件中写入如下代码

from playwright.sync_api import Page


def test_visit_admin_dashboard(page: Page):
    page.goto("http://www.baidu.com")

命令行执行代码:

PS D:\Programs\Python\com.davieyang.demo\PlayWright> pytest .\PlaywrightPytest.py --slowmo 100
======================================= test session starts ================================================
platform win32 -- Python 3.7.9, pytest-7.1.2, pluggy-1.0.0
rootdir: D:\Programs\Python\com.davieyang.demo\PlayWright
plugins: base-url-2.0.0, html-3.1.1, metadata-2.0.1, playwright-0.3.0
collected 1 item                                                                                                                                                                                                                                                        

PlaywrightPytest.py .                                                                                                                                                                                                                                             [100%]

==================================== 1 passed in 2.66s ====================================================

跳过测试用例

# test_my_application.py
import pytest

@pytest.mark.skip_browser("firefox")
def test_visit_example(page):
    page.goto("https://example.com")
    # ...

指定特殊浏览器执行

代码中指定

# conftest.py
import pytest

@pytest.mark.only_browser("chromium")
def test_visit_example(page):
    page.goto("https://example.com")
    # ...

命令行指定

PS D:\Programs\Python\com.davieyang.demo\PlayWright> pytest .\PlaywrightPytest.py --browser-channel chrome
================================= test session starts =======================================================
platform win32 -- Python 3.7.9, pytest-7.1.2, pluggy-1.0.0
rootdir: D:\Programs\Python\com.davieyang.demo\PlayWright
plugins: base-url-2.0.0, html-3.1.1, metadata-2.0.1, playwright-0.3.0
collected 1 item                                                                                                                                                                                                                                                        

PlaywrightPytest.py .                                                                                                                                                                                                                                             [100%]

=========================================== 1 passed in 1.96s ============================================

定义base-url

创建Py文件,并写入如下代码

from playwright.sync_api import Page


def test_visit_admin_dashboard(page: Page):
    page.goto("category_9732604")


在命令行执行命令

PS D:\Programs\Python\com.davieyang.demo\PlayWright> pytest .\PlaywrightPytest.py --browser-channel chrome --base-url https://blog.csdn.net/dawei_yang000000
============================= test session starts ======================================
platform win32 -- Python 3.7.9, pytest-7.1.2, pluggy-1.0.0
baseurl: https://blog.csdn.net/dawei_yang000000
rootdir: D:\Programs\Python\com.davieyang.demo\PlayWright
plugins: base-url-2.0.0, html-3.1.1, metadata-2.0.1, playwright-0.3.0
collected 1 item                                                                                                                                                                                                                                                        

PlaywrightPytest.py .                                                                                                                                                                                                                                             [100%]
================================= 1 passed in 2.31s =====================================

忽略HTTPS错误

# conftest.py
import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    return {
        **browser_context_args,
        "ignore_https_errors": True
    }

自定义分辨率

# conftest.py
import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    return {
        **browser_context_args,
        "viewport": {
            "width": 1920,
            "height": 1080,
        }
    }

设备模拟

# conftest.py
import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args, playwright):
    iphone_11 = playwright.devices['iPhone 11 Pro']
    return {
        **browser_context_args,
        **iphone_11,
    }

也可以在命令行执行加上参数--device="iPhone 11 Pro"

持久化环境

# conftest.py
import pytest
from playwright.sync_api import BrowserType
from typing import Dict

@pytest.fixture(scope="session")
def context(
    browser_type: BrowserType,
    browser_type_launch_args: Dict,
    browser_context_args: Dict
):
    context = browser_type.launch_persistent_context("./foobar", **{
        **browser_type_launch_args,
        **browser_context_args,
        "locale": "de-DE",
    })
    yield context
    context.close()

结合Unittest单元测试框架执行用例

import pytest
import unittest

from playwright.sync_api import Page


class MyTest(unittest.TestCase):
    @pytest.fixture(autouse=True)
    def setup(self, page: Page):
        self.page = page

    def test_foobar(self):
        self.page.goto("https://microsoft.com")
        self.page.click("#foobar")
        assert self.page.evaluate("1 + 1") == 2

 类似资料: