2023年6月29日发(作者:)
Python接⼝⾃动化Python 接⼝⾃动化 requests+ unittest⽹上http接⼝⾃动化测试Python实现有很多,我本⼈也是在⽹上途径学了⼀点相关课程。然后运⽤到⼯作中,在这⾥我进⾏下总结,相当于⼯作总结吧,有不对的地⽅ 或者写的不清楚的地⽅。希望⼤神帮忙指出~做测试或者做开发的都知道 常⽤的接⼝测试⼯具有 postman、jmeter等,在使⽤这些⼯具的时候我们就知道常⽤的接⼝类型,还有请求类型。⽐如我⽤的post 、 get请求。关于post、get请求的区别,⼤家可以参考⽹上的其他博客。我后期可能会根据⾃⼰的理解专门写⼀篇关于post、get的⽂章好了闲话不多说我们进⼊正题吧1、脚本所需的库requests python第三⽅库 ⽤于访问⽹络资源安装⽅法:pip install requests如果是⽤ide 在⾥⾯可以直接安装unittest 单元测试框架不仅可以适⽤于单元测试,还可以适⽤WEB⾃动化测试⽤例的开发与执⾏2、结构⽬录3、封装http请求⼀般我都会封装基类 ⽤于较少重复多余的代码class RunMain(): #发送post请求 def send_Post(self,url,data): result = (url= url,data= data).json() res = (result ,ensure_ascii= False , sort_keys= True , indent= 2) return res #发送get请求 def send_Get(self,url,data): result = (url=url, data=data).json() res = (result, ensure_ascii=False, sort_keys=True, indent=2) return res
#根据method来判断是 post请求 还是 get请求 def run_main(self,method ,url = None ,data = None): result = None if method == 'post': result = _Post(url,data) elif method == 'get': result = _Get(url,data) else: print("method值错误") return result4、封装发送邮件的基类有时候我们的测试报告需要发送给开发⼈员或者其他⼈员,这时候就需要我们脚本去发送邮件了#SMTP 服务器主机mail_host = _email('mail_host')#指定 SMTP 服务使⽤的端⼝号mail_port = _email('mail_port')#⽤户名mail_user = _email('mail_user')#邮件密码 授权码mail_pass = _email('mail_pass')#邮件发送⽅邮箱地址sender = _email('sender')#接受邮件放邮箱地址value = _email('receiver')title = _email('subject')content = _email('content')class Email(): def __init__(self): er = [] #获取接收⼈ 列表 for r in str(value).split('/'): (r) #格式化时间 data = ().strftime("%Y-%m-%d %H:%M:%S") t = title+" "+data = MIMEMultipart('mixed') def config_header(self): #设置邮件发送头 ['Subject'] = t ['From'] = sender ['To'] = ":".join(er) def config_content(self): #设置邮件主题 content_plain = MIMEText(content,'plain') (content_plain) def config_file(self): #如果有⽂件,就配置邮件附件 filename ⽤英⽂形式,如果⽤中⽂ 需要改动 if _file(): htmlpath = (_basepath(),'result','') html = open(htmlpath,'rb').read() filehtml = MIMEText(html,'base64','utf-8') filehtml['Content-Type'] = 'application/octet-stream' filehtml['Content-Disposition'] = 'attachment; filename=""' (filehtml) def check_file(self): #判断⽂件是否存在如果存在则返回 True 反之 返回 False reportpath = (_basepath(),'result','') if (reportpath) and not (reportpath) == 0: return True else: return False def send_email(self): _header() _content() _file() try: smtp = () t(mail_host,mail_port) (mail_user, mail_pass) il(sender, er, _string()) () print('邮件已发送注意查收') except Exception as ex: print('邮件发送失败,错误详情:'+str(ex))5、封装读取 配置⽂件的基类#获取⽂件路径basepath = _basepath()config_path = (basepath,'')config = Parser()(config_path)class ReadConfig(): #获取名字为 [HTTP] 的属性值 def get_http(self,name): value = ('HTTP' , name) return value def get_email(self,name): value = ('EMAIL' , name) return value def get_database(self,name): value = ('DATABASE' , name) return value6、⽣成HTML的基类 这个类⽹上有很多 我这是最原始的 有兴趣的朋友可以去美化#⽣成测试报告相关"""A TestRunner for use with the Python unit testing framework. Itgenerates a HTML report to show the result at a simplest way to use this is to invoke its main method. E.g. import unittest import HTMLTestRunner ... define your tests ... if __name__ == '__main__': ()For more customization options, instantiates a HTMLTestRunner more customization options, instantiates a HTMLTestRunner stRunner is a counterpart to unittest's TextTestRunner. E.g. # output to a file fp = file('my_', 'wb') runner = stRunner( stream=fp, title='My unit test', description='This demonstrates the report output by HTMLTestRunner.' ) # Use an external stylesheet. # See the Template_mixin class for more customizable options HEET_TMPL = '' # run the test (my_test_suite)------------------------------------------------------------------------Copyright (c) 2004-2007, Wai Yip TungAll rights ribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions aremet:* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.* Neither the name Wai Yip Tung nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "ASIS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITEDTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR APARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNEROR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, ORPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OFLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDINGNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."""# URL: /software/__author__ = "Wai Yip Tung"__version__ = "0.8.2""""Change HistoryVersion 0.8.2* Show output inline instead of popup window (Viorel Lupu).Version in 0.8.1* Validated XHTML (Wolfgang Borgert).* Added description of test classes and test n in 0.8.0* Define Template_mixin class for customization.* Workaround a IE 6 bug that it does not treat %(heading)s%(report)s%(ending)s