Python接口自动化

Python接口自动化

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""" # variables: (title, generator, stylesheet, heading, report, ending) # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # Stylesheet # # alternatively use a for external style sheet, e.g. # STYLESHEET_TMPL = """""" # ------------------------------------------------------------------------ # Heading # HEADING_TMPL = """

%(title)s

%(parameters)s

%(description)s

""" # variables: (title, parameters, description) HEADING_ATTRIBUTE_TMPL = """

%(name)s: %(value)s

""" # variables: (name, value) # ------------------------------------------------------------------------ # Report # REPORT_TMPL = """

ShowSummaryFailedAll

%(test_list)s
Test Group/Test case Count Pass Fail Error View
Total %(count)s %(Pass)s %(fail)s %(error)s  
""" # variables: (test_list, count, Pass, fail, error) REPORT_CLASS_TMPL = r""" %(desc)s %(description)s %(count)s %(Pass)s %(fail)s %(error)s Detail""" # variables: (style, desc, count, Pass, fail, error, cid) REPORT_TEST_WITH_OUTPUT_TMPL = r"""
%(desc)s
%(status)s """ # variables: (tid, Class, style, desc, status) REPORT_TEST_NO_OUTPUT_TMPL = r"""
%(desc)s
%(status)s""" # variables: (tid, Class, style, desc, status) REPORT_TEST_OUTPUT_TMPL = r"""%(id)s: %(output)s""" # variables: (id, output) # ------------------------------------------------------------------------ # ENDING # ENDING_TMPL = """
 
"""# -------------------- The end of the Template class -------------------TestResult = sultclass _TestResult(TestResult): # note: _TestResult is a pure representation of results. # It lacks the output and reporting ability compares to unittest._TextTestResult. def __init__(self, verbosity=1): TestResult.__init__(self) 0 = None 0 = None s_count = 0 e_count = 0 _count = 0 ity = verbosity # result is a list of result in 4 tuple # ( # result code (0: success; 1: fail; 2: error), # TestCase object, # Test output (byte string), # stack trace, # ) = [] def startTest(self, test): est(self, test) # just one buffer for both stdout and stderr Buffer = IO() stdout_ = Buffer stderr_ = Buffer 0 = 0 = = stdout_redirector = stderr_redirector def complete_output(self): """ Disconnect output redirection and return buffer. Safe to call multiple times. """ if 0: = 0 = 0 0 = None 0 = None return ue() def stopTest(self, test): # Usually one of addSuccess, addError or addFailure would have been called. # But there are some path in unittest that would bypass this. # We must disconnect stdout in stopTest(), which is guaranteed to be called. te_output() def addSuccess(self, test): s_count += 1 cess(self, test) output = te_output() ((0, test, output, '')) if ity > 1: ('ok ') (str(test)) ('n') else: ('.') def addError(self, test, err): _count += 1 or(self, test, err) _, _exc_str = [-1] output = te_output() ((2, test, output, _exc_str)) if ity > 1: ('E ') (str(test)) ('n') else: ('E') def addFailure(self, test, err): e_count += 1 lure(self, test, err) _, _exc_str = es[-1] output = te_output() ((1, test, output, _exc_str)) if ity > 1: ('F ') (str(test)) ('n') else: ('F')class HTMLTestRunner(Template_mixin): """ """ def __init__(self, stream=, verbosity=1, title=None, description=None): = stream ity = verbosity if title is None: = T_TITLE else: = title if description is None: ption = T_DESCRIPTION else: ption = description ime = () def run(self, test): "Run the given test case or test suite." result = _TestResult(ity) test(result) me = () teReport(test, result) print('nTime Elapsed: %s' % (me - ime), file=) return result def sortResult(self, result_list): # unittest does not seems to run in any particular order. # Here at least we want to group them together by class. rmap = {} classes = [] for n, t, o, e in result_list: cls = t.__class__ if not cls in rmap: rmap[cls] = [] (cls) rmap[cls].append((n, t, o, e)) r = [(cls, rmap[cls]) for cls in classes] return r def getReportAttributes(self, result): """ Return report attributes as a list of (name, value). Override this to add custom attributes. """ startTime = str(ime)[:19] duration = str(me - ime) status = [] if s_count: ('Pass %s' % s_count) if e_count: ('Failure %s' % e_count) if _count: ('Error %s' % _count) if status: status = ' | '.join(status) else: status = 'none' return [ ('Start Time', startTime), ('Duration', duration), ('Status', status), ] def generateReport(self, test, result): report_attrs = ortAttributes(result) generator = 'HTMLTestRunner %s' % __version__ stylesheet = self._generate_stylesheet() heading = self._generate_heading(report_attrs) report = self._generate_report(result) ending = self._generate_ending() output = _TMPL % dict( title=(), generator=generator, stylesheet=stylesheet, heading=heading, report=report, ending=ending, ) (('utf8')) def _generate_stylesheet(self): return HEET_TMPL def _generate_heading(self, report_attrs): a_lines = [] for name, value in report_attrs: line = G_ATTRIBUTE_TMPL % dict( name=(name), value=(value), ) a_(line) heading = G_TMPL % dict( title=(), parameters=''.join(a_lines), description=(ption), ) return heading def _generate_report(self, result): rows = [] sortedResult = sult() for cid, (cls, cls_results) in enumerate(sortedResult): # subtotal for a class np = nf = ne = 0 for n, t, o, e in cls_results: if n == 0: np += 1 elif n == 1: nf += 1 else: ne += 1 # format class description if cls.__module__ == "__main__": name = cls.__name__ else: name = "%s.%s" % (cls.__module__, cls.__name__) doc = cls.__doc__ and cls.__doc__.split("n")[0] or "" desc = doc and '%s: %s' % (name, doc) or name description = cls_results[0][1].case_name row = _CLASS_TMPL % dict( style=ne > 0 and 'errorClass' or nf > 0 and 'failClass' or 'passClass', desc=desc, description=description, count=np + nf + ne, Pass=np, fail=nf, error=ne, cid='c%s' % (cid + 1), ) (row) for tid, (n, t, o, e) in enumerate(cls_results): self._generate_report_test(rows, cid, tid, n, t, o, e) report = _TMPL % dict( test_list=''.join(rows), count=str(s_count + e_count + _count), Pass=str(s_count), fail=str(e_count), error=str(_count), ) return report def _generate_report_test(self, rows, cid, tid, n, t, o, e): # e.g. 'pt1.1', 'ft1.1', etc has_output = bool(o or e) tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid + 1, tid + 1) name = ().split('.')[-1] doc = escription() or "" desc = doc and ('%s: %s' % (name, doc)) or name tmpl = has_output and _TEST_WITH_OUTPUT_TMPL or _TEST_NO_OUTPUT_TMPL # o and e should be byte string because they are collected from stdout and stderr? if isinstance(o, str): # TODO: some problem with 'string_escape': it escape n and mess up formating # uo = unicode(('string_escape')) uo = o else: uo = o if isinstance(e, str): # TODO: some problem with 'string_escape': it escape n and mess up formating # ue = unicode(('string_escape')) ue = e else: ue = e script = _TEST_OUTPUT_TMPL % dict( id=tid, output=(uo + ue), ) row = tmpl % dict( tid=tid, tid=tid, Class=(n == 0 and 'hiddenRow' or 'none'), style=n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'none'), desc=desc, script=script, status=[n], ) (row) if not has_output: return def _generate_ending(self): return _TMPL############################################################################### Facilities for running tests from the command line############################################################################### Note: Reuse ogram to launch test. In the future we may# build our own launcher to support more specific command line# parameters like test title, CSS, TestProgram(ogram): """ A variation of the ogram. Please refer to the base class for command line parameters. """ def runTests(self): # Pick HTMLTestRunner as the default test runner. # base class's testRunner parameter is not useful because it means # we have to instantiate HTMLTestRunner before we know ity. if nner is None: nner = HTMLTestRunner(verbosity=ity) ts(self)main = TestProgram############################################################################### Executing this module from the command line##############################################################################if __name__ == "__main__": main(module=None)7、配置读取测试⽤例的基类⼀个接⼝传参可能有很多,设计测试⽤例的时候我们考虑会很多 正常的 不正常的 等等class ReadExcel(): def get_xls(self,xls_name,sheet_name): cls = [] #拼接⽂件路径 xlsPath = (basepath,'test_file','case',xls_name) #打开⽂件 file = open_workbook(xlsPath) #获取sheet 也就是 ⽂件的 sheet名字 sheet = _by_name(sheet_name) #获取⾏数 nrows = for i in range(nrows): if _values(i)[0] != u'case_name': #获取整⾏ 整列的值 返回必须是数字 所以上⾯有空的 cls数组 (_values(i)) return cls贴上测试⽤的excel代码中的 sheet 指的就是 excel中的 login8、编写配置⽂件我们创建⼀个新⽂件夹 创建 ⽂件 格式如下9、编写项⽬路径基类import osdef get_basepath(): #获取⽂件路径 basepath = (th(__file__))[0] return basepath10、编写测试类login_xls = cel().get_xls("","login")url = nfig().get_http("loginurl")@trized(*login_xls)class testUserLogin(se): def setParameters(self,case_name,path,data,method): _name = str(case_name) = str(path) = str(data) = str(method) def description(self): _name def setUp(self): print(_name + "测试开始前准备") #调⽤测试⽅法 def testLogin(self): esult() def tearDown(self): print("测试结束,输出log完结nn") def checkResult(self): #将读取到的 data 转为 json格式 data = () #调⽤ configHTTP 类中的run_main⽅法 info = RunMain().run_main(,url+,data) #将得到的返回值进⾏格式化并取值判断 print(info) res = (info) if _name == "login": Equal(res['code'],200) if _name == "login_error": Equal(res['code'],404) Equal(res['msg'], '密码错误') if _name == "login_null": Equal(res['code'],404)因为接⼝定义只接受json格式的参数 所以我们在读取到excel中数据的时候 需要将其转换为json格式data = ()调⽤ configHTTP类中的 RunMain()⽅法 返回值就是 接⼝的返回值 我们处理返回值就可以得到我们想要的数据例如 脚本中Equal(res['code'],200)将返回值中的code 与 200 ⽐较看看是否相等,如果不相等则结果错误查看⽇志setUp() ⽅法让我们可以在测试开始之前进⾏数据的准备testLogin()就是我们测试的主⽅法tearDown()测试结束之后执⾏的放我们所有的打印类容都可以在⽹页中查看11、编写总运⾏发放import osimport stRunner as HTMLTestRunnerimport Email as configEmailimport nfig as readConfigimport getPathimport unittestbasepath = _basepath()report_path = (basepath,'result')class AllTest: def __init__(self): global resultPath resultPath = (report_path,'') stFile = (basepath,'test_') le = (basepath,'test_case') st = [] def set_case_list(self): """ 读取⽂件中的⽤例名称,并添加到caselist元素组 :return: """ fb = open(stFile) for value in nes(): data = str(value) # 如果data⾮空且不以#开头 if data != '' and not with('#'): # 读取每⾏数据会将换⾏转换为n,去掉每⾏数据中的n (e("n","")) () def set_case_suite(self): # 通过set_case_list()拿到caselist元素组 _case_list() test_suite = ite() suite_module = [] # 从caselist元素组中循环取出case for case in st: # 通过split函数来将user/login_case分割字符串,-1取后⾯,0取前⾯ case_name = ("/")[-1] # 打印出取出来的名称 print(case_name+'.py') # 批量加载⽤例,第⼀个参数为⽤例存放路径,第⼀个参数为路径⽂件名 参考这个 /happyuu/article/details/80683161 discover = er(le, pattern=case_name+'.py',top_level_dir=None) # 将discover存⼊suite_module元素 suite_(discover) # 判断suite_module元素组是否存在元素 if len(suite_module)>0: # 如果存在,循环取出元素组内容,命名为suite for suite in suite_module: # 从discover中取出test_name,使⽤addTest添加到测试集 for test_name in suite: test_t(test_name) else: return None return test_suite def run(self): try: # 调⽤set_case_suite获取test_suite suit = _case_suite() # 判断test_suite是否为空 if suit is not None: # 打开result/测试报告⽂件,如果不存在就创建 fp = open(resultPath,'wb') # 调⽤HTMLTestRunner 这个⽂件不⽤管 ⽹上有可以直接下载的 runner = stRunner(stream=fp,title="测试报告",description="测试说明") (suit) else: print("没有案例可以测试") finally: on_off = nfig().get_email('on_off') if on_off =='on': ().send_email() elif on_off == 'off': print('发送邮件已关闭') ()if __name__=="__main__": AllTest().run()这⾥需要编写⼀个caselist ⽤于存放该类需要运⾏那些 测试⽤例 不需要运⾏的我们可以注释起来最后为⼤家献上 所有源码 仅供参考 ps:有些功能还没写完~

发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1688022590a67579.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信