Python-based interface testing framework instance and python framework instance

Source: Internet
Author: User

Python-based interface testing framework instance and python framework instance

Background

Recently, when the company is pushing messages, many interfaces will naturally be generated. During the test, the interface needs to be called. I suddenly felt that I could write a test framework by myself?

Just do what you need. Because the existing interface testing tools such as Jmeter and SoupUI have a long learning cycle, simply write one by yourself. If you are not looking for anyone, all the functions can be clearly understood by yourself.

Of course, writing tools are just a way of learning. ready-made and mature tools are certainly better than what we write.

Development Environment

-------------------------------------------------------------

Operating System: Mac OS X EI Caption

Python: 2.7

IDE: Pycharm

-------------------------------------------------------------

Analysis

The interface is based on the HTTP protocol. To put it bluntly, it is enough to initiate an HTTP request. For Python, it is simply a piece of cake. Directly Using requests can easily complete the task.

Architecture

The entire framework is relatively small and involves less things. You only need to clarify the functions of several modules.

The above is a complete interface test process. It is not difficult to go down step by step.

Data Source

I use JSON to store data sources. Of course, Excel is widely used to store data sources. JSON is easier to use and I am too lazy to read Excel Data, python supports JSON very well. Of course, this depends on your personal preferences.

{"TestId": "testcase004", "Method": "post", "Title": "Push messages separately", "Desc": "Push messages separately ", "Url": "http://xxx.xxx.xxx.xx", "InputArg": {"action": "44803", "account": "1865998 xxxx", "uniqueid": "00d7c889-06a0-450e-bab1-5741a1192038 ", "title": "test", "summary": "", "message": "12345", "msgtype": "25", "menuid ": "203"}, "Result": {"errorno": "0 "}}

As shown in the code above, you can make adjustments based on your business needs.

Send request

Sending a request is easy. Use the requests module to read the sent parameters, such as post, get, or others from JSON. To generate a test report, you need to record the sent data. I chose to use txt text as the record container.

F = file ("case. json ") testData = json. load (f) f. close () def sendData (testData, num): payload ={}# obtain the sending parameter from json for x in testData [num] ['inputarg ']. items (): payload [x [0] = x [1] with open('leftside.txt ', 'a +') as f: f. write (testData [num] ['testid']) f. write ('-') f. write (testData [num] ['title']) f. write ('\ n') # Send request data = requests. get (testData [num] ['url'], params = payload) r = data. json ()

Accept return

Because we need to generate a test report, we need to store the returned data first. You can choose to store it in a database, but I think it is too troublesome to store the database, you only need to use txt text as the storage container.

With open('rightside.txt ', 'a +') as rs: rs. write ('send data') rs. write ('|') rs. write ('title: '+ testData [num] ['title']) rs. write ('|') rs. write ('sending Method: '+ testData [num] ['method']) rs. write ('|') rs. write ('case Description: '+ testData [num] ['desc']) rs. write ('|') rs. write ('sending address: '+ testData [num] ['url']) rs. write ('|') rs. write ('sending parameter: '+ str (payload ). decode ("unicode-escape "). encode ("UTF-8 "). replace ("u \ '", "\'") rs. write ('|') rs. write (testData [num] ['testid']) rs. write ('\ n ')

Result Determination

The result indicates that all equals are used. This is because our interface only needs to be processed in this way. If necessary, we can write a regular expression.

With open('result.txt ', 'a +') as rst: rst. write ('Return data') rst. write ('|') for x, y in r. items (): rst. write (':'. join ([x, y]) rst. write ('|') # write test Result try: if cmp (r, testData [num] ['result']) = 0: rst. write ('pass') else: rst. write ('fail ') failed t Exception: rst. write ('no such t result') rst. write ('\ n ')

There are three types of results here: Success, failure, or no result. The setting of the result depends on your own definition.

Generate Test report

The test report is a major concern. Because I use txt text to store the data I sent, returned, and returned, each time I use the + mode to add new results, the results will become more and more, and the check will be very painful.

My processing method is to read the data in txt text in Python after each test, then use Django to dynamically generate a result, and then use requests to capture the webpage and save it in the Report folder.

Web reports

I will not talk much about Django's methods. The blog already contains a series of articles. We need to open the three previously recorded txt files in the views file, and then perform some data processing and return them to the front end. The front end uses Bootstrap for rendering to generate a beautiful test report.

def index(request):  rightside = []  result = []  rst_data = []  leftside = []  passed = 0  fail = 0  noresult = 0  with open(os.getcwd() + '/PortTest/leftside.txt') as ls:    for x in ls.readlines():      lf_data = {        'code': x.strip().split('-')[0],        'title': x.strip().split('-')[1]      }      leftside.append(lf_data)  with open(os.getcwd() + '/PortTest/rightside.txt') as rs:    for x in rs.readlines():      row = x.strip().split('|')      rs_data = {        "fssj": row[0],        "csbt": row[1],        "fsfs": row[2],        "alms": row[3],        "fsdz": row[4],        "fscs": row[5],        'testid': row[6]      }      rightside.append(rs_data)  with open(os.getcwd() + '/PortTest/result.txt') as rst:    for x in rst.readlines():      row = x.strip().split('|')      if row[len(row)-1] == 'fail':        fail += 1      elif row[len(row)-1] == 'pass':        passed += 1      elif row[len(row)-1] == 'no except result':        noresult += 1      rs_data = []      for y in row:        rs_data.append(y)      result.append(rs_data)  for a, b in zip(rightside, result):    data = {      "sendData": a,      "dealData": b,      "result": b[len(b)-1]    }    rst_data.append(data)  return render(request, 'PortTest/index.html', {"leftside": leftside,                          "rst_data": rst_data,                          "pass": passed,                          "fail": fail,                          "noresult": noresult})

It is basically basic knowledge, string segmentation, and so on. For convenience of data processing, data storage is stored in a certain format, and the views method is easy to process.

The front-end code is as follows:

<! DOCTYPE html> 

Test report

Last

It is easy to write a tool using Python. It is mainly intended to meet the actual usage needs. If you want to perform a complete Interface Test, try to use mature tools.

PS: simple wheel building is also an excellent way to learn the principle.

The above example of the Python-based interface testing framework is all the content that I have shared with you. I hope to give you a reference and support for the help house.

Related Article

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.