当前位置:网站首页>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
边栏推荐
- Report FCRA test question set and answers (11 wrong questions)
- vim编辑器的实时操作
- Differences between MySQL BTREE index and hash index
- VMware Workstation cannot connect to the virtual machine. The system cannot find the specified file
- Nanny Anaconda installation tutorial
- Execution plan calculation for different time types
- What is cloud migration? The four modes of cloud migration are?
- Solution to the fourth "intelligence Cup" National College Students' IT skills competition (group B of the final)
- 第九天 static 抽象类 接口
- Database dbvisualizer Pro reported file error, resulting in data connection failure
猜你喜欢
Government cloud migration practice: Beiming digital division used hypermotion cloud migration products to implement the cloud migration project for a government unit, and completed the migration of n
面试题 17.10. 主要元素
Detailed explanation of file operation (2)
Dlib of face recognition framework
Cloudy data flow? Disaster recovery on cloud? Last value content sharing years ago
安装及管理程序
无线鹅颈麦主播麦手持麦无线麦克风方案应当如何选择
文件操作详解(2)
Force buckle - 198 raid homes and plunder houses
DanceNN:字节自研千亿级规模文件元数据存储系统概述
随机推荐
Vim使用Vundle安装代码补全插件(YouCompleteMe)
Xinwangda: HEV and Bev super fast charging fist products are shipped on a large scale
Flask如何在内存中缓存数据?
第九天 static 抽象类 接口
LVM与磁盘配额
The system research problem that has plagued for many years has automatic collection tools, which are open source and free
欣旺达:HEV和BEV超快充拳头产品大规模出货
Day (6) of picking up matlab
linux上啟動oracle服務
Loading order of logback configuration file
LVM and disk quota
Detailed explanation of file operation (2)
TIA botu - basic operation
Server log analysis tool (identify, extract, merge, and count exception information)
PHP 零基础入门笔记(13):数组相关函数
The font of the soft cell changes color
ES常用查询、排序、聚合语句
Disk management and file system
File system read and write performance test practice
MySQL personal learning summary