Python unittest结合Flask实现API自动化测试详解

七月
七月
发布时间:2026-10-12 | 2人浏览过
原创

本文详细介绍如何使用Python的unittest框架结合Flask进行API自动化测试。通过定义RESTful接口、配置Blueprint蓝图,并利用api.url_for和flask.url_for生成测试URL,实现GET、POST、PUT方法的自动化验证。文章重点解析了请求参数获取方式及端点命名规则,提供完整代码示例与测试结果,帮助开发者快速掌握API接口测试的核心流程。

项目测试在软件开发中至关重要,熟悉Python的开发者通常都编写过自动化测试脚本。近期负责公司的API测试工作,为此整理了一个简单示例,旨在梳理API测试的具体流程。

首先,需要编写RESTful API接口文件testpost.py,该文件需包含get、post和put方法的实现。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import request
from flask_restful import Resource
from flask_restful import reqparse


test_praser = reqparse.RequestParser()
test_praser.add_argument('ddos')


class TestPost(Resource):
 def post(self, PostData):
 data = request.get_json()
 user = User('wangjing')
 if data['ddos']:
 return {'hello': 'uese', "PostData": PostData, 'ddos': 'data[\'ddos\']'}
 return {'hello': 'uese', "PostData": PostData}

 def get(self, PostData):
 data = request.args
 if data and data['ddos']:
 return "hello" + PostData + data['ddos'], 200
 return {'hello': 'uese', "PostData": PostData}

 def put(self, PostData):
 data = test_praser.parse_args()
 if data and data['ddos']:
 return "hello" + PostData + data['ddos'], 200
 return {'hello': 'uese', "PostData": PostData}

注:关于request对象获取数据的方式,此处定义了三种常用方法。

post方法:使用request.get_json(),调用API时以JSON格式传递参数。 get和put方法:使用request.args或reqparse.RequestParser(),调用API时传递字符串参数。

其次,定义Blueprint(蓝图)文件init.py。

#!/usr/bin/env python
 # -*- coding: utf-8 -*-
 from flask import Blueprint
 from flask_restful import Api
 from testpost import TestPost

 testPostb = Blueprint('testPostb', __name__)
 api = Api(testPostb)
 api.add_resource(TestPost, '/<string:PostData>/postMeth')

接着,编写测试脚本testPostM.py。

#!/usr/bin/env python
 # -*- coding: utf-8 -*-
 import unittest
 import json
 from secautoApp.api.testPostMeth import api
 from flask import url_for
 from run import app
 from secautoApp.api.testPostMeth import TestPost

 headers = {'Accept': 'application/json',
 'Content-Type': 'application/json'
 }

 class APITestCase(unittest.TestCase):
 def setUp(self):
 # self.app = create_app(os.getenv("SECAUTOCFG") or 'default')
 self.app = app
 # self.app_context = self.app.app_context()
 # self.app_context.push()
 self.client = self.app.test_client()

 #
 # def tearDown(self):
 # self.app_context.pop()

 def test_post(self):
 # with app.test_request_context():

 response = self.client.get(api.url_for(TestPost, PostData='adb', ddos='123'))
 self.assertTrue(response.status_code == 200)

 response = self.client.get(url_for('testPostb.testpost', PostData='adb', ddos='123'))
 self.assertTrue(response.status_code == 200) 
 self.assertTrue(json.loads(response.data)['PostData'] =='adb')

 response = self.client.post(url_for('testPostb.testpost', PostData='adb'), headers=headers,
   data=json.dumps({"ddos": '123'}))
 print json.loads(response.data)
 self.assertTrue(response.status_code == 200)

 response = self.client.put(url_for('testPostb.testpost', PostData='adb', ddos='123'))
 self.assertTrue(json.loads(response.data) == 'helloadb123')

 response = self.client.put(url_for('testPostb.testpost', PostData='adb'))
 print json.loads(response.data)['PostData']
 self.assertTrue(response.status_code == 200)

注:调用的API URL主要依赖flask_restful的api.url_for或flask的url_for生成,下面将详细说明这两种方法的具体用法。

flask_restful中api.url_for的用法说明。

api.url_for(TestPost, PostData='adb'),其中TestPost指代在RESTful API接口文件中定义的类。由于已在API蓝图中通过api.add_resource(TestPost, '/<string:PostData>/postMeth')以类方式注册,因此可直接引用。

flask中url_for的用法说明。

url_for('testPostb.testpost', PostData='adb', ddos='123'),字符串'testPostb.testpost'中: testPostb指蓝图的名称,即testPostb = Blueprint('testPostb', name)中Blueprint函数的第一个参数。 testpost指蓝图下的端点名称,在flask_restful中,对应api.add_resource(TestPost, '/<string:PostData>/postMeth')中类名TestPost的小写形式。

启动测试脚本的方法如下。

C:\secauto3>python run.py test
test_post (testPostM.APITestCase) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.056s

OK

小结:url_for传递的参数与request中获取的数据存在对应关系。最后需注意,flask_restful中的端点名称必须为api.add_resource中注册类名的小写形式。

领取干货:零基础入门学习python视频教程。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表