Python self-Study code optimization 2

Source: Internet
Author: User

The code of the interface test is encapsulated in different modules, but the use of classes, classes and properties is still being learned.
imptestcase.py

1 #Coding:utf-82 Importxlrd3 """import testcase from Excel"""4 classImptestcase (object):5     6     def __init__(self):7         Pass8         9     defimportcase (self):Tennrows =0 OneRdict = {}#Store Request Parameters AReturnres = {} -FName ='testcase.xlsx' -Sheet_name='case1' theBK =Xlrd.open_workbook (fname) -         Try: -Sheet =bk.sheet_by_name (sheet_name) -         except: +             Print("no sheet in%s named Sheet1"%fname) -       +nrows =sheet.nrows ANcols =Sheet.ncols at          forIinchRange (0,ncols): -data =sheet.col_values (i) -Rdict[data[0]]=data[1:] -          -returnres['nrows']=nrows -returnres['rdict']=rdict in         returnReturnres

sendreq.py

#Coding:utf-8ImportRequests fromImptestcaseImportImptestcase"""Send requestsresponse = requests.post (Url,json = data,headers = Headers,verify=false)"""classSendreq (object):def __init__(self,nrows,rdict): Self.nrows=nrows self.rdict=rdictdefSendRequest (self): relist= []         forIinchRange (0,self.nrows-1): URL= self.rdict['URL'][i]ifself.rdict['Headers'][i]!="': Headers= eval (self.rdict['Headers'][i])#str to dict            Else: Headers= {}                 ifself.rdict['JSON'][i]!="': JSON= self.rdict['JSON'][i]#str to dict            Else: JSON= {}            ifself.rdict['params'][i]!="': Params= eval (self.rdict['params'][i])#str to dict            Else: Params= {}                        Try:                ifself.rdict['Method']=='Get': R= Requests.get (url,headers = Headers,params = params,verify=False)Else: R= Requests.post (Url,json = Json,headers = headers,verify=False) r.raise_for_status () r.encoding=r.apparent_encoding Relist.append ('Casename:'+self.rdict['Casename'][i]) relist.append ('Status:'+str (r.status_code)) Relist.append ('Date:'+r.headers['Date'])                             exceptException as E:Print(e)Print('fail') relist.append (str (e))returnRelist

outputresult.py

#Coding:utf-8 fromSendreqImportSendreq"""XXX"""classOutputresult (object):def __init__(self,relist): Self.relist=relistdefoutput (self): Fout=open ('output.html','W', encoding='UTF-8', newline="') Fout.write ('') Fout.write ('') Fout.write ('<meta charset = "UTF-8"/>') Fout.write ('') Fout.write ('<body>') Fout.write ('') Fout.write ('<table>') Fout.write ('<tr>')        #fout.write (' <td>%s</td> '% relist)         forIinchRange (0,len (self.relist)): Fout.write ('<td>%s</td>'%Self.relist[i]) fout.write ('</tr>') Fout.write ('</table>') Fout.write ('</body>') Fout.write ('') Fout.close ()

main.py

#Coding:utf-8 fromImptestcaseImportImptestcase fromSendreqImportSendreq fromOutputresultImportOutputresultdefMainrun (): TC=imptestcase () re=tc.importcase () Send= Sendreq (re['nrows'],re['rdict']). SendRequest ()Print(send) out=outputresult (send) Out.output () Mainrun ()

The next plan is:
1. Learn the knowledge of OOP such as modules, classes, examples, etc.

2. Use the knowledge to further optimize the code;

3. Write and manage code using PYCHARM.

Python self-Study code optimization 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.