0
点赞
收藏
分享

微信扫一扫

python实战: requests,unittest

龙毓七七 2022-05-03 阅读 140

使用requests库传递URL参数、设置请求头与请求体

使用requests库获取响应数据

使用requests库发送不同类型的请求

requestssession操作

一、requests

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

安装:

安装: pip install requests

验证: pip show requests

2 发送get请求

解决响应数据乱码问题

获取当前编码格式: 响应.encoding

设置新的编码规范: 响应.encoding="utf-8"

# 导包 
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)

3 发送post请求

response = requests.post(url, data=None, json=None) 

说明:

data: 参数接收form表单数据,后台会⾃动附加form表单请求信息头(data数据格式为字典)

json:参数接收json数据,后台会⾃动附加json表单请求信息头

headers = {"Content-Type":"application/json"}

3.1 提交form表单

"""
需求: 
1. 请求TPshop项目的登录接口,请求数据(
username: 13088888888, 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": "13488888888", 
              "password": "123456", 
              "verify_code": "8888" 
             }
response = requests.post(url=login_url, data=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 响应内容解析

用途:断言

实现:

response.status_code :响应状态码

response.url :url地址信息

response.encoding :查看响应数据编码格式

response.headers :查看头部信息

response.cookies : 查看cookies信息

response.text :文本形式查看响应数据

response.content :字节码形式查看响应数据

response.json() json形式查看响应数据

案例一

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

2). 获取响应状态码

3). 获取请求URL

4). 获取响应字符编码

5). 获取响应头数据

6). 获取响应的cookie数据

7). 获取文本形式的响应内容

8). 获取字节形式的响应内容

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"))

8 设置cookie(了解)

产生及应用

使用:

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

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

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

9 设置session(掌握)

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

使用:

实例化: session = requests.Session()

发送请求:

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

...

案例:

二、集成UnitTest

UnitTest优势

管理测试用例

提供了丰富的断言

生成测试报告

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

 

 

实现思路:

# 获取验证码: 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"))
[
  {
    "desc": "登录成功",
    "username": "13488888888",
    "password": "123456",
    "verify_code": "8888",
    "status_code": 200,
    "status": 1,
    "msg": "登陆成功"
  },
    {
    "desc": "账号不存在",
    "username": "13488888899",
    "password": "123456",
    "verify_code": "8888",
    "status_code": 200,
    "status": -1,
    "msg": "账号不存在"
  },
  {
    "desc": "密码错误",
    "username": "13488888888",
    "password": "error",
    "verify_code": "8888",
    "status_code": 200,
    "status": -2,
    "msg": "密码错误"
  }
]

举报

相关推荐

0 条评论