Project background:
The XXXX bank project adopts a B/S structure, mainly to solve the management of tellers, vouchers, cash, accounts, etc. from the deposit, loan, and accounting modules in banking business.
Manual Disadvantages:
1. The project business complexity is high and the regression testing workload is heavy
2. The function of a single interface is relatively simple, easy to realize automatic integration, and is more stable than the UI, and can better achieve the purpose of monitoring project quality.
3. From the perspective of front-end and back-end separation, relying solely on front-end restrictions cannot meet security requirements.
Optimization solutions and tool selection:
Postman:
Powerful Chrome plug-in, beautiful interface and free choice of response format. The disadvantages are that it supports a single protocol and cannot separate data. What’s more troublesome is that not all companies can access Google.
SoupUI:
It is an open source interface testing tool that supports multiple protocols (http\soup\rest, etc.) and can implement functional and performance testing. It is highly flexible and scripts can be developed on this basis. The disadvantage is that it is difficult to get started.
Jmeter:
The interface stress testing tool used by Java is a bit overkill for interface function testing. The disadvantage is that it cannot generate a visual interface test report.
To sum up: manual development is more suitable
Framework Principle:
Adopt the data-driven model to separate data and business logic to complete the purpose of writing test cases – “test case execution -” sending test reports
The test case format is written as follows:
Code implementation:
Note: For data desensitization, take Baidu translation interface as an example
1. Read the test case data data.py
# coding=utf-8 import json import xlrd importsys reload(sys) sys.setdefaultencoding('utf-8') def tableToJson(): source = xlrd.open_workbook(r"C:\Users\HP\Desktop\0608\InterfaceData.xlsx") table = source.sheet_by_index(0) list = [] # Dictionary list totalList = [] # json list for i in xrange(1,2): #Get the value from row 2 of the i-th table as a parameter of the use case keys = table.col_values(1) # Get the value of column 2 of the i-th table keys.pop(0) for j in xrange(3, table.ncols): test_value = table.col_values(j) # Get the value from column 4 of the i-th table as the parameter value of the use case test_value.pop(0) for k in range(len(test_value)): s = test_value[k] # prints data = dict(zip(keys, test_value)) # Convert two lists of equal length into dictionaries list.append(data) data = {} data[table.name] = list list = [] data_to_json = json.dumps(data, ensure_ascii=False, encoding="gb2312") # Convert the unicode in the list to Chinese print u"Use case data:", data_to_json totalList.append(data_to_json) return totalList if __name__ == '__main__': jsonData = tableToJson() #Write to file f = open(r"F:\TestData0618.json", 'w + ') for i in jsonData: f.write(i) f.write('\\ ') f.close()
operation result:
2. Execute the test case test.py
#coding=utf-8 import requests import unittest import json class MyTest(unittest.TestCase): # Class that encapsulates the initialization and restoration of the test environment def setUp(self): print("start test") def tearDown(self): print("end test") class Test_transapi(MyTest): # An interface encapsulates a class @staticmethod def getParams(): Data = open(r"F:\TestData0618.json").read() temp = eval(Data) #type(Data) is str, type(temp) is dict data = temp['2100'] return data def test_transapi(self): self.url = "http://fanyi.baidu.com/v2transapi" self.headers = { 'Host': 'fanyi.baidu.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36', 'Accept': 'text/html,application/xhtml + xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'zh-CN,zh;q=0.8', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive'} data = self.getParams() for i in data: print i self.params = i #print u'parameters:',self.params r = requests.get(url=self.url, params=self.params,headers=self.headers) #print(r.text) print(r.status_code) self.assertEqual(200,r.status_code) if __name__=="__main__": unittest.main()
operation result:
3. Build the test report run.py
#coding=utf-8 from HTMLTestRunner import HTMLTestRunner import time import unittest #Define the test case directory as the current directory test_dir = r'C:\Users\HP\Desktop\0608' discover = unittest.defaultTestLoader.discover(test_dir,pattern = 'test*.py') if __name__=="__main__": #Get the current time in a certain format now = time.strftime("%Y-%m-%d %H-%M-%S") #Define report storage path filename =test_dir + '/' + now + 'test_result.html' fp = open(filename,"wb") #Define test report runner = HTMLTestRunner(stream = fp, title = u"2100 interface test report", description = u"Test case execution:") #Run test runner.run(discover) fp.close() #Close the report file
operation result:
4.Send test report send.py
-
#coding=utf-8 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def SendMail(subject,msg,to_addrs,from_addr,smtp_addr,password): ''' @subject: email subject @msg: Email content @to_addrs: Recipient’s email address @from_addr: The email address of the sender @smtp_addr: smtp service address, which can be viewed in the mailbox. For example, the 163 mailbox is smtp.163.com @password: sender’s email password ''' mail_msg = MIMEMultipart() #Create an instance with attachments #Construct attachment test.docx att1 = MIMEText(open(r'C:\Users\HP\Desktop\0608\2017-06-18 22-33-24test_result.html','rb').read() , 'base64', 'gb2312') att1["Content-Type"] = 'application/octet-stream' att1.add_header('Content-Disposition', 'attachment', filename=u'Test report.html'.encode('gbk')) mail_msg.attach(att1) #Build MIMEText plain text content txt = MIMEText(msg,'plain', 'utf-8') mail_msg.attach(txt) mail_msg['Subject'] = subject mail_msg['From'] =from_addr mail_msg['To'] = ','.join(to_addrs) try: s = smtplib.SMTP() s.connect(smtp_addr) #Connect to smtp server s.login(from_addr,password) #Log in to email s.sendmail(from_addr, to_addrs, mail_msg.as_string()) #Send mail s.quit() print "success" exceptException,e: print str(e) if __name__ == '__main__': from_addr = "XXX" smtp_addr = "XXX" to_addrs = ["XXX"] subject = "send test" password = "XXX" msg = "hello,this is just a send test" SendMail(subject,msg,to_addrs,from_addr,smtp_addr,password)
operation result:
5. Execute test cases regularly
Issues and Challenges:
1. The interface document is not updated in a timely manner, resulting in use case data that may be different from what is actually needed. It is recommended to use the SwaggerUI tool to manage interface test documents
2. Before executing most use cases, you need to ensure that you are logged in for security reasons. Simply adding cookies to the request header does not work. Use session.
3. The test report uses the universal version (one script, one record). In the current situation, if all use cases under an interface are written in one script, there will only be one record.
4. The Chinese attachment name of the email is garbled
Thank you to everyone who read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, if you can use it, you can take it directly:
This information should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can also help you!Yes Friends who need it can click on the small card below to get it