当前位置:网站首页>DDT + Excel for interface test
DDT + Excel for interface test
2022-04-23 16:36:00 【Sink the wine cup and fleeting time】
DDT+Excel Conduct interface test
There are many methods of interface testing , For example, using postman
、Jmeter
And other tools for interface testing ; You can also test the interface by writing code , Generate test reports .
Use the way of writing code to test the interface , Usually a test case , Normal operation is required 、 Abnormal multiple scenario testing , Each scene , Different test data are needed , In general , The same test case will be run with different data by using data-driven testing .
Management of test data , There are many ways , such as yaml
file 、py
file , In some cases , Table type files will be used , Such as excel
form 、csv
Documents, etc.
Here is a brief introduction to DDT+Excel
Conduct interface test
DDT brief introduction
Data-Driven Tests
(DDT) namely Data driven testing
DDT The advantages of :
- Avoid writing duplicate code
- Separate the data from the test script
- By using data-driven testing , To validate multiple sets of data test scenarios
DDT The essence is a decorator , A set of data, a scene .
Frame structure
Interface test content
Usually , Conduct interface test , The following points need to be considered : Requested url Address 、 Request mode 、 Request parameters 、 Response content
example :
url:http://192.168.31.111:8080/api/user/verify_phone
method:post
params:
{
phone_num:15912349876}
response:
{
"success":true,
"code": 2000,
"msg":" The mobile phone number format is correct "
}
{
"success":false,
"code": 2001,
"msg":" The length of the entered mobile number is not 11 position "
}
Path configuration
dir_config.py
import os
# The absolute path of the top-level directory of the framework project
base_dir = os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
# Test data path
testdatas_dir = os.path.join(base_dir,"test_datas")
# Test case path
testcases_dir = os.path.join(base_dir,"test_cases")
# Test report path
htmlreport_dir = os.path.join(base_dir,"reports")
excel Process encapsulation
Detailed analysis , You can view this article :Python encapsulation excel operation
excel_handler.py
from openpyxl import load_workbook
from openpyxl.worksheet.worksheet import Worksheet
class ExcelHandler():
''' operation Excel '''
def __init__(self, file):
''' Initialization function '''
self.file = file
def open_sheet(self, sheet_name) -> Worksheet:
''' Open form '''
wb = load_workbook(self.file)
sheet = wb[sheet_name]
return sheet
def read_header(self, sheet_name):
''' Get the header of the form '''
sheet = self.open_sheet(sheet_name)
headers = []
for i in sheet[1]:
headers.append(i.value)
return headers
def read_rows(self,sheet_name):
''' Read all data except the header ( All data except the first row ) The returned content is a two-dimensional list , If you want to get the data of each row , You can use for Cycle or * Unpack '''
sheet = self.open_sheet(sheet_name)
rows = list(sheet.rows)[1:]
data = []
for row in rows:
row_data = []
for cell in row:
row_data.append(cell.value)
data.append(row_data)
return data
def read_key_value(self,sheet_name):
''' Get all the data , And combine the contents in the header with the data ( In the form of a dictionary ) '''
sheet = self.open_sheet(sheet_name)
rows = list(sheet.rows)
# Get the title
data = []
for row in rows[1:]:
rwo_data = []
for cell in row:
rwo_data.append(cell.value)
# List into Dictionary , Use with the content in the header zip Function to package
data_dict = dict(zip(self.read_header(sheet_name),rwo_data))
data.append(data_dict)
return data
@staticmethod
def write_change(file,sheet_name,row,column,data):
''' write in Excel data '''
wb = load_workbook(file)
sheet = wb[sheet_name]
# Change cell
sheet.cell(row,column).value = data
# preservation
wb.save(file)
# close
wb.close()
requests Request to packaging
Detailed analysis , You can view this article : Interface request encapsulation
RequestsHandler.py
import requests
class HTTPHandler:
# initialization
def __init__(self):
self.session = requests.Session()
# Define a method , Receive access http How to request
def visit(self, url, method, params=None, data=None, json=None, **kwargs):
res = self.session.request(method, url, params=params, data=data, json=json, **kwargs)
try:
return res.json()
except ValueError:
print('return not json')
# close session conversation
def close_session(self):
self.session.close()
The test case
Test data
【 expand 】: If the data to be transmitted is not a single data such as mobile phone number , It is json Formatted data
Such as phonenum
This column becomes msg
, yes json Formatted data
{
"name":"lili","phonenum":'17379745547'}
You need to process the read data , If the data read is of string type , It needs to be converted to dictionary type , You can use eval()
function
however , If the data needs to have null
Type of content , Use eval()
The function will report an error
{
"name":"lili","phonenum":null}
because python There is no null
Data of type , Only None
, therefore , I need to use json.loads()
function
import json
data = '{"name":"lili","phonenum":null}'
data_json= json.loads(data)
Test case file
test_user.py
import json
import unittest
import os
import ddt
from TEST.common.RequestHandler import HTTPHandler
from TEST.common.excel_handler import ExcelHandler
from TEST.common import dir_config
# Read test data
test_data = ExcelHandler(os.path.join(dir_config.testdatas_dir,"data.xlsx")).read_key_value("Sheet1")
@ddt.ddt
class Test_Verify_Code(unittest.TestCase):
def setUp(self) -> None:
self.req = HTTPHandler()
def tearDown(self) -> None:
self.req.close_session()
@ddt.data(*test_data)
def test_verify_phone(self,test_data):
res = self.req.visit(test_data["url"],test_data["method"],json=test_data["phonenum"])
# res = self.req.visit(test_data["url"],test_data["method"],json=json.loads(test_data["msg"]))
self.assertEqual(res["code"],test_data["excepted"])
Before executing the test case , You can initialize a resquest
object , Conduct session conversation , End of execution case , Close this session . Put these two steps into setUp
and tearDown
in
By calling ExcelHandler
Class read_key_value
Method , Read excel File data , Convert it to a list , Each element in the list is a set of test data in dictionary format
[
{'url': 'http://192.168.31.111:8080/api/user/verify_phone', 'method': 'post', 'phonenum': 17761523654, 'excepted': 2000},
{'url': 'http://192.168.31.111:8080/api/user/verify_phone', 'method': 'post', 'phonenum': 123, 'excepted': 2001},
{'url': 'http://192.168.31.111:8080/api/user/verify_phone', 'method': 'post', 'phonenum': ' test ', 'excepted': 2002},
{'url': 'http://192.168.31.111:8080/api/user/verify_phone', 'method': 'post', 'phonenum': 'test', 'excepted': 2002}
]
adopt ddt
Unpack , Read each set of test data , By calling HTTPHandler
Class visit
Method , Read the contents of each set of test data examples , Request interface , Compare the contents of the response one by one
Executable files
run_case.py
import os
import time
import unittest
from TEST.common import dir_config
from TEST.common.HTMLTestRunnerNew import HTMLTestRunner
from TEST.test_cases import test_user
testloader = unittest.TestLoader()
# Load all use cases in the specified directory
suit_total = testloader.discover(dir_config.testcases_dir)
curTime = time.strftime("%Y-%m-%d %H_%M", time.localtime())
# Test report file name format
file_path = os.path.join(dir_config.htmlreport_dir,'{}_test.html'.format(curTime))
with open(file_path,"wb") as f:
runner = HTMLTestRunner(f,title=' Test report ',description=' The content of the test report is :',tester='bobo')
runner.run(suit_total)
Executable files , Generate test reports
版权声明
本文为[Sink the wine cup and fleeting time]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231402128507.html
边栏推荐
- Es common query, sorting and aggregation statements
- On the security of key passing and digital signature
- Using JSON server to create server requests locally
- vim编辑器的实时操作
- Xinwangda: HEV and Bev super fast charging fist products are shipped on a large scale
- Hypermotion cloud migration helped China Unicom. Qingyun completed the cloud project of a central enterprise and accelerated the cloud process of the group's core business system
- Passing header request header information between services through feign
- 安装及管理程序
- Phpstudy V8, a commonly used software for station construction 1 graphic installation tutorial (Windows version) super detailed
- Dlib of face recognition framework
猜你喜欢
建站常用软件PhpStudy V8.1图文安装教程(Windows版)超详细
What is the experience of using prophet, an open source research tool?
Use itextpdf to intercept the page to page of PDF document and divide it into pieces
DanceNN:字节自研千亿级规模文件元数据存储系统概述
Nanny Anaconda installation tutorial
Force buckle - 198 raid homes and plunder houses
Interview question 17.10 Main elements
Install redis and deploy redis high availability cluster
Gartner 发布新兴技术研究:深入洞悉元宇宙
Creation of RAID disk array and RAID5
随机推荐
Disk management and file system
Gartner 發布新興技術研究:深入洞悉元宇宙
Database dbvisualizer Pro reported file error, resulting in data connection failure
1959年高考数学真题
文件系统读写性能测试实战
5-minute NLP: text to text transfer transformer (T5) unified text to text task model
Summary according to classification in sail software
关于 background-image 渐变gradient()那些事!
Day (6) of picking up matlab
英语 | Day15、16 x 句句真研每日一句(从句断开、修饰)
建站常用软件PhpStudy V8.1图文安装教程(Windows版)超详细
Gartner publie une étude sur les nouvelles technologies: un aperçu du métacosme
七朋元视界可信元宇宙社交体系满足多元化的消费以及社交需求
Creation of RAID disk array and RAID5
Gartner announces emerging technology research: insight into the meta universe
Phpstudy V8, a commonly used software for station construction 1 graphic installation tutorial (Windows version) super detailed
伪分布安装spark
Take according to the actual situation, classify and summarize once every three levels, and see the figure to know the demand
linux上启动oracle服务
Cartoon: what are IAAs, PAAS, SaaS?