Python-based interface testing framework example
Background
Recently, the company is doing message push, so naturally many interfaces will be generated. During the test process, the interface needs to be called. I suddenly thought if I could do it myself Write a testing framework?
Just do it. Since the existing interface testing tools Jmeter, SoupUI and other learning cycles are a bit long, you might as well write one yourself. You don’t need anyone else, and you can know all the functions clearly.
Of course, writing tools and making wheels is just a way of learning. Ready-made and mature tools are definitely easier to use than those we write ourselves.
Development environment
------------------------------------------ --------------------------
Operating system: Mac OS X EI Caption
Python version: 2.7
IDE: Pycharm
------------------------------------------------ -------------------------
analyze
The interface is based on the HTTP protocol, so to put it bluntly, just initiate an HTTP request. For Python, it is a piece of cake. You can easily complete the task by using requests directly.
Architecture
The entire framework is relatively small and involves relatively few things. You only need to clearly distinguish the functions of several modules.
#The above is a complete process of interface testing. Just take it step by step, it's not difficult.
Data source
I use JSON to save the data source. Of course, the more common way is to use Excel to save, and use JSON to save it. I saved it because JSON is more convenient to use and I am too lazy to read Excel. Python’s support for JSON is very friendly. Of course, this depends on personal preference.
{ "TestId": "testcase004", "Method": "post", "Title": "单独推送消息", "Desc": "单独推送消息", "Url": "http://xxx.xxx.xxx.xx", "InputArg": { "action": "44803", "account": "1865998xxxx", "uniqueid": "00D7C889-06A0-426E-BAB1-5741A1192038", "title": "测试测试", "summary": "豆豆豆", "message": "12345", "msgtype": "25", "menuid": "203" }, "Result": { "errorno": "0" } }
The example is shown in the code above and can be adjusted according to personal business needs.
Send a request
Sending a request is very simple, use the requests module, and then read the sent parameters from JSON, post, get or other. Since a test report needs to be generated, the data sent needs to be recorded. I chose to use txt text as the recording container.
f = file("case.json") testData = json.load(f) f.close() def sendData(testData, num): payload = {} # 从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') # 发送请求 data = requests.get(testData[num]['Url'], params=payload) r = data.json()
Accept return
Since we need to generate a test report, then return We need to store the data first. We can choose to use a database to store it, but I think database storage is too troublesome. Just use txt text as a storage container.
with open('rightside.txt', 'a+') as rs: rs.write('发送数据') rs.write('|') rs.write('标题:'+testData[num]['Title']) rs.write('|') rs.write('发送方式:'+testData[num]['Method']) rs.write('|') rs.write('案例描述:'+testData[num]['Desc']) rs.write('|') rs.write('发送地址:'+testData[num]['Url']) rs.write('|') rs.write('发送参数:'+str(payload).decode("unicode-escape").encode("utf-8").replace("u\'","\'")) rs.write('|') rs.write(testData[num]['TestId']) rs.write('\n')
Result Determination
The result determination I use is equal to the determination. Because our interface only needs to be processed in this way, if necessary, it can be written as a regular judgment.
with open('result.txt', 'a+') as rst: rst.write('返回数据') rst.write('|') for x, y in r.items(): rst.write(' : '.join([x, y])) rst.write('|') # 写测试结果 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')
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 highlight. Since I send data, return data and results are all stored in txt text, then every time I use a+ mode, it will be new. If it increases, there will be more and more results, and it will be very painful to check.
My way of handling it is to use Python to read the data in the txt text after each test, then use Django to dynamically generate a result, and then use requests to crawl the web page and save it in the Report folder. .
Web Page Report
I won’t go into details about Django’s method, there is already a whole series of articles on the blog. We need to open the three previously recorded txt files in the views file, then do some data processing and return them to the front end. The front end uses Bootstrap to render them to 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[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})
Basically some very basic knowledge, string segmentation and so on. For the convenience of data processing here, when obtaining data storage, it must be stored in a certain format, and the views method is easy to process.
The front-end code is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link href="http://jb51.net/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"> <script src="http://jb51.net/jquery/2.0.0/jquery.min.js"></script> <script src="http://jb51.net/bootstrap/3.0.3/js/bootstrap.min.js"></script> </head> <body> <p class="container"> <p class="row"> <p class="page-header"> <h1>接口测试报告 <small>Design By Sven</small> </h1> </p> </p> <p class="row"> <p class="col-md-4"> <h3 id="测试通过-nbsp-span-nbsp-class-label-nbsp-label-success-nbsp-pass-nbsp-span">测试通过 <span class="label label-success">{{ pass }}</span></h3> </p> <p class="col-md-4"> <h3 id="测试失败-nbsp-span-nbsp-class-label-nbsp-label-danger-nbsp-fail-nbsp-span">测试失败 <span class="label label-danger">{{ fail }}</span></h3> </p> <p class="col-md-4"> <h3 id="无结果-nbsp-span-nbsp-class-label-nbsp-label-warning-nbsp-noresult-nbsp-span">无结果 <span class="label label-warning">{{ noresult }}</span></h3> </p> </p> <p></p> <p class="row"> <p class="col-md-3"> <ul class="list-group"> {% for ls in leftside %} <li class="list-group-item"><a href="#{{ ls.code }}">{{ ls.code }} - {{ ls.title }}</a></li> {% endfor %} </ul> </p> <p class="col-md-9"> {{ x.result }} {% for x in rst_data %} <p class="panel-group" id="accordion"> {% if x.result == 'pass' %} <p class="panel panel-success"> {% elif x.result == 'fail' %} <p class="panel panel-danger"> {% elif x.result == 'no except result' %} <p class="panel panel-warning"> {% endif %} <p class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" href="#{{ x.sendData.testid }}"> {{ x.sendData.testid }} - {{ x.sendData.csbt }} </a> </h4> </p> <p id="{{ x.sendData.testid }}" class="panel-collapse collapse"> <p class="panel-body"> <b>{{ x.sendData.fssj }}</b><br> {{ x.sendData.csbt }}<br> {{ x.sendData.fsfs }}<br> {{ x.sendData.alms }}<br> {{ x.sendData.fsdz }}<br> {{ x.sendData.fscs }} <hr> {% for v in x.dealData %} {{ v }}<br> {% endfor %} </p> </p> </p> </p> <p></p> {% endfor %} </p> </p> </p> <script> $(function () { $(window).scroll(function () { if ($(this).scrollTop() != 0) { $("#toTop").fadeIn(); } else { $("#toTop").fadeOut(); } }); $("body").append("<p id=\"toTop\" style=\"border:1px solid #444;background:#333;color:#fff;text-align:center;padding:10px 13px 7px 13px;position:fixed;bottom:10px;right:10px;cursor:pointer;display:none;font-family:verdana;font-size:22px;\">^</p>"); $("#toTop").click(function () { $("body,html").animate({scrollTop: 0}, 800); }); }); </script> </body> </html>
Test report renderings
Finally
It is easy to write a tool in Python, but the main purpose is to more conveniently meet the needs of actual work. If you want to do a complete interface test, try to use mature tools.
PS: Simply making wheels is also an excellent way to learn the principles.
The above example of the interface testing framework based on Python is all the content shared by the editor. I hope it can give you a reference, and I hope you will support the PHP Chinese website.
For more articles related to Python-based interface testing framework examples, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete
