注:
学习python自动化测试,需要先学习python基础,主要还是多敲代码,多联系,孰能生巧,你也会是一名合格的程序员
python基础学习:
http://c.biancheng.net/python/
https://www.runoob.com/python3/python3-tutorial.html
编写接口自动化测试,你要了解掌握他的库,比如下面最重要的两个库,unittest和requests;
官方文档:https://docs.python.org/3/library/unittest.html unittest
官方文档:http://2.python-requests.org/zh_CN/latest/user/quickstart.html requests
掌握这两个库,相信做接口测试是完全没问题的。
接口测试post(接口测试有很多种写法,能成功就OK)
1 # coding:utf-8 2 import unittest,time 3 import requests 4 import re 5 6 host = "http://192.168.0.175:8080" 7 8 9 def login(s,username,psw): 10 url = host+"/login.jsp" 11 12 headers = { 13 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0", 14 "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 15 "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", 16 "Accept-Encoding": "gzip, deflate", 17 "Referer": host+"/zentao/user-login.html", 18 #"Cookie": # 头部没登录前不用传cookie,因为这里cookie就是保持登录的 19 "Connection": "keep-alive", 20 "Content-Type": "application/x-www-form-urlencoded", 21 } 22 23 data = {'os_username': 'admin', 24 'os_password': '123456', 25 'os_destination': '', 26 'user_role': '', 27 'atl_token': '', 28 'login': '%E7%99%BB%E5%BD%95' 29 } 30 31 # s = requests.session() 不要写死session 32 33 r1 = s.post(url, data=data, headers=headers) 34 return r1.content 35 36 def is_login_sucess(res): 37 if "登录失败,请检查您的用户名或密码是否填写正确。" in res: 38 return False 39 elif "parent.location=" in res: 40 return True 41 else: 42 return False 43 44 if __name__ == "__main__": 45 s = requests.session() 46 a = login(s,"admin","123456") 47 print(is_login_sucess(a))
封装接口:post和get(要搭建接口自动化测试框架,进行封装可以更加方便)
import requests import json class RunMain: def send_get(self, url, data): res = requests.get(url=url, params=json.dumps(data).json() return res def send_post(self, url, data): res =requests.post(url=url, data=json.dumps(data)).json() return res def run_main(self, url, method, data=None): if method == 'POST': res = self.send_post(url, data) else: res = self.send_get(url, data) return res if __name__ == "__main__": url = 'http://192.168.0.157:18005/oauth/token' data = { 'clientId': 'XXXXXXXXXXXXXXXXX', 'password': '123456', 'userName': 'admin', 'VerificationCode': '', 'VerificationCodeKey': "XXXXXXXXXXXXXXXXXX" } test = RunMain() print(test.run_main(url, 'POST', data))
运行可以得出返回参数
返回参数还可以进行美化,就像Navicat一样
class RunMain: def send_get(self, url, data): res = requests.get(url=url, params=data).json() #return res return json.dumps(res, indent=2, sort_keys=False, ensure_ascii=False) def send_post(self, url, data): res =requests.post(url=url, data=json.dumps(data)).json() #return res return json.dumps(res,indent=2, sort_keys=False, ensure_ascii=False)
结果得到返回参数
每天学一点,未来是你的