网站开发教程公司,安化网站建设,一站式做网站费用,中信建设有限责任公司 电话模拟接口
介绍
Web API 通常作为 HTTP 终结点实现。Playwright提供了API来模拟和修改网络流量#xff0c;包括HTTP和HTTPS。页面所做的任何请求#xff0c;包括 XHR 和获取请求#xff0c;都可以被跟踪、修改和模拟。使用Playwright#xff0c;您还可以使用包含页面发出的…模拟接口
介绍
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 dataroute.fulfill(jsonjson)# Intercept the route to the fruit APIpage.route(*/**/api/v1/fruits, handle)# Go to the pagepage.goto(https://demo.playwright.dev/api-mocking)# Assert that the Strawberry fruit is visiblepage.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(jsonjson)route.fulfill(status500) 修改接口响应
有时候需要模拟服务器返回500错误的状态可以使用page.route拦截请求并修改
这就给我们测试前端的各种异常场景带来了很大的遍历可以模拟出任何我们希望返回的接口数据
from playwright.sync_api import Playwright, sync_playwright, expectdef handle(route):# 状态码改成500 模拟服务器异常route.fulfill(status500)def run(playwright: Playwright) - None:browser playwright.chromium.launch(headlessFalse)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)