pytest接口自动化-直接上手

发布于:2025-06-26 ⋅ 阅读:(22) ⋅ 点赞:(0)

课程:B站大学
自学接口层自动化。为项目搭建一套完善的自动化框架平台。解放回归测试


接口自动化主流技术栈

在这里插入图片描述
结合项目业务以及提升自己的编码能力,为后续前端打下基础,我选择用代码类自动化,也方便维护。
使用pytest的格式标准:
在这里插入图片描述

request库常用的方法

request库是一种用来模拟http/https请求的库,故http协议有哪些方式,则库中函数就有不同请求方法

二、常用函数

  1. requests.get(url, params=None, ​**kwargs)
    ​功能:发送一个HTTP GET请求到指定的URL。
    ​常用参数:
    url:请求的目标地址。
    params:字典或字节序列,用于在URL中添加查询参数。
    headers:自定义请求头。
    timeout:设置超时时间。
示例:
python
import requests

response = requests.get('https://api.example.com/data', params={'key': 'value'})
print(response.json())
  1. requests.post(url, data=None, json=None, ​**kwargs)
    ​功能:发送一个HTTP POST请求到指定的URL。
    ​常用参数:
    url:请求的目标地址。
    data:字典、字节或文件对象,用于发送表单数据。
    json:字典,用于发送JSON格式的数据。
    headers:自定义请求头。
    timeout:设置超时时间。
​示例:
python
import requests

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.example.com/submit', json=payload)
print(response.status_code)
  1. requests.put(url, data=None, ​**kwargs)
    ​功能:发送一个HTTP PUT请求到指定的URL,通常用于更新资源。
    ​常用参数:
    url:请求的目标地址。
    data:字典、字节或文件对象,用于发送数据。
    headers:自定义请求头。
    timeout:设置超时时间。
​示例:
python
import requests

data = {'key': 'new_value'}
response = requests.put('https://api.example.com/resource/1', data=data)
print(response.json())
  1. requests.delete(url, ​**kwargs)
    ​功能:发送一个HTTP DELETE请求到指定的URL,通常用于删除资源。
    ​常用参数:
    url:请求的目标地址。
    headers:自定义请求头。
    timeout:设置超时时间。
示例:
python
import requests

response = requests.delete('https://api.example.com/resource/1')
print(response.status_code)
  1. requests.head(url, ​**kwargs)
    ​功能:发送一个HTTP HEAD请求到指定的URL,通常用于获取资源的元信息。
    ​常用参数:
    url:请求的目标地址。
    headers:自定义请求头。
    timeout:设置超时时间。
​示例:
python
import requests

response = requests.head('https://api.example.com/resource/1')
print(response.headers)
  1. requests.options(url, ​**kwargs)
    ​功能:发送一个HTTP OPTIONS请求到指定的URL,通常用于获取服务器支持的HTTP方法。
    ​常用参数:
    url:请求的目标地址。
    headers:自定义请求头。
    timeout:设置超时时间。
示例:
python
import requests

response = requests.options('https://api.example.com/resource/1')
print(response.headers['Allow'])
  1. requests.patch(url, data=None, ​**kwargs)
    ​功能:发送一个HTTP PATCH请求到指定的URL,通常用于部分更新资源。
    ​常用参数:
    url:请求的目标地址。
    data:字典、字节或文件对象,用于发送数据。
    headers:自定义请求头。
    timeout:设置超时时间。
示例:
python
import requests

data = {'key': 'updated_value'}
response = requests.patch('https://api.example.com/resource/1', data=data)
print(response.json())

三、通用参数

  1. headers
    ​功能:自定义请求头,常用于传递认证信息或指定内容类型。
    ​示例:
    python
    headers = {‘Authorization’: ‘Bearer token’}
    response = requests.get(‘https://api.example.com/data’, headers=headers)
  2. params
    ​功能:用于GET请求的查询参数。
示例:
python
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://api.example.com/data', params=params)
  1. data
    ​功能:用于POST、PUT、PATCH请求的主体数据。
​示例:
python
data = {'key': 'value'}
response = requests.post('https://api.example.com/submit', data=data)
  1. json
    ​功能:用于发送JSON格式的数据,自动设置Content-Type为application/json。
示例:
python
json_data = {'key': 'value'}
response = requests.post('https://api.example.com/submit', json=json_data)
  1. timeout
    ​功能:设置请求的超时时间,防止请求长时间挂起。
示例:
python
response = requests.get('https://api.example.com/data', timeout=5)
  1. auth
    ​功能:用于基本认证。
示例:
python
from requests.auth import HTTPBasicAuth
response = requests.get('https://api.example.com/data', auth=HTTPBasicAuth('username', 'password'))

四、响应对象的常用属性和方法

  1. response.status_code
    ​功能:获取响应的状态码。
示例:
python
print(response.status_code)
  1. response.text
    ​功能:获取响应的文本内容。
​示例:
python
print(response.text)
  1. response.json()
    ​功能:将响应内容解析为JSON对象。
示例:
python
data = response.json()
print(data)
  1. response.headers
    ​功能:获取响应的头信息。
示例:
python
print(response.headers)
  1. response.cookies
    ​功能:获取响应的cookies。
示例:
python
print(response.cookies)

五、会话管理 (requests.Session)
功能
通过Session对象可以在多个请求之间保持某些参数,如cookies、headers等,提高效率。

示例
python
import requests
session = requests.Session()
session.headers.update({'Authorization': 'Bearer token'})
response1 = session.get('https://api.example.com/data1')
response2 = session.get('https://api.example.com/data2')
session.close()

一般来说,使用了request库中的方法后,会把接口的响应数据都给response对象
response对象的方法如下:
在这里插入图片描述
使用request库中方法遵循的原则:
在这里插入图片描述
示例代纯手打:

import re

import pytest
import requests


class TestDemo:
    access_token = ""
    csrf_token = ""
    session_id = requests.session()

    #get请求,通过params传参
    # def test_get_token(self):
    #     urls = "https://api.weixin.qq.com/cgi-bin/token"
    #     datas = {
    #         "grant_type":"client_credential",
    #         "appid":"wx74a8627810cfa308",
    #         "secret":"e40a02f9d79a8097df497e6aaf93ab80"
    #     }
    #     res = requests.get(url=urls,params=datas)
    #     print(res.json())
    #     TestDemo.access_token = res.json()["access_token"]
    # #post请求,通过datas表单传参或者json传参
    # def test_edit_flag(self):
    #     url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token="+TestDemo.access_token
    #     datas = {"tag":{"id":134, "name":"广东人"}}
    #     res = requests.post(url=url,json=datas)
    #     print(res.json())
    # #文件上传
    # def test_file_upload(self):
    #     url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+TestDemo.access_token+"&type=image"
    #     files = {
    #         "media":open("E:\pythonstudy\pytest_mahsang\pytest_mashang\QQ截图20250323141037.png","rb")
    #     }
    #     res = requests.post(url=url,files=files)
    #     print(res.json())
    #鉴权/越权,访问BBS首页接口
    def test_index(self):
        res = TestDemo.session_id.request(method="get",url="http://47.107.116.139/phpwind/")
        # res = requests.get(url="http://47.107.116.139/phpwind/")
        result = res.text
       #正则表达式
        TestDemo.csrf_token = re.search('name="csrf_token" value="(.*?)"',result)
        print(TestDemo.csrf_token)
    # 登录
    def test_login(self):
        url = "http://47.107.116.139/phpwind/index.php?m=u&c=login&a=dorun"
        headers = {
            "Accept":"application/json,text/javascript,/;q=0.01",
            "X-Requested-With":"XMLHttpRequest"
        }
        datas = {
            "username":"bailisss",
            "password":"123456",
            "csrf_token":TestDemo.csrf_token,
            "backurl":"http://http://47.107.116.139/phpwind/",
            "invite":""
        }
        res = TestDemo.session_id.post(url=url,data=datas,headers=headers)
        # res = requests.post(url=url,data=datas)
        print(res.json())
if __name__ == '__main__':
    pytest.main(['-s', '企微接口自动化测试demo.py'])

接口文档在微信官方文档中
在这里插入图片描述
作业:post请求里面data传参和json传参的区别。

表单文件传参:Content-Type: multipart/form-data

表单传参:Content-Type: x-www-form-urlencoded

文本raw传参:json: Content-Type: application/json

二进制传参:Content-Type: application/octet-stream
在这里插入图片描述
接口3:

统一请求封装

1、解决多个py文件共享session的问题
2、统计请求数据
3、统一异常处理
4、统一日志监控
在实际接口中这很常用:封装api

#统一请求封装
import requests


class RequestUtil:
     session = requests.session()

     def all_send_request(self,method,url,**kwargs):
         res = RequestUtil.session.request(method=method,url=url,**kwargs)
         return res

pytest命名规范

  1. 测试文件命名
    以 test_ 或 _test 开头/结尾的 Python 文件会被 pytest 自动识别并执行,例如:
test_sample.py
sample_test.py

不能以纯数字开头,否则 pytest 无法识别。
2. 测试类命名
测试类的名称需以 Test 开头,且类名不能带 init 方法,否则 pytest 无法识别。例如:

class TestOrder:
    def test_create_order(self):
        assert True

pytest 不要求测试类必须继承 unittest.TestCase。
测试函数命名
以 test_ 开头的函数才会被 pytest 识别并执行,例如:
def test_add_product():
assert 1 + 1 == 2
不能使用 setup、teardown 作为测试函数的名称,否则可能与 pytest 的 setup 和 teardown 机制冲突。

测试方法命名
在测试类中的方法也必须以 test_ 开头:

class TestUser:
    def test_login(self):
        assert True

若方法名未以 test_ 开头,pytest 将不会执行该方法。
测试数据/夹具命名
夹具(fixture)应尽量使用有意义的名称,并可以放入 conftest.py 共享使用:

import pytest

@pytest.fixture
def user_data():
    return {"username": "test_user", "password": "123456"}

def test_user_login(user_data):
    assert user_data["username"] == "test_user"

夹具不需要 test_ 开头,否则会被 pytest 误认为是测试用例。

常见测试用例结构
tests/
│── test_order.py
│── test_user.py
│── conftest.py  # 公共 fixture
│── __init__.py

实践是检验真理的唯一标准


网站公告

今日签到

点亮在社区的每一天
去签到