当前位置:网站首页>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
边栏推荐
- G008-hwy-cc-estor-04 Huawei Dorado V6 storage simulator configuration
- 299. Number guessing game
- MySQL的btree索引和hash索引区别
- Day 10 abnormal mechanism
- Es common query, sorting and aggregation statements
- 面试题 17.10. 主要元素
- NVIDIA显卡驱动报错
- 1959年高考数学真题
- 如何进行应用安全测试(AST)
- Server log analysis tool (identify, extract, merge, and count exception information)
猜你喜欢
JMeter setting environment variable supports direct startup by entering JMeter in any terminal directory
各大框架都在使用的Unsafe类,到底有多神奇?
DanceNN:字节自研千亿级规模文件元数据存储系统概述
Use if else to judge in sail software - use the title condition to judge
Xinwangda: HEV and Bev super fast charging fist products are shipped on a large scale
[key points of final review of modern electronic assembly]
建站常用软件PhpStudy V8.1图文安装教程(Windows版)超详细
Countdown 1 day ~ 2022 online conference of cloud disaster tolerance products is about to begin
Use itextpdf to intercept the page to page of PDF document and divide it into pieces
Force buckle - 198 raid homes and plunder houses
随机推荐
Nacos 详解,有点东西
Set the color change of interlaced lines in cells in the sail software and the font becomes larger and red when the number is greater than 100
OAK-D树莓派点云项目【附详细代码】
Countdown 1 day ~ 2022 online conference of cloud disaster tolerance products is about to begin
logback的配置文件加载顺序
vim编辑器的实时操作
About background image gradient()!
LVM and disk quota
5分钟NLP:Text-To-Text Transfer Transformer (T5)统一的文本到文本任务模型
How to upgrade openstack across versions
The font of the soft cell changes color
Qipengyuan horizon credible meta universe social system meets diversified consumption and social needs
JMeter installation tutorial and solutions to the problems I encountered
Cloudy data flow? Disaster recovery on cloud? Last value content sharing years ago
On the value, breaking and harvest of NFT project
Cloud migration practice in the financial industry Ping An financial cloud integrates hypermotion cloud migration solution to provide migration services for customers in the financial industry
Easyexcel reads the geographical location data in the excel table and sorts them according to Chinese pinyin
JSP learning 1
伪分布安装spark
Day 10 abnormal mechanism