首页 > 其他分享 >Playwright测试REST API

Playwright测试REST API

时间:2023-09-18 11:37:10浏览次数:48  
标签:Playwright GITHUB api request REST API context issue issues

Playwright不仅可以测试Web应用,也可以访问REST API进行测试。考虑以下应用场景:

  • 测试服务器端API。
  • 在进行Web应用测试前,调用一些API探测服务器状态。
  • 在Web应用测试后,调用一些API服务来进行数据验证。

后面的2个选项意味着可以在测试用例中组合Web和API的测试。

举例测试流程如下:

flowchart TD prereq([连接登录Github]) --> create(["创建新Repro"]) create --> bug["创建一个bug"] bug --> post([删除创建的Repro])

源码

import os
from typing import Generator

import pytest
from playwright.sync_api import Playwright, APIRequestContext, expect

GITHUB_API_TOKEN = "XXXXXXXXXX"

# GITHUB_API_TOKEN = os.getenv("GITHUB_API_TOKEN")
assert GITHUB_API_TOKEN, "GITHUB_API_TOKEN is not set"

# GITHUB_USER = os.getenv("GITHUB_USER")

GITHUB_USER = "xxxxxxxxx"
assert GITHUB_USER, "GITHUB_USER is not set"

GITHUB_REPO = "test"  # 临时测试使用的repo名字

@pytest.fixture(scope="session")
def api_request_context(playwright: Playwright) -> Generator[APIRequestContext, None, None]:
    headers = {
        # We set this header per GitHub guidelines.
        "Accept": "application/vnd.github.v3+json",
        # Add authorization token to all requests.
        # Assuming personal access token available in the environment.
        "Authorization": f"token {GITHUB_API_TOKEN}",
    }

    request_context = playwright.request.new_context(
        base_url="https://api.github.com", extra_http_headers=headers
    )
    yield request_context
    request_context.dispose()


# Create repo
# ...
@pytest.fixture(scope="session", autouse=True)
def create_test_repository(
        api_request_context: APIRequestContext,
) -> Generator[None, None, None]:
    # Before all
    new_repo = api_request_context.post("/user/repos", data={"name": GITHUB_REPO})
    assert new_repo.ok
    yield
    # After all
    deleted_repo = api_request_context.delete(f"/repos/{GITHUB_USER}/{GITHUB_REPO}")
    assert deleted_repo.ok


def test_should_create_bug_report(api_request_context: APIRequestContext) -> None:
    data = {
        "title": "[Bug] report 1",
        "body": "Bug description",
    }
    new_issue = api_request_context.post(f"/repos/{GITHUB_USER}/{GITHUB_REPO}/issues", data=data)
    assert new_issue.ok

    issues = api_request_context.get(f"/repos/{GITHUB_USER}/{GITHUB_REPO}/issues")
    assert issues.ok
    issues_response = issues.json()
    issue = list(filter(lambda issue: issue["title"] == "[Bug] report 1", issues_response))[0]
    assert issue
    assert issue["body"] == "Bug description"


def test_should_create_feature_request(api_request_context: APIRequestContext) -> None:
    data = {
        "title": "[Feature] request 1",
        "body": "Feature description",
    }
    new_issue = api_request_context.post(
        f"/repos/{GITHUB_USER}/{GITHUB_REPO}/issues", data=data
    )
    assert new_issue.ok

    issues = api_request_context.get(f"/repos/{GITHUB_USER}/{GITHUB_REPO}/issues")
    assert issues.ok
    issues_response = issues.json()
    issue = list(
        filter(lambda issue: issue["title"] == "[Feature] request 1", issues_response)
    )[0]
    assert issue
    assert issue["body"] == "Feature description"

playwright.request.new_context类似requests库中的session的含义

加入web一起的组合用例

def test_last_created_issue_should_be_first_in_the_list(api_request_context: APIRequestContext, page: Page) -> None:
    def create_issue(title: str) -> None:
        data = {
            "title": title,
            "body": "Feature description",
        }
        new_issue = api_request_context.post(
            f"/repos/{GITHUB_USER}/{GITHUB_REPO}/issues", data=data
        )
        assert new_issue.ok

    create_issue("[Feature] request 1")
    create_issue("[Feature] request 2")
    page.goto(f"https://github.com/{GITHUB_USER}/{GITHUB_REPO}/issues")
    first_issue = page.locator("a[data-hovercard-type='issue']").first
    expect(first_issue).to_have_text("[Feature] request 2")

标签:Playwright,GITHUB,api,request,REST,API,context,issue,issues
From: https://www.cnblogs.com/herbert/p/17711404.html

相关文章

  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-16-处理模态对话框弹窗
    1.简介我们在日常工作中,会经常遇到弹出警告框的问题,弹框无法绕过,必须处理才可以执行后续的测试,所以弹框处理也是我们必须掌握的一个知识。宏哥在java+selenium系列文章中介绍过这部分内容。那么,playwright对于弹框的处理是怎样的?是否比selenium更加简单呢?下面我们就来介绍一下pla......
  • Postman测试金蝶云星空Webapi【协同开发云下的本地环境】
    业务背景:基于金蝶云星空提供的接口测试,交付之前或者联调之前开发者先自测,即使纠错,提高效率。  大致流程:先请求登录接口,获得token后再请求标准webapi或者自定义接口,这样上下文才不会空。 说明: 金蝶的接口格式一般为:http://ServerIp/K3Cloud/接口命名空间.接口实现类名......
  • playwright的自用实例
    这是自己用的例子,记录一下,以后好翻看。主要涉及的是定位元素。fromplaywright.sync_apiimportsync_playwrightplaywright=sync_playwright().start()browser=playwright.chromium.launch(headless=False,slow_mo=2000)page=browser.new_page()page.goto("https://www......
  • Stream Api
    作用:处理集合和数组等数据。java8引入的特点:基于数据源的一种元素序列,可以通过数据源的元素,进行某种操作,比如:过滤、排序、映射等。这些操作不会修改元数据的内容。流支持链式调用,每次操作都会返回一个新的流对象,可以连续操作。流操作可以分为两类:中间操作和终端操作,中间操作是指,对......
  • API商品数据接口:实现电子商务应用程序的核心功能
    随着电子商务的飞速发展,许多电商平台都提供了应用程序接口(API),允许开发者调用特定的功能,如商品查询、购物车管理、订单处理以及支付等。这些API为开发者提供了在应用程序中嵌入电商功能的机会,从而为用户提供更加便捷的购物体验。本文将深入探讨API商品数据接口的相关概念、实现方法......
  • K8S你学废了么5——Secret与downloadAPI
    一、背景介绍前面介绍的k8s中的pv存储卷与cm存储卷,k8s中还有2中特殊的存储卷:secret和downloadAPI。其作用分别是用来存放敏感信息和将pod中的信息暴漏给pod中运行的代码,这也是k8s中经常会用到的两个存储卷,下面就这两个存储卷展开详细说明。二、Secret存储卷尽管configMap资源也可以......
  • FastAPI学习-15.JSON 编码器 jsonable_encoder
    前言在某些情况下,您可能需要将数据类型(如Pydantic模型)转换为与JSON兼容的数据类型(如dict、list等)。比如,如果您需要将其存储在数据库中。对于这种要求, FastAPI提供了jsonable_encoder()函数。使用jsonable_encoderjsonable_encoder在实际应用场景中,可能需要将数据类型(如:Py......
  • FastAPI学习-16.响应状态码 status_code
    前言与指定响应模型的方式相同,你也可以在以下任意的_路径操作_中使用 status_code 参数来声明用于响应的HTTP状态码:@app.get()@app.post()@app.put()@app.delete()响应状态码fromfastapiimportFastAPIapp=FastAPI()@app.post("/items/",status_code=201)......
  • FastAPI学习-17.其它响应html,文件,视频或其它
    前言通过我们返回JSON类型的接口会比较多,除了返回JSON格式,还可以响应其它格式的内容JSONResponseContent-Type 会被设置成 application/jsonHTMLResponseContent-Type 会被设置成 text/htmlPlainTextResponse Content-Type 会被设置成text/plainORJSONResp......
  • FastAPI学习-18.Response 返回 XML 格式
    前言假设你想要返回一个 XML响应。你可以把你的XML内容放到一个字符串中,放到一个 Response 中,然后返回。Response自定义返回可以把XML内容放到一个字符串中,放到一个 Response 中,设置media_type="application/xml"fromfastapiimportFastAPI,Responseapp=Fa......