PythonAPI测试用RESTAssuredPython吗

wen python案例 27

本文目录导读:

PythonAPI测试用RESTAssuredPython吗

  1. 推荐方案
  2. 为什么Python没有REST Assured?
  3. 如果你的需求是类似REST Assured的链式调用:

对于Python API测试,不使用REST Assured,因为REST Assured是Java的库。

在Python中进行API测试,常用的库和框架有:

推荐方案

requests + pytest(最常用)

import requests
import pytest
class TestAPI:
    def test_get_user(self):
        response = requests.get("https://api.example.com/users/1")
        assert response.status_code == 200
        assert response.json()["name"] == "John"

httpx(异步支持更好)

import httpx
response = httpx.get("https://api.example.com/users/1")
print(response.json())

Tavern(类似REST Assured的BDD风格)

# test_api.tavern.yaml
test_name: Get user
stages:
  - name: Get user by ID
    request:
      url: https://api.example.com/users/1
      method: GET
    response:
      status_code: 200
      body:
        name: John

Robot Framework(关键字驱动)

*** Test Cases ***
Get User
    ${response}=    GET    https://api.example.com/users/1
    Should Be Equal As Numbers    ${response.status_code}    200

为什么Python没有REST Assured?

  • REST Assured是Java生态的产物
  • Python有更简洁、Pythonic的解决方案
  • requests库本身就是Python最流行的HTTP库,配合pytest已经足够强大

如果你的需求是类似REST Assured的链式调用:

import requests
from asserts import assert_equal
class RESTAssured:
    def __init__(self):
        self.response = None
    def given(self):
        return self
    def when_get(self, url):
        self.response = requests.get(url)
        return self
    def then_status(self, code):
        assert_equal(self.response.status_code, code)
        return self
    def then_body(self, **kwargs):
        for key, value in kwargs.items():
            assert_equal(self.response.json()[key], value)
        return self
# 使用
RESTAssured().given().when_get("https://api.example.com/users/1").then_status(200).then_body(name="John")

Python API测试推荐使用 requests + pytesthttpx + pytest,这是最成熟、最广泛使用的方式。

抱歉,评论功能暂时关闭!