zl程序教程

您现在的位置是:首页 >  其他

当前栏目

【接口测试】Day6-使用requests库

测试接口 requests 使用 Day6
2023-09-11 14:17:06 时间

目录

今日目标

requests

unittest

一、requests库

1 、介绍和安装

2 发送get请求

 3 发送post请求

3.1 提交form表单

3.2 提交json数据

4 其他请求方式(了解)

5 传递URL参数

6 响应内容解析 

案例1

案例1-代码

案例2

​​​​​​​案例2-代码

7 设置请求头

8 设置cookie(了解)

 9 设置session(掌握)

 二、集成UnitTest

案例:使用TPShop项目完成对登录功能的接口测试

实现思路

 代码

生成报告

实现参数化

今日总结


今日目标

requests

  • 使用requests库传递URL参数、设置请求头与请求体
  • 使用requests库获取响应数据
  • 使用requests库发送不同类型的请求 
  • requests库session操作

unittest

  • requests库集成unittest

一、requests库

1 、介绍和安装

介绍:基于python语言开发的一个开源的库,能够完全满足基于HTTP协议的接口测试。

  • 安装: pip3 install requests
  • % pip3 install requests
    Defaulting to user installation because normal site-packages is not writeable
    Collecting requests
      Downloading requests-2.27.1-py2.py3-none-any.whl (63 kB)
         ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 63.1/63.1 kB 400.2 kB/s eta 0:00:00
    Collecting urllib3<1.27,>=1.21.1
      Downloading urllib3-1.26.9-py2.py3-none-any.whl (138 kB)
         ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 139.0/139.0 kB 582.2 kB/s eta 0:00:00
    Collecting idna<4,>=2.5
      Downloading idna-3.3-py3-none-any.whl (61 kB)
         ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 61.2/61.2 kB 273.1 kB/s eta 0:00:00
    Collecting charset-normalizer~=2.0.0
      Downloading charset_normalizer-2.0.12-py3-none-any.whl (39 kB)
    Collecting certifi>=2017.4.17
      Downloading certifi-2022.5.18.1-py3-none-any.whl (155 kB)
         ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 155.2/155.2 kB 368.6 kB/s eta 0:00:00
    Installing collected packages: urllib3, idna, charset-normalizer, certifi, requests
      WARNING: The script normalizer is installed in '/Users/zxf/Library/Python/3.8/bin' which is not on PATH.
      Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
    Successfully installed certifi-2022.5.18.1 charset-normalizer-2.0.12 idna-3.3 requests-2.27.1 urllib3-1.26.9
  • 验证:pip3 show requests
  • % pip3 show requests
    Name: requests
    Version: 2.27.1
    Summary: Python HTTP for Humans.
    Home-page: https://requests.readthedocs.io
    Author: Kenneth Reitz
    Author-email: me@kennethreitz.org
    License: Apache 2.0
    Location: /Users/zxf/Library/Python/3.8/lib/python/site-packages
    Requires: certifi, charset-normalizer, idna, urllib3
    Required-by:

2 发送get请求

# 导包
import requests

# 发送请求
response = requests.get("http://www.baidu.com")

# 查看响应
# 查看响应数据编码格式
print("原始的数据编码为:", response.encoding)
print("设置前响应数据:", response.text)

# 设置响应数据编码格式
response.encoding = "utf-8"
print("设置编码后数据编码为:", response.encoding)
print("设置后响应数据:", response.text)
  • 解决响应数据乱码问题
  1. 获取当前编码格式: 响应.encoding 
  2. 设置新的编码规范: 响应.encoding="utf-8" 

  • 运行结果:

 3 发送post请求

response = requests.post(url, data=None, json=None) 
"""
:param url: 请求的URL
:param data: (可选) 要发送到请求体中的字典、元组、字节或文件对象 
:param json: (可选) 要发送到请求体中的JSON数据
"""

说明:

  • data: 参数接收form表单数据,后台会自动附加form表单请求信息头(data数据格式为字典) 
  • json:参数接收json数据,后台会自动附加json表单请求信息头(headers = {"Content-Type":"application/json"})

3.1 提交form表单

"""
1. 请求TPshop项目的登录接口,
请求数据(username: username, password: 123456, verify_code: 1234)
2. 登录接口URL:http://localhost/index.php?m=Home&c=User&a=do_login
"""

# 导包
import requests

# 发请求
login_url = "http://localhost/index.php?m=Home&c=User&a=do_login"
login_data = {
    "username": "username",
    "password": "123456",
    "verify_code": "8888"
}
response = requests.post(url=login_url, data=login_data)

# 看响应
print(response.json())

到tpshop官网下载页面 下载看安装视频教程,或者自己搭的web也行

3.2 提交json数据

# 导包
import requests

# 发送请求
login_url = "http://IP:端口/api/sys/login"
login_data = {
    "mobile": "13000000000",
    "password": "123456"
}
response = requests.post(url=login_url, json=login_data)

# 查看响应
print(response.json())

4 其他请求方式(了解)

  • put:修改资源
  • delete:删除资源 
  • head:响应数据中只包含请求头,前提是项目中已实现该功能 
  • options:查看接口支持的请求方法,前提是项目中已实现该功能

5 传递URL参数

  • 需求:

 1. 访问TPshop搜索商品的接口,通过查询字符串的方式传递搜索的关键字 iPhone ,并查看响应数据 

2. 请求路径格式为: http://localhost/Home/Goods/search.html?q=iPhone

  • 代码实现: 
# 导包
import requests

# 发送请求
# 直接通过url传递参数
# response = requests.get(" http://localhost/Home/Goods/search.html?q=iphone")

#  通过params传递参数:
#  (1)字符串
urlA = "http://localhost/Home/Goods/search.html"
stringA = "q=iphone"
response = requests.get(url=urlA, params=stringA)

#  (2)字典
dictA = {
    "q": "iphone"
}
response = requests.get(url=urlA, params=dictA)
# 查看响应
print(response.text)

6 响应内容解析 

 

案例1

1). 访问百度首页的接口`http://www.baidu.com`,获取以下响应数据 

2). 获取响应状态码
3). 获取请求URL
4). 获取响应字符编码

5). 获取响应头数据
6). 获取响应的cookie数据 7). 获取文本形式的响应内容 8). 获取字节形式的响应内容

案例1-代码

import requests
# 1). 访问百度首页的接口`http://www.baidu.com`,获取以下响应数据
response = requests.get("http://www.baidu.com")

# 2). 获取响应状态码
print("响应状态码:", response.status_code)

# 3). 获取请求URL
print("URL:", response.url)

# 4). 获取响应字符编码
print("编码格式为:", response.encoding)

# 5). 获取响应头数据
print("响应头信息:", response.headers)
print("Content-Type:", response.headers.get("Content-Type"))

# 6). 获取响应的cookie数据
print("cookies:", response.cookies)
print("提取指定的cookie:", response.cookies.get("BDORZ"))

# 7). 获取文本形式的响应内容
print("文本形式显示响应内容:", response.text)

# 8). 获取字节形式的响应内容
print("获取字节形式的响应内容:", response.content)
print("获取字节形式的响应内容:", response.content.decode("utf-8"))

案例2

1). 访问查询天气信息的接口,并获取JSON响应数据
2). 接口地址:http://www.weather.com.cn/data/sk/101010100.html

​​​​​​​案例2-代码

import requests

# 1). 访问查询天气信息的接口,并获取JSON响应数据
# 2). 接口地址:http://www.weather.com.cn/data/sk/101010100.html

response = requests.get("http://www.weather.com.cn/data/sk/101010100.html")

# 查看响应
print(response.json())

7 设置请求头

  • 使用方法: headers={"Content-Type":"application/json"} 

案例:

"""
1. 请求IHRM项目的登录接口,URL: http://ip:端口/api/sys/login
2. 请求头: Content-Type: application/json
3. 请求体: {"mobile":"13800000002", "password":"123456"}
"""

import requests
login_url = "http://ip:端口/api/sys/login"
login_header = {
    "Content-Type": "application/json"
}
login_data ={
    "mobile": "13800000002",
    "password": "123456"
}
# 发送请求
response = requests.post(url=login_url, json=login_data, headers=login_header)

# 查看响应
print(response.json())

8 设置cookie(了解)

使用:

  • 案例:解决tpshop登录验证码问题 

1. 使用requests库调用TPshop登录功能的相关接口,完成登录操作 

2. 登录成功后获取‘我的订单’页面的数据

接口地址:
获取验证码:http://localhost/index.php?m=Home&c=User&a=verify 

登录用户:(username: 13088888888, password: 123456, verify_code: 1234)

登录:http://localhost/index.php?m=Home&c=User&a=do_login 

我的订单:http://localhost/Home/Order/order_list.html

import requests
# 获取验证码
response = requests.get("http://localhost/index.php?m=Home&c=User&a=verify")
print(response.cookies)
PHPSESSID = response.cookies.get("PHPSESSID")
print(PHPSESSID)

# 登录
login_url = "http://localhost/index.php?m=Home&c=User&a=do_login"
login_data = {
    "username": "13488888888",
    "password": "123456",
    "verify_code": "8888"
}
cookies = {
    "PHPSESSID": PHPSESSID
}
response = requests.post(url=login_url, data=login_data, cookies=cookies)
print(response.json())

# 我的订单:http://localhost/Home/Order/order_list.html
response = requests.get("http://localhost/Home/Order/order_list.html", cookies=cookies)
print(response.text)

 9 设置session(掌握)

  • 作用:

在多个请求之间存储数据并自动添加数据,如cookies 

  • 使用:

实例化: session = requests.Session() 

发送请求:

        request.get() ==> session.get() 

        ...

案例:

1. 使用requests库调用TPshop登录功能的相关接口,完成登录操作 

2. 登录成功后获取‘我的订单’页面的数据

接口地址:
获取验证码:http://localhost/index.php?m=Home&c=User&a=verify 

登录用户:(username: 13088888888, password: 123456, verify_code: 1234)

登录:http://localhost/index.php?m=Home&c=User&a=do_login 

我的订单:http://localhost/Home/Order/order_list.html

import requests 

# 创建session对象
session = requests.Session() 

# 获取验证码
response = session.get("http://localhost/index.php?m=Home&c=User&a=verify")

# 登录
login_url = "http://localhost/index.php?m=Home&c=User&a=do_login" 
login_data = {
    "username": "13488888888",
    "password": "123456",
    "verify_code": "8888"
}
response = session.post(url=login_url, data=login_data)
print(response.json())

# 我的订单:http://localhost/Home/Order/order_list.html
response = session.get("http://localhost/Home/Order/order_list.html") 
print(response.text)

 二、集成UnitTest

UnitTest优势

  • 管理测试用例
  • 提供了丰富的断言
  • 生成测试报告

案例:使用TPShop项目完成对登录功能的接口测试

实现思路

# 导包
# 创建测试类

实现代码:

# 创建测试方法 

        # setup

                # 实例化session对象 

                # 定义验证接口url地址 

                # 定义正如接口url地址

        # teardown
                # 关闭session对象

        # 登录成功
                # 发送验证码请求并断言 

                # 发登录请求并断言

        # 账号不存在
                # 发送验证码请求并断言 

                # 发登录请求并断言

        # 密码错误
                # 发送验证码请求并断言 

                # 发登录请求并断言

 代码

# 获取验证码: http://localhost/index.php?m=Home&c=User&a=verify
# 登录     : http://localhost/index.php?m=Home&c=User&a=do_login

# 导包
import requests
import unittest


# 创建测试类
class TPShopLogin(unittest.TestCase):
    def setUp(self):
        # 实例化session对象
        self.session = requests.Session()
        # 定义验证接口url地址
        self.url_verify = "http://localhost/index.php?m=Home&c=User&a=verify"
        # 定义正如接口url地址
        self.url_login = "http://localhost/index.php?m=Home&c=User&a=do_login"

    # teardown
    def tearDown(self):
        # 关闭session对象
        self.session.close()

    # 登录成功
    def test01_success(self):
        # 发送验证码请求并断言
        response = self.session.get(url=self.url_verify)
        self.assertEqual(200, response.status_code)
        self.assertIn("image", response.headers.get("Content-Type"))

        # 发登录请求并断言
        login_data = {
            "username": "13488888888",
            "password": "123456",
            "verify_code": "8888"
        }
        response = self.session.post(url=self.url_login, data=login_data)
        print(response.json())
        self.assertEqual(200, response.status_code)
        self.assertEqual(1, response.json().get("status"))
        self.assertIn("登陆成功", response.json().get("msg"))

    # 账号不存在
    def test02_user_is_not_exist(self):
        # 发送验证码请求并断言
        response = self.session.get(url=self.url_verify)
        self.assertEqual(200, response.status_code)
        self.assertIn("image", response.headers.get("Content-Type"))

        # 发登录请求并断言
        login_data = {
            "username": "13488888899",
            "password": "123456",
            "verify_code": "8888"
        }
        response = self.session.post(url=self.url_login, data=login_data)
        print(response.json())
        self.assertEqual(200, response.status_code)
        self.assertEqual(-1, response.json().get("status"))
        self.assertIn("账号不存在", response.json().get("msg"))


    # 密码错误
    def test03_password_error(self):
        # 发送验证码请求并断言
        response = self.session.get(url=self.url_verify)
        self.assertEqual(200, response.status_code)
        self.assertIn("image", response.headers.get("Content-Type"))

        # 发登录请求并断言
        login_data = {
            "username": "13488888888",
            "password": "error",
            "verify_code": "8888"
        }
        response = self.session.post(url=self.url_login, data=login_data)
        print(response.json())
        self.assertEqual(200, response.status_code)
        self.assertEqual(-2, response.json().get("status"))
        self.assertIn("密码错误", response.json().get("msg"))

生成报告

# 导包
import time
import unittest
from test10_unittest_tpshop import TPShopLogin
from test12_unittest_params import TPShopLogin2
from tools.HTMLTestRunner import HTMLTestRunner


# 封装测试套件
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TPShopLogin))
suite.addTest(unittest.makeSuite(TPShopLogin2))

# 指定报告路径
report = "./report/report-{}.html".format(time.strftime("%Y%m%d-%H%M%S"))

# 打开文件流
with open(report, "wb") as f:
    # 创建HTMLTestRunner运行器
    runner = HTMLTestRunner(f, title="tpshop接口测试报告")

    # 执行测试套件
    runner.run(suite)

实现参数化

# 获取验证码: http://localhost/index.php?m=Home&c=User&a=verify
# 登录     : http://localhost/index.php?m=Home&c=User&a=do_login

# 导包
import json

import requests
import unittest
from parameterized import parameterized

# 构造测试数据
def build_data():
    test_data = []
    file = "./data/login.json"
    with open(file, encoding="utf-8") as f:
        json_data = json.load(f)
        for case_data in json_data:
            username = case_data.get("username")
            password = case_data.get("password")
            verify_code = case_data.get("verify_code")
            status_code = case_data.get("status_code")
            status = case_data.get("status")
            msg = case_data.get("msg")
            test_data.append((username, password, verify_code, status_code, status, msg))
    print("test_data=".format(username, password, verify_code, status_code, status, msg))
    return test_data


# 创建测试类
class TPShopLogin2(unittest.TestCase):
    def setUp(self):
        # 实例化session对象
        self.session = requests.Session()
        # 定义验证接口url地址
        self.url_verify = "http://localhost/index.php?m=Home&c=User&a=verify"
        # 定义正如接口url地址
        self.url_login = "http://localhost/index.php?m=Home&c=User&a=do_login"

    # teardown
    def tearDown(self):
        # 关闭session对象
        self.session.close()

    # 登录成功
    @parameterized.expand(build_data())
    def test01_login(self, username, password, verify_code, status_code, status, msg):
        # 发送验证码请求并断言
        response = self.session.get(url=self.url_verify)
        self.assertEqual(200, response.status_code)
        self.assertIn("image", response.headers.get("Content-Type"))

        # 发登录请求并断言
        login_data = {
            "username": username,
            "password": password,
            "verify_code": verify_code
        }
        response = self.session.post(url=self.url_login, data=login_data)
        print(response.json())
        self.assertEqual(status_code, response.status_code)
        self.assertEqual(status, response.json().get("status"))
        self.assertIn(msg, response.json().get("msg"))

今日总结

requests

  • 使用requests库传递URL参数、设置请求头与请求体
  • 使用requests库获取响应数据
  • 使用requests库发送不同类型的请求 
  • requests库session操作

unittest

  • requests库集成unittest

一边学习一边记录呀,加油!