Python+Requests+Unittest+Excel 接口自动化测试框架之Request模块01


1.Requests模块
 a.Request模块是Python中可以实现模拟Http协议的模块
 b.安装方式很多,可以用pip install requests

2.举例

import requests
class Http_Request:
    #定义一个请求函数,传入url,method,param参数
    def http_request(self,url,method,param):
        #对method进行判断并断言,method.upper()对method进行大写处理判断值
        if method.upper()=='GET':
            try:
            #如果是GET,则调用requests的get方法,传入url,param
                res=requests.get(url,param)
            except Exception as e:
                print('get请求出错了,错误是{0}'.format(e))
        elif method.upper()=='POST':
            try:
           #如果是post,则调用requests的post方法,传入url,param
                res=requests.post(url,json=param)
            except Exception as e :
                print('Post请求出错了,错误是{0}'.format(e))
        else:
        #method的值不是get和post
            print('输入的method不能被识别')

        #返回请求的结果
        return res

#if __name__=='__main__':后面的代码只会在运行该文件时执行,被调用的时候不会执行,相当于自己的测试数据

if __name__=='__main__':
    url='http://127.0.0.1:7000/api/XXXXX'  #请求的URL
    testdata={"RoleBaseInfo":{"ASIName":"","RoleName":"Role1","Remark":"Role1"},"PrivilegeList":[]}  #请求参数 Json或是字符串格式

    res=Http_Request().http_request(url,'post',testdata)
    print(res.json())   #打印返回的结果,json格式

    print(res.text)   #打印返回结果 text格式



  

   

 

你可能感兴趣的:(接口自动化测试)