vlambda博客
学习文章列表

接口测试与unittest的应用(1)


    简单来说就是模拟浏览器发送请求,判断返回内容的一个过程。下面的代码主要是基本的get与post请求,以及unittest的基本模板使用

import requestsimport unittestclass Test_Tq(unittest.TestCase): def setUp(self): print("开始") def tearDown(self): print("结束") def test01(self): #普通get请求带参数 url = "http://v.juhe.cn/weather/index" # para = {"cityname":"北京","key":"221ec2c9d854d2859310ea808cb760fd"} # # # 发送请求 # r = requests.get(url,params=para) # print(r.status_code) # # # 获取json数据 # print(r.json()) # res = r.json() # print(res["reason"]) # print(res["result"]) # print(res["result"]["sk"]) # print(res["result"]["sk"]["temp"])
para = {"cityname":"北京","key":"221ec2c9d854d2859310ea808cb760f"} r = requests.get(url,params=para) # print(r.status_code) res = r.json() print(res) print(res["error_code"]) def test02(self): #普通post请求带参数 url ="http://v.juhe.cn/weather/ip" # para = {"ip":"58.215.185.154","key":"221ec2c9d854d2859310ea808cb760fd"} para = {"ip":"58.215.185","key":"221ec2c9d854d2859310ea808cb760fd"} # 发送post请求 r = requests.post(url,data=para) # 获取json数据 res = r.json() print(res) # print(res["reason"]) def test03(self): #关联测试 url2 = "http://192.168.103.106:1080/webtours/nav.pl?in=home" #通过抓包软件分析登录前需要访问另一个地址获取sessionid s = requests.session()# 为了保持和下一个接口建立相同的连接通道 res = s.get(url2) # print(res.text) usersession = re.findall(r'name=userSession value=(.+?)>',res.text) #通过正则找出session值 print(usersession) # para2 ={"in":"home"} # 接口地址 url ="http://192.168.103.106:1080/webtours/login.pl" para ={"userSession":usersession[0],"username":"jojo","password":"bean","login.x":"54","login.y":"11","login":"Login","JSFormSubmit":"off"} r = s.post(url,data=para) # 发送post请求 # r = requests.post(url,data=para) print(r.text) print(res["error_code"]) self.assertEqual("10001",res["error_code"]) def test04(self): # url ="http://www.kuaidi.com/index-ajaxselectcourierinfo-1202247993797-yunda.html" r = requests.get(url) res = r.json() # print(res)
self.assertEqual(res["company"],"韵达快递") # 判断是否签收 print(res["data"]) print(res["data"][0]) print(res["data"][0]["context"]) self.assertIn("已签收",res["data"][0]["context"])


if __name__ =='__main__': unittest.main()