首页 > 其他分享 >接口测试-requests

接口测试-requests

时间:2022-09-19 11:57:17浏览次数:63  
标签:self token 接口 headers json 测试 requests def

引言:你是如何做接口自动化的,用的工具于技术有哪些?

2个维度:

工具:postman、jmeter

代码:requests

一、Requests概述

Requests在官方的文档中,有这么介绍的⼀句话,具体为:HTTP For Humans,翻译过来就是:“让HTTP服务人类”。Requests是非常优秀的⼀个Python的第三方库,它在HTTP的应用层的协议中,客户端与服务端的交互请求, 非常的轻量级,交互非常的友好。

安装:pip install requests

二、Requests的源码结构

在如上的流程图中,我们可以看出,我们常用的请求方法GET,POST,PUT,DELETE的方法,在Requests里都能够很好的得到支持和处理。

三、Requests请求方法的参数

在⼀个请求方法中,我们关心的是它到底需要带哪些参数,主要可以总结为:

简单的我们可以把它总结为:请求地址,请求方法,请求参数(不是必填),和其他的非必填的信息

四、get方法实战

具体展示如下,以百度为例:

 结果如下:

 

其中r.text和r.content区别:

用了request.get方法后,返回一个response对象,这个对象里面存的是服务器返回的所有信息,包括响应头,响应状态码等。

其中返回的网页部分会存在.content和.text两个对象中。如果需要获得这些网页原始数据,我们可以通过r.text 或 r.content来获取数据。

  • .text 存的是.content 编码后的字符串
  • .content中间存的是字节码

一般来说 ,text直接用比较方便,返回的是字符串,但是,有时候会解析不正常,导致返回的是一堆乱码。这时需要用.content.decode('utf-8'),使其正常显示。

总的来说,text是现成的字符串,.content还要编码,但是.text不是所有时候显示都正常(需要用.content.decode()进行手动编码)

想要提取文本就用text,但是如果你想要提取图片、文件,就要用到content。

五、post方法实战

在post的请求方法中,它的形式参数存在两种,⼀种是json形式,还有⼀个是data形式。

json使用场景:请求数据格式是application/json

import requests
def login():
    r=requests.post(
        url="http://47.95.142.233:8000/login/auth/",
        headers={'Content-Type':'application/json'},
        json={"username":"13484545195","password":"asd888"})
    return r.json()["token"]
print(login())

data使用场景:请求数据格式是表单

当为json类型时,如果使用data=,需要序列化处理该如何处理?

import requests
def login():
    r=requests.post(
        url="http://47.95.142.233:8000/login/auth/",
        headers={'Content-Type':'application/json'},
        data=json.dumps({"username":"13484545195","password":"asd888"}))
    return r.json()["token"]
print(login())

六、参数传递

一般情况,想要实现参数传递的方法:

1、函数返回值
2、把动态参数写到一个文件里面,使用到的时候再读取(使用的较多)

a、函数返回值的方式:

import requests
import json
def login():
r=requests.post(
url="http://47.95.142.233:8000/login/auth/",
headers={'Content-Type':'application/json'},
data=json.dumps({"username":"13484545195","password":"asd888"}))
return r.json()["token"]

def index():
r=requests.get(
url="http://47.95.142.233:8000/interface/index",
headers={"Authorization":"JWT {token}".format(token=login())})
print(r.status_code)
print(r.json())
index()

b、读取的方式:

import requests
import json
def write(content):
    with open("token", "w") as f:
        f.write(content)
def read(): with open("token", "r") as f: return f.read()
def login(): r=requests.post( url="http://47.95.142.233:8000/login/auth/", headers={'Content-Type':'application/json'}, data=json.dumps({"username":"13484545195","password":"asd888"})) write(content=r.json()["token"])
def index(): r=requests.get( url="http://47.95.142.233:8000/interface/index", headers={"Authorization":"JWT {token}".format(token=login())}) print(r.status_code) print(r.json()) login() index()

 七、实战-风暴平台

import unittest
import requests
import json
# 将文件写入到filename里 def write(filename,content): with open(filename, "w") as f: f.write(content) # 读取文件filename的内容 def read(filename): with open(filename, "r") as f: return f.read() # 登录接口,将获取到的token,通过变量r,写入filename里 def login(): r=requests.post( url="http://47.95.142.233:8000/login/auth/", headers={'Content-Type':'application/json'}, json={"username":"13484545195","password":"asd888"}) return r
# 由于每次访问都会在头里调用token,那么将其分离出来,并且将文件名命名为:token def headers(): return {"Authorization": "JWT {token}".format(token=read(filename="token"))} # 添加产品的方法 def addProduct(): r=requests.post( url="http://47.95.142.233:8000/interface/product/", headers=headers(), json={"name":"无涯课堂","product_type":"WEB","version":"1.0.0","master":"无涯","description":"this is a test data"}) # 从添加产品的接口里,获取了产品的id,把id写入到名为:productid的文件里 # 如果是int类型的要强制转换为str write(filename="productid",content=str(r.json()["id"])) return r # 查询产品名称 def findProduct(findname): r=requests.get( url="http://47.95.142.233:8000/interface/products?name=findname".format(findname=findname), headers=headers() ) return r # 修改产品 def modifyProduct(): r=requests.put( url="http://47.95.142.233:8000/interface/product/{productid}/".format( productid=read(filename="productid")), headers=headers(), json={"name":"接口产品","product_type":"WEB","version":"V1.0.1","master":"Rose","description":"this is an API product."} ) return r # 删除产品的方法,删除产品是没有参数的 def delProduct(): # 产品id的调用 r=requests.delete( url="http://47.95.142.233:8000/interface/product/{productid}/".format( productid=read(filename="productid")),headers=headers(), ) return r class ApiTest(unittest.TestCase): # 初始化动作,并且把登录接口获取到的token写到文件中去 def setUp(self) -> None: r=login() write(filename="token",content=r.json()["token"]) # 清理动作,什么都不做 def tearDown(self) -> None: pass def test_index(self): '''验证查看首页''' r=requests.get( url="http://47.95.142.233:8000/interface/index", headers=headers()) self.assertEqual(r.status_code,200) self.assertEqual(r.json()["count"]["api"],0) def test_add_product(self): '''测试产品的添加''' r=addProduct() delProduct() self.assertEqual(r.status_code,201) self.assertEqual(r.json()["name"],"无涯课堂") def test_find_productMoren(self): '''默认查询产品名称''' addProduct() r=findProduct(findname="") self.assertEqual(r.status_code,200) def test_find_productMohu(self): '''模糊查询产品名称''' addProduct() r=findProduct(findname="无") self.assertEqual(r.status_code,200) def test_find_productJingque(self): '''精确查询产品名称''' addProduct() r=findProduct(findname="无涯课堂") self.assertEqual(r.status_code,200) def test_modify_productName(self): '''修改产品的名称''' addProduct() r=modifyProduct() delProduct() self.assertEqual(r.json()["name"],"接口产品") def test_modify_productType(self): '''修改产品的类型''' addProduct() r=modifyProduct() delProduct() self.assertEqual(r.json()["product_type"],"WEB") def test_modify_productVersion(self): '''修改产品的版本''' addProduct() r=modifyProduct() delProduct() self.assertEqual(r.json()["version"],"V1.0.1") def test_modify_productMaster(self): '''修改产品的负责人''' addProduct() r=modifyProduct() delProduct() self.assertEqual(r.json()["master"],"Rose") def test_modify_productDescription(self): '''修改产品的描述''' addProduct() r=modifyProduct() delProduct() self.assertEqual(r.json()["description"],"this is an API product.") def test_del_product(self): '''删除产品''' addProduct() r=delProduct() self.assertEqual(r.status_code,204) if __name__ == '__main__': unittest.main()

标签:self,token,接口,headers,json,测试,requests,def
From: https://www.cnblogs.com/wangwt123/p/16705300.html

相关文章

  • 通过自动化单元测试的形式守护系统架构
    1背景随着需求开发迭代,代码库规模逐渐变大,新的团队成员引入等诸多因素,系统起初制定的架构规则不可避免遭到破坏。不仅仅是破坏团队的统一开发规范,更为重要的是随着代码库......
  • allure介绍——生成完美的测试报告
    一、allure简介Allure是输出网页测试报告的一种框架1、该框架是基于Java写的,所以安装该框架需要先安装JDK;2、下载allure命令行工具,路径:https://github.com/allure-frame......
  • 【自动化测试】xpath、css使用及区别
    CSS和XPATH的功能对比对比项定位方式CSSXPATH常规属性id#id_keyword//*[@id=‘id关键字‘]常规属性class.class_name//*[@class=‘class属性名‘]......
  • CentOS6扩容测试
    1、查看当前状态root有7个多G2、新增了一块磁盘sdb,容量为20G3、fdisk/dev/sdb——划分区,新建分区sdb14、mkfs.ext4/dev/sdb——格式化成ext4格式5、pv......
  • 抽象类和接口
    抽象类和接口今天我们将讨论C#中最常见和广泛使用的概念之一。它们用于从小型项目到大型企业级项目。让我们开始吧……抽象类抽象类是一种特殊类型的类,不能被实例化。......
  • 带你掌握如何使用CANN 算子ST测试工具msopst
    摘要:本期带您了解如何使用msopst工具。本文分享自华为云社区《【CANN文档速递13期】算子ST测试工具【msopst】》,作者:昇腾CANN。如何获取msopst工具msopst工具存储在As......
  • 关于IntelliJ IDEA 2020.1 勾选delegate IDE build/run actions to maven后测试类方法
    今天写MAVEN项目时,在执行测试类时发现方法都执行了两次,比如我执行insertAccout的测试类,就保存了两条相同的记录,执行别的测试类的时候,都会附带执行一次插入,产生一条记录,看了......
  • 服务器接口附件限制【1M】解决办法
     一、业务场景:    在后端与手机小程序端接口传附件时,发现经过云服务器的接口交互,附件超过1M就会有如下提示:<html><head><title>413RequestEntityTooLarg......
  • 漫谈测试成长之探索——测试汇报
    作为测试工程师,我们为保障软件项目的质量付出了很多精力。但是,由于我们的工作内容所限制,相对于其他项目角色,我们在项目中很难输出比较直观的成果。又因为工作成果不明显,测......
  • Java【SpringBoot】——添加测试依赖
    在pom.xml添加依赖1<dependency>2<groupId>org.springframework.boot</groupId>3<artifactId>spring-boot-starter-test</artifactId>......