最强自动化测试框架Playwright(17)- 模拟接口

模拟接口

介绍

Web API 通常作为 HTTP 终结点实现。Playwright提供了API来模拟修改网络流量,包括HTTP和HTTPS。页面所做的任何请求,包括 XHR 和获取请求,都可以被跟踪、修改和模拟。使用Playwright,您还可以使用包含页面发出的多个网络请求的HAR文件进行模拟。

模拟 API 请求

以下代码将截获所有调用,并改为返回自定义响应。不会向 API 发出任何请求。测试将转到使用模拟路由的 URL,并断言页面上存在模拟数据。*/**/api/v1/fruits

 如下代码,handle会改变route的返回数据。

def test_mock_the_fruit_api(page: Page):
    def handle(route: Route):
        json = [{"name": "Strawberry", "id": 21}]
        # fulfill the route with the mock data
        route.fulfill(json=json)

    # Intercept the route to the fruit API
    page.route("*/**/api/v1/fruits", handle)

    # Go to the page
    page.goto("https://demo.playwright.dev/api-mocking")

    # Assert that the Strawberry fruit is visible
    page.get_by_text("Strawberry").to_be_visible()

模拟接口返回状态码为500 

def test_mock_the_fruit_api(page: Page):
    def handle(route: Route):
        # json = [{"name": "Strawberry", "id": 21}]
        # # fulfill the route with the mock data
        # route.fulfill(json=json)
        route.fulfill(status=500)

 修改接口响应

有时候需要模拟服务器返回500错误的状态,可以使用page.route拦截请求并修改

这就给我们测试前端的各种异常场景带来了很大的遍历,可以模拟出任何我们希望返回的接口数据

from playwright.sync_api import Playwright, sync_playwright, expect


def handle(route):
    # 状态码改成500 模拟服务器异常
    route.fulfill(status=500)

def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.goto("http://127.0.0.0:8000/login.html")
    page.get_by_placeholder("请输入用户名").click()
    page.get_by_placeholder("请输入用户名").fill("yoyo")
    page.get_by_placeholder("请输入密码").click()
    page.get_by_placeholder("请输入密码").fill("aa123456")

    page.route("/api/login", handle)

    page.get_by_role("button", name="立即登录 >").click()
    page.pause()  # 断点
    # ---------------------
    context.close()
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值