An example of interface test framework based on Python _python

Source: Internet
Author: User

Background

Recently, the company is doing message push, so naturally there will be many interfaces, testing process needs to call the interface, I suddenly feel that I can write a test framework?

Say dry, because the existing interface testing tools JMeter, SOUPUI, such as learning cycle a bit long, simply write a bar, do not ask for help, all functions can be clear.

Of course, writing tools to build wheels is just a way to learn, ready-made tools are certainly more useful than our own writing.

Development environment

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

Operating system: Mac OS X EI Caption

Python version: 2.7

Ide:pycharm

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

Analysis

The interface is based on the HTTP protocol, so it would be easy to just launch an HTTP request, which is a piece of cake for Python. It's easy to get the job done directly using requests.

Architecture

The whole frame is relatively small, the things involved are relatively few, as long as the separation of the functions of several modules on the line.

Above is a complete flow of interface testing. It's not hard to just walk down the road one step at a time.

Data source

The data source I'm using JSON to save, of course, the more extensive use of Excel to save, with JSON to save because JSON is easy to use, lazy to read Excel, Python support for JSON is very friendly. Of course, this depends on a person's preference.

{
  "TestID": "testcase004", "Method
  ": "Post",
  "Title": "Push messages individually",
  "Desc": "Push messages individually",
  "URL": "http ://xxx.xxx.xxx.xx ",
  " Inputarg ": {
   " action ":" 44803 ",
   " account ":" 1865998xxxx ",
   " UniqueID ":" 00d7c889-06a0-426e-bab1-5741a1192038 ",
   " title ":" Test Test ",
   " summary ":" Peas "," Message
   ":" 12345 ",
   "Msgtype": "MenuID": "
   203"
  },
  "result": {
   "Errorno": "0"
  }
 }

As shown in the above code, it can be adjusted according to the business needs of the individual.

Send Request

Sending a request is simple, using the requests module, and then reading the sent parameters from JSON, post, get, or other. As the test report is to be generated, the data sent needs to be recorded and I choose to use txt text as the container for the record.

f = File ("Case.json")
TestData = Json.load (f)
F.close ()


def senddata (TestData, num):
  payload = {}
  # Get send parameters 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

Since we need to generate test reports, we need to store the returned data first, we can choose to use the database storage, but I think the database storage is too cumbersome, as long as the use of txt text as a storage container.

With open (' Rightside.txt ', ' A + ') as RS:
    rs.write (' send data ')
    rs.write (' | '
    ) Rs.write (' caption: ' +testdata[num][' title ')]
    rs.write (' | ')
    Rs.write (' Send way: ' +testdata[num][' method '])
    rs.write (' | ')
    Rs.write (' Case description: ' +testdata[num][' Desc '])
    rs.write (' | ')
    Rs.write (' Send address: ' +testdata[num][' Url '])
    rs.write (' | ')
    Rs.write (' Send parameters: ' +str (payload). Decode ("Unicode-escape"). Encode ("Utf-8"). Replace ("u\", "\"))
    rs.write (' | ')
    Rs.write (testdata[num][' TestID '])
    rs.write (' \ n ')

Result determination

The result is that I'm using all equal judgment. Because our interface only needs to be handled this way, if necessary, can be written as a regular decision.

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 Results
    try:
      if CMP (r, testdata[num][' result ']) = = 0:
        rst.write (' pass ')
      else:
        rst.write (' Fail ')
    except Exception:
      rst.write (' No except result ')
    rst.write (' \ n ')

I have 3 kinds of results here, success, failure or no result. The setting of the result depends on your definition.

Generate Test Report

Test report is a play, because I send data, return data and results are in txt text storage, then each use a + mode new, will make the result more and more, and check up very egg pain.

My approach is to use Python to read the data in txt text after each test, and then use Django to dynamically generate a result, and then use requests to crawl the page and save it in the file folder.

Web page report

I'm not going to tell you the Django method, there's already a whole series of articles on the blog. We need to open in the views file before the record of the 3 TXT file, and then do some data processing, return to the front end with bootstrap to render, you can generate a more 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[l En (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 (rig Htside, result): data = {"SendData": A, "dealdata": B, "result": B[len (b)-1]} Rst_data.app End (data) return render (Request, ' porttest/index.html ', {"leftside": Leftside, "Rst_data": rst _data, "pass": Passed, "fail": Fail, "Noresu LT ": Noresult})

Basically are some very basic knowledge, string segmentation and so on. Here the data processing for convenience, in the acquisition of data storage must be in accordance with a certain format to store, views of the method is very easy to do processing.

The front end code is as follows:

<! DOCTYPE html>  

Test Report Effect Chart

At last

Writing a tool in Python is easy, but it is more convenient to meet the needs of the actual work. If you want to do a complete interface test, or try to use the mature tools.

PS: Simple wheel making is also an excellent way to learn the principles.

The above example is based on the Python interface test framework examples are small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

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.