当前位置:网站首页>Interface automation test, complete introduction
Interface automation test, complete introduction
2022-07-28 03:40:00 【Test kid】
1. What is interface testing
seeing the name of a thing one thinks of its function , Interface test is to test the interface between systems or components , Mainly the exchange of verification data , Transfer and control the management process , And logical interdependence . The interface protocol is divided into HTTP,WebService,Dubbo,Thrift,Socket Other types , Test types are mainly divided into functional tests , Performance testing , Stability test , Security test, etc .
In the of layered testing “ The pyramid ” In the model , The interface test belongs to the second level service integration test . comparison UI layer ( Mainly WEB or APP) For automated testing , The benefits of interface automation testing are greater , And easy to achieve , Low maintenance cost , Has a higher input-output ratio , Automated testing is preferred by every company .
Let 's take one HTTP Interface, for example , Completely introduce the interface automation test process : From requirements analysis to use case design , From scripting 、 Test execution to result analysis , And provide complete use case design and test script .

2. The basic flow
The basic interface function automation test process is as follows :
Demand analysis -> Use case design -> Script development -> The test execution -> Result analysis
3. Demand analysis
Requirement analysis is a reference requirement 、 Design and other documents , On the basis of understanding the requirements, you also need to know the internal implementation logic , And you can put forward requirements at this stage 、 Unreasonable or omission in the design .
Such as : Douban movie search interface , I understand that the need is to support the film title , Search for cast and tags , And paged back search results .
4. Use case design
Use case design is based on understanding interface test requirements , Use MindManager or XMind Such as mind mapping software to write test case design , The main contents include parameter verification , Functional verification 、 Business scenario verification 、 Safety and performance verification, etc , The commonly used use case design methods are equivalence class partition method , Boundary value analysis , Scenario analysis , Cause and effect diagram , Orthogonal table, etc .
For Douban movie search interface function test part , We mainly focus on parameter verification , Functional verification , Three aspects of business scenario verification , The design test cases are as follows :

5. Script development
According to the test case design written above , We use python+nosetests The framework compiles relevant automated test scripts . It can completely realize the automatic test of interface 、 Automatic execution and e-mail sending test report function .
5.1 relevant lib install
Necessary lib Here's the library , Use pip Command installation :
pip install nose
pip install nose-html-reporting
pip install requests5.2 Interface call
Use requests library , We can easily write the above interface call methods ( Search engine q= Lau Andy , The sample code is as follows ):
#coding=utf-8
import requests
import json
url = 'https://api.douban.com/v2/movie/search'
params=dict(q=u' Lau Andy ')
r = requests.get(url, params=params)
print 'Search Params:\n', json.dumps(params, ensure_ascii=False)
print 'Search Response:\n', json.dumps(r.json(), ensure_ascii=False, indent=4)When actually writing automated test scripts , We need some encapsulation . In the following code, we encapsulate the Douban movie search interface ,test_q The method only needs to use nosetests Provided yield Method can easily loop through the execution list qs Every test set in :
class test_doubanSearch(object):
@staticmethod
def search(params, expectNum=None):
url = 'https://api.douban.com/v2/movie/search'
r = requests.get(url, params=params)
print 'Search Params:\n', json.dumps(params, ensure_ascii=False)
print 'Search Response:\n', json.dumps(r.json(), ensure_ascii=False, indent=4)
def test_q(self):
# Verify search criteria q
qs = [u' Chasing murderers in the daytime and night ', u' A Chinese Odyssey ', u' Stephen Chow ', u' Zhang Yimou ', u' Stephen Chow , headmaster ', u' Zhang Yimou , Gong Li ', u' Stephen Chow , A Chinese Odyssey ', u' Chasing murderers in the daytime and night , Pan Yueming ']
for q in qs:
params = dict(q=q)
f = partial(test_doubanSearch.search, params)
f.description = json.dumps(params, ensure_ascii=False).encode('utf-8')
yield (f,)We design according to test cases , Write the automatic test script of each function in turn .
5.3 Result verification
When testing the interface manually , We need to judge whether the test passes or not through the results returned by the interface , So is automated testing .
For this interface , We search “q= Lau Andy ”, We need to determine whether the returned result contains “ Actor Andy Lau or film title Andy Lau ”, Search for “tag= comedy ” when , You need to determine whether the movie type in the returned result is “ comedy ”, When paging results, you need to check whether the number of returned results is correct, etc . The complete result verification code is as follows :
class check_response():
@staticmethod
def check_result(response, params, expectNum=None):
# Because the search results have fuzzy matching , The simple process here only verifies the correctness of the first returned result
if expectNum is not None:
# The number of expected results is not None when , Only judge the number of returned results
eq_(expectNum, len(response['subjects']), '{0}!={1}'.format(expectNum, len(response['subjects'])))
else:
if not response['subjects']:
# The result is empty. , Direct return failure
assert False
else:
# The result is not empty , Verify the first result
subject = response['subjects'][0]
# Check the search criteria first tag
if params.get('tag'):
for word in params['tag'].split(','):
genres = subject['genres']
ok_(word in genres, 'Check {0} failed!'.format(word.encode('utf-8')))
# Then verify the search criteria q
elif params.get('q'):
# Judge the title in turn , Whether the director or actor contains search words , If any one contains, success will be returned
for word in params['q'].split(','):
title = [subject['title']]
casts = [i['name'] for i in subject['casts']]
directors = [i['name'] for i in subject['directors']]
total = title + casts + directors
ok_(any(word.lower() in i.lower() for i in total),
'Check {0} failed!'.format(word.encode('utf-8')))
@staticmethod
def check_pageSize(response):
# Determine whether the number of paging results is correct
count = response.get('count')
start = response.get('start')
total = response.get('total')
diff = total - start
if diff >= count:
expectPageSize = count
elif count > diff > 0:
expectPageSize = diff
else:
expectPageSize = 0
eq_(expectPageSize, len(response['subjects']), '{0}!={1}'.format(expectPageSize, len(response['subjects'])))5.4 Perform the test
For the above test script , We use nosetests Command can easily run automated tests , And can use nose-html-reporting Plug in generation html Format test report .
Run the command as follows :
nosetests -v test_doubanSearch.py:test_doubanSearch --with-html --html-report=TestReport.html5.5 Send email reports
Once the test is complete , We can use smtplib The method provided by the module sends html Format test report . The basic process is to read the test report -> Add email content and attachments -> Connect to the mail server -> Send E-mail -> sign out , The sample code is as follows :
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_mail():
# Read the contents of the test report
with open(report_file, 'r') as f:
content = f.read().decode('utf-8')
msg = MIMEMultipart('mixed')
# Add email content
msg_html = MIMEText(content, 'html', 'utf-8')
msg.attach(msg_html)
# Add attachments
msg_attachment = MIMEText(content, 'html', 'utf-8')
msg_attachment["Content-Disposition"] = 'attachment; filename="{0}"'.format(report_file)
msg.attach(msg_attachment)
msg['Subject'] = mail_subjet
msg['From'] = mail_user
msg['To'] = ';'.join(mail_to)
try:
# Connect to the mail server
s = smtplib.SMTP(mail_host, 25)
# land
s.login(mail_user, mail_pwd)
# Send E-mail
s.sendmail(mail_user, mail_to, msg.as_string())
# sign out
s.quit()
except Exception as e:
print "Exceptioin ", e6. Result analysis
open nosetests Test report generated after running , It can be seen that a total of 51 Test cases ,50 Article success ,1 Article failed .

For the failed use case, you can see that the passed in parameter is :{"count": -10, "tag": " comedy "}, At this time, the number of returned results is inconsistent with our expected results (count When it's negative , The expected result is that the interface reports an error or uses the default value 20, But the actual number of results returned is 189.)

7. Full script
Once the download is complete , Complete interface automation test can be carried out by using the following commands, and the final test report can be sent by mail :
python test_doubanSearch.pyFinally, in my QQ The technical exchange group sorted out my 10 Some technical data sorted out by software testing career in recent years , Include : e-book , Resume module , Various work templates , Interview treasure , Self study projects, etc . If you encounter problems in your study or work , There will also be great gods in the group to help solve , Group number 798478386 ( remarks CSDN555 )
Full set of software test automation test teaching video

300G Download tutorial materials 【 Video tutorial +PPT+ Project source code 】

A complete set of software testing automation testing factory has been

边栏推荐
- [openvx] VX for basic use of objects_ convolution
- 一篇文章掌握Postgresql中对于日期类数据的计算和处理
- Asemi rectifier bridge gbpc5010, gbpc5010 parameters, gbpc5010 size
- verticle-align行内元素垂直居中对齐
- BRD,MRD,PRD的区别
- 【OPENVX】对象基本使用之vx_matrix
- 接口自动化测试,完整入门篇
- How does win11 display fixed applications?
- 构建“产业大脑”,以“数字化”提升园区运营管理及服务能力!
- 某宝模拟登录,减少二次验证的方法
猜你喜欢

Outlook tutorial, how to use color categories and reminders in outlook?

接口自动化测试,完整入门篇

ASEMI整流桥GBPC3510在直流有刷电机中的妙用

20220727 use the Bluetooth module hc-05 of Huicheng technology to pair mobile phones for Bluetooth serial port demonstration

ES6 from getting started to mastering 08: extended object functions
![2022-07-27: Xiao Hong got an array arr with a length of N. she is going to modify it only once. She can modify any number arr[i] in the array to a positive number not greater than P (the modified numb](/img/24/fbf63272f83b932e0ee953f8d4db75.png)
2022-07-27: Xiao Hong got an array arr with a length of N. she is going to modify it only once. She can modify any number arr[i] in the array to a positive number not greater than P (the modified numb

Illustrated: detailed explanation of JVM memory layout

MySQL Basics (create, manage, add, delete, and modify tables)

In December, the PMP Exam adopted the new syllabus for the first time. How to learn?

SAP UI5 FileUploader 控件深入介绍 - 为什么需要一个隐藏的 iframe 试读版
随机推荐
C language to achieve a dynamic version of the address book
LabVIEW loads and uses custom symbols in tree control projects
Assembly method of golang Gorm query arbitrary fields
收藏|0 基础开源数据可视化平台 FlyFish 大屏开发指南
[openvx] VX for basic use of objects_ matrix
Outlook 教程,如何在 Outlook 中使用颜色类别和提醒?
一篇文章掌握Postgresql中对于日期类数据的计算和处理
【OPENVX】对象基本使用之vx_matrix
什么是Tor?Tor浏览器更新有什么用?
Swift中的协议
单调栈——739. 每日温度
动态规划——509. 斐波那契数
Super nice PHP program source code of nteam official website
动态规划——1049. 最后一块石头的重量 II
Use of custom annotations
Play WolframAlpha computing knowledge engine
What is tor? What is the use of tor browser update?
MangoPapa 的实用小脚本(目录篇)
Golang gets the tag of the loop nested structure
20220727 use the Bluetooth module hc-05 of Huicheng technology to pair mobile phones for Bluetooth serial port demonstration