python接口测试笔记

一、安装requests包

安装requests包:

pip install requests

查看安装的包

pip.exe list

pip.exe show requests

如何查看是否安装成功

import requests

http协议:

客户端(浏览器、使用cmd):发送给请求包---》网络服务器

返回给客户服务器一个响应包

请求包:

首部:header

主体:body

响应包:

首部:header

主体:body

常见的请求格式:

get、post:、delete、put、options

 

get请求和post请求区别:

get用于信息的获取,而且是安全和幂等的。所谓安全意味着该操作用于获取信息而非修改信息,就像数据库查询一样,不会修改,增加数据,不会影响资源的状态;幂等意味着对同一URL的多个请求应该返回同样的结果。

post请求用于修改服务器上的资源的请求。

简单总结

1 get是从服务器上获取数据,post是向服务器传送数据

2 get传送的数据量较小,不能大于2k;post传送的数据量较大

3 get安全性非常低,post安全性较高

 

首部:header

主体:body

 

二、接口测试常用请求

get方法:

import requests

r=requests.get("https://github.com/Ranxf")

r.url

r.text[:20]

r.headers

post请求

requests.post("http://httpbin.org/post")

put请求

requests.put("http://httpbin.org/put")

requests.delete("http://httpbin.org/delete")

2.1 带参数的get请求

url_params = {'q':'gloryroad'}       #    字典传递参数,如果值为None的键不会被添加到url中

r = requests.get('https://cn.bing.com/search',params = url_params)

print(r.url)

type(r.text)

type(r.content)

r.status_code

r.raw

 

三、注册一个用户

import requests

import json

import os

import hashlib

print ("register------")

data = json.dumps({'username': 'wxg', 'password': 'wxg123456', 'email': '1552049711@qq.com'}) #

r = requests.post('http://39.106.41.11:8080/register/', data= data)

print (r.status_code)

print (r.text)

print (type(r.json()))

print (r.json())

四、注册多个用户

import requests

import json

import os

import hashlib

import random

import string

username="".join([string.ascii_lowercase[random.randint(0,25)] for i in range(10)])

print (username)

 

print ("register------")

data = json.dumps({'username': username, 'password': 'wulaoshi12345', 'email': 'wulaoshi@qq.com'}) #

r = requests.post('http://39.106.41.11:8080/register/', data= data)

print (r.status_code)

print (r.text)

print (type(r.json()))

print (str(r.json()))

assert "{'code': '00', 'userid':" in str(r.json())

 

4.1 通过读、写文件注册多个用户名

import requests

import json

import os

import hashlib

import pickle

 

#需要默认文件里面写个初始值1即可

with open("E:\\http\\num.txt") as fp:

    unique_number = fp.readline().strip()

 

print ("register------")

data = json.dumps({'username': 'userdat'+unique_number, 'password': 'wulaoshi12345', 'email': 'wulaoshi@qq.com'}) #

r = requests.post('http://39.106.41.11:8080/register/', data= data)

print (r.status_code)

print (r.text)

print (type(r.json()))

print (str(r.json()))

 

assert "{'code': '00', 'userid':" in str(r.json())

 

with open("E:\\http\\num.txt",'w') as fp:

fp.write(str(int(unique_number)+1))

 

4.2用函数进行封装

import requests

import json

import os

import hashlib

import pickle

 

def send_request(interface,value):

    r = requests.post(interface, data= value)

    return r

 

def get_response_info(response_obj):

    print (response_obj.status_code)

    print (response_obj.text)

    print (type(response_obj.json()))

    print (str(response_obj.json()))

    print (response_obj.url)

 

def assert_response(response_obj,assert_word):

    assert assert_word in str(response_obj.json())

   

#需要默认文件里面写个初始值1

with open("E:\\http\\num.txt","r+") as fp:

    unique_number = fp.readline().strip()

    fp.seek(0,0)

    fp.write(str(int(unique_number)+1))

    

interface='http://39.106.41.11:8080/register/'

value = json.dumps({'username': 'wxg'+unique_number, 'password': 'wulaoshi12345', 'email': 'wulaoshi@qq.com'}) #

 

r=send_request(interface,value)

get_response_info(r)

assert_response(r,"{'code': '00', 'userid':")

4.3 配置数据和程序分离

import requests

import json

import os

import hashlib

import pickle

from conf import *

 

def send_request(interface,value):

    r = requests.post(interface, data= value)

    return r

 

def get_response_info(response_obj):

    print (response_obj.status_code)

    print (response_obj.text)

    print (type(response_obj.json()))

    print (str(response_obj.json()))

    print (response_obj.url)

 

def assert_response(response_obj,assert_word):

    assert assert_word in str(response_obj.json())

   

#需要默认文件里面写个初始值1

with open("e:\\http\\num.txt","r+") as fp:

    unique_number = fp.readline().strip()

    fp.seek(0,0)

    fp.write(str(int(unique_number)+10))

    

interface=register

value = json.dumps({'username': 'wxg'+unique_number, 'password': 'wulaoshi12345', 'email': 'wulaoshi@qq.com'}) #

 

r=send_request(interface,value)

get_response_info(r)

assert_response(r,"{'code': '00', 'userid':")

<think>好的,我现在需要帮用户寻找用于Python接口测试的相关库。首先,用户明确提到了“python api testing libraries”,所以我要先回想自己知道的常用库。 首先想到的是requests,这个库非常基础,用于发送HTTP请求,虽然不是专门为测试设计,但很多测试框架会基于它。然后,可能用户需要更专业的测试框架,比如pytest,它本身是一个测试框架,但可以结合requests来做API测试。另外,还有一些专门的库,比如unittest,这是Python自带的单元测试框架,也可以用来做API测试。 接下来,可能需要更高级的工具,比如Robot Framework,它支持关键字驱动,适合自动化测试。还有httpx,支持异步请求,可能在某些场景下有用。Behave是BDD风格的测试框架,可能适合需要自然语言描述测试用例的情况。 然后,我需要检查用户提供的引用内容,看看有没有相关的信息。引用[4]提到了Postman,虽然它是独立工具,但用户可能也会对Postman的Python库如newman或postman-collection感兴趣。引用[2]提到安装jupyter笔记本和jupytext,可能用户是在Jupyter环境中进行测试,但暂时不确定是否需要特别提及。引用[3]关于Tesseract的安装,可能和接口测试无关,可以忽略。引用[5]关于白噪声测试,可能和API测试关系不大,但如果是测试数据分析相关的API,可能需要考虑,但用户的问题更偏向接口测试,所以可能不相关。 接下来,我需要组织这些信息,按照用户的要求,分点列出库的名称、特点、适用场景和示例代码。同时,用户要求生成相关问题,需要根据回答内容提出相关问题,比如如何选择库、异步测试、集成到CI/CD等。 需要注意的是,用户希望回答结构清晰,帮助逐步解决问题,所以需要分点说明每个库的优缺点,并给出示例代码。同时,引用部分需要自然添加引用标识,比如Postman相关的引用[^4]。 最后,确保所有数学表达式和代码块格式正确,使用中文回答,并生成相关问题。检查是否有遗漏的库,比如aiohttp可能也可以提到,但可能和httpx重复,不过作为异步库还是可以单独列出。还有,像FastAPI的测试客户端,如果用户使用FastAPI框架的话,可以提到TestClient,但需要确认是否属于第三方库。</think>### Python接口测试常用库及工具 以下是针对API测试的Python库及工具分类说明,包含核心功能和使用场景: --- #### 一、基础HTTP请求库 1. **Requests** - **特点**:发送HTTP/HTTPS请求的黄金标准库,适合构造API请求和验证响应 - **场景**:手动编写测试用例或结合测试框架使用 - **示例**: ```python import requests response = requests.get("https://api.example.com/data") assert response.status_code == 200 ``` 2. **HTTPX** - **特点**:支持同步/异步请求,兼容HTTP/2协议 - **场景**:需要处理高并发请求或现代协议特性的测试 - **示例**: ```python async with httpx.AsyncClient() as client: response = await client.get("https://api.example.com/async") ``` --- #### 二、专用测试框架 1. **Pytest + Requests** - **组合优势**:通过插件(pytest-requests)实现参数化测试和夹具管理 - **场景**:需要数据驱动测试或复杂测试套件管理 - **示例**: ```python @pytest.mark.parametrize("user_id", [1, 2, 3]) def test_user_api(user_id): response = requests.get(f"/users/{user_id}") assert "username" in response.json() ``` 2. **Robot Framework** - **特点**:关键字驱动测试,支持自然语言编写用例[^4] - **场景**:非技术人员参与测试脚本编写 - **示例**: ```robotframework *** Test Cases *** Get User Info Create Session api https://api.example.com ${response}= Get Request api /users/1 Should Be Equal As Numbers ${response.status_code} 200 ``` --- #### 三、高级测试工具 1. **Schemathesis** - **原理**:基于OpenAPI规范自动生成测试用例 - **优势**:可发现参数边界问题和非预期输入处理缺陷 - **安装**:`pip install schemathesis` 2. **Tavern** - **特点**:YAML格式声明式测试,支持认证流程测试 - **场景**:需要测试OAuth/JWT等安全机制的API - **示例**: ```yaml test_name: Get user profile stages: - name: Authenticate request: url: "{host}/auth" method: POST response: status_code: 200 ``` --- #### 四、云服务集成方案 1. **Postman+Newman** - **工作流**:在Postman中设计测试集合 → 通过Newman命令行工具集成到CI/CD - **优势**:可视化测试设计+自动化流水线执行 - **示例**: ```bash newman run collection.json --env-var "host=https://api.example.com" ``` --- #### 五、性能测试工具 1. **Locust** - **特点**:Python代码定义用户行为模型,分布式压测支持 - **场景**:需要模拟复杂用户场景的负载测试 - **示例**: ```python from locust import HttpUser, task class ApiUser(HttpUser): @task def get_users(self): self.client.get("/users") ``` --- ### 选择建议参考表 | 需求场景 | 推荐工具 | 复杂度 | |---------------------------|------------------------|--------| | 简单接口验证 | Requests + Pytest | ★☆☆ | | 自动化回归测试 | Robot Framework | ★★☆ | | 协议合规性测试 | Schemathesis | ★★★ | | 安全认证测试 | Tavern | ★★☆ | | CI/CD集成 | Newman + Postman | ★★☆ | | 高并发性能测试 | Locust | ★★★ |
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值