模拟接口
介绍
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)