当前位置:网站首页>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
边栏推荐
- Installation and management procedures
- How magical is the unsafe class used by all major frameworks?
- Postman batch production body information (realize batch modification of data)
- How to upgrade openstack across versions
- Database dbvisualizer Pro reported file error, resulting in data connection failure
- Xinwangda: HEV and Bev super fast charging fist products are shipped on a large scale
- Real time operation of vim editor
- 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
- Detailed explanation of gzip and gunzip decompression parameters
- 各大框架都在使用的Unsafe类,到底有多神奇?
猜你喜欢

安装及管理程序
![[key points of final review of modern electronic assembly]](/img/17/007ca1f4fedd11ab878bddda3faf56.jpg)
[key points of final review of modern electronic assembly]

LVM与磁盘配额

Cloudy data flow? Disaster recovery on cloud? Last value content sharing years ago

力扣-198.打家劫舍

Day 10 abnormal mechanism

How magical is the unsafe class used by all major frameworks?

G008-HWY-CC-ESTOR-04 华为 Dorado V6 存储仿真器配置

Sail soft calls the method of dynamic parameter transfer and sets parameters in the title

Day (4) of picking up matlab
随机推荐
Sort by character occurrence frequency 451
homwbrew安装、常用命令以及安装路径
Introduction notes to PHP zero Foundation (13): array related functions
What is homebrew? And use
Win11 / 10 home edition disables the edge's private browsing function
Database dbvisualizer Pro reported file error, resulting in data connection failure
Detailed explanation of UWA pipeline function | visual configuration automatic test
Review 2021: how to help customers clear the obstacles in the last mile of going to the cloud?
英语 | Day15、16 x 句句真研每日一句(从句断开、修饰)
最詳細的背包問題!!!
如何进行应用安全测试(AST)
Creation of RAID disk array and RAID5
人脸识别框架之dlib
logback的配置文件加载顺序
MySQL personal learning summary
How to conduct application security test (AST)
vim编辑器的实时操作
Flask如何在内存中缓存数据?
Easyexcel reads the geographical location data in the excel table and sorts them according to Chinese pinyin
众昂矿业:萤石浮选工艺