自动化神器 Playwright 的 Web 自动化测试解决方案

本贴最后更新于 358 天前,其中的信息可能已经沧海桑田

1. 主流框架的认识

image.png

2. Playwright认识

3. Playwright环境搭建

image.png

image.png

4. Playwright入门实战

1)脚本录制

from playwright.sync_api import Playwright, sync_playwright, expect


def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.goto("http://testingpai.com/")
    page.get_by_text("登录").click()
    page.get_by_placeholder("用户名/邮箱/手机号").click()
    page.get_by_placeholder("用户名/邮箱/手机号").fill("kemi")
    page.get_by_placeholder("用户名/邮箱/手机号").press("Tab")
    page.get_by_placeholder("密码").fill("123456")
    page.pause()  # 断点调试功能
    page.get_by_role("button", name="登录").click()

    # ---------------------
    context.close()
    browser.close()


with sync_playwright() as playwright:
    run(playwright)

2)录制工具快速定位元素

image.png

4. Pytest+Allure+Playwright完整项目演示

1)脚本转为测试用例

image.png

from playwright.sync_api import Page, expect

def test_example(page: Page) -> None:
    page.goto("http://testingpai.com/")
    page.get_by_text("登录").click()
    page.get_by_placeholder("用户名/邮箱/手机号").click()
    page.get_by_placeholder("用户名/邮箱/手机号").fill("kemi")
    page.get_by_placeholder("用户名/邮箱/手机号").press("Tab")
    page.get_by_placeholder("密码").fill("123456")
    page.get_by_role("button", name="登录").click()

image.png

2)数据驱动

import pytest
from playwright.sync_api import Page, expect

# 测试用例数据
case_data = [{'caseid':1,'username':'kemi123', 'password':'kemi123'},
             {'caseid':2,'username':'zhangsan', 'password':'123456'},
             {'caseid':3,'username':'lisi', 'password':'123456'}]

# 数据驱动
@pytest.mark.parametrize('case', case_data)
def test_example(page: Page,case) -> None:
    username = case['username']
    password = case['password']

    page.goto("http://testingpai.com/")
    page.get_by_text("登录").click()
    page.get_by_placeholder("用户名/邮箱/手机号").click()
    page.get_by_placeholder("用户名/邮箱/手机号").fill(username)
    page.get_by_placeholder("用户名/邮箱/手机号").press("Tab")
    page.get_by_placeholder("密码").fill(password)
    page.get_by_role("button", name="登录").click()
    page.screenshot(path=f"images/login/登录{case['caseid']}.png")  # 截图保存到指定位置

3)报告显示

image.png

3 操作
lemonkemi 在 2023-05-19 13:53:49 更新了该帖
lemonkemi 在 2023-05-19 13:50:41 更新了该帖
lemonkemi 在 2023-05-19 13:49:15 更新了该帖
1 回帖
请输入回帖内容 ...