当前位置:网站首页>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

边栏推荐
- [wrong question]mocha and railgun
- ASEMI整流桥GBPC3510在直流有刷电机中的妙用
- Tungsten Fabric SDN — BGP as a Service
- 【论文笔记】基于深度学习的移动机器人自主导航实验平台
- Responsive high-end website template source code Gallery material resource download platform source code
- ASEMI整流桥GBPC5010,GBPC5010参数,GBPC5010大小
- MSGAN用于多种图像合成的模式搜索生成对抗网络---解决模式崩塌问题
- 一篇文章掌握Postgresql中对于日期类数据的计算和处理
- Xctf attack and defense world web master advanced area unserialize3
- Swift中的协议
猜你喜欢
D2dengine edible tutorial (4) -- draw text

The open source of "avoiding disease and avoiding medicine" will not go far

高等数学(第七版)同济大学 习题3-4 个人解答(前8题)

BRD,MRD,PRD的区别

20220726汇承科技的蓝牙模块HC-05的AT命令测试

53. Maximum subarray maximum subarray sum

收藏|0 基础开源数据可视化平台 FlyFish 大屏开发指南

695. Maximum area of the island

Tensorboard usage record

20220726 at command test of Bluetooth module hc-05 of Huicheng Technology
随机推荐
[force deduction] 1337. Row K with the weakest combat effectiveness in the matrix
pip-script.py‘ is not present Verifying transaction: failed
20220726汇承科技的蓝牙模块HC-05的AT命令测试
MangoPapa 的实用小脚本(目录篇)
tensorboard使用记录
【OPENVX】对象基本使用之vx_matrix
Super nice PHP program source code of nteam official website
VMware virtual machine network settings
数字经济已成为最大看点
【OPENVX】对象基本使用之vx_image
ASEMI整流桥GBPC5010,GBPC5010参数,GBPC5010大小
【P4】解决本地文件修改与库文件间的冲突问题
leetcode刷题:动态规划09(最后一块石头的重量 II)
最新版宝塔安装zip扩展,php -m 不显示的处理方法
构建“产业大脑”,以“数字化”提升园区运营管理及服务能力!
每周推荐短视频:如何正确理解“精益”这个词?
MySQL Basics (create, manage, add, delete, and modify tables)
过亿资产地址被拉入黑名单?Tether地址冻结功能该怎么用?
CF question making record from July 25th to July 31st
某宝模拟登录,减少二次验证的方法