Python+Unittest+Requests+PyMysql+HTMLReport 接口自动化框架

时间:2021-07-31 18:44:36

整体框架使用的是:Python+Unittest+Requests+PyMysql+HTMLReport  多线程并发模式

  • 主要依赖模块 Unittest、Requests、PyMysql、HTMLReport
  • 主要包含以下几个模块:

   1. Business:与业务相关的公共模块

  • get_login_token:接口自动化过程中需要实时获取token,并将实时获取的token传给下个接口作为请求参数
from Business.url import url_login
import requests, json def login_token(username=11111, password=123456):
"""获取登录后的token""" headers = {'Content-Type': 'application/json;charset=UTF-8'} request_param = {
"username": username,
"password": password
}
response = requests.post(url_login, data=json.dumps(request_param), headers=headers) # 返回JSON中data数据的token
print(response.json()['data']['token'])
return response.json()['data']['token'] if __name__ == '__main__':
login_token()
  • headers:头部信息
headers = {
'Content-Type': "application/x-www-form-urlencoded",
'X-Requested-With': "XMLHttpRequest",
'Content-Length': "",
'Connection': "keep-alive"
}
  • url:对应的URL地址
erp_url = 'https://www.baidu.com'

2. Common:与业务无关公共模块

  • connect_db:连接数据库,并操作数据库
import pymysql

# python3用的是pymysql,python2用的是MySQLdb

class OperationMysql:
"""
数据库SQL相关操作
""" def __init__(self):
self.conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='test',
passwd='',
db='test',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor
)
self.cur = self.conn.cursor() # 查询一条数据
def search_one(self, sql):
self.cur.execute(sql)
result = self.cur.fetchone() # 只显示一行结果
# result = self.cur.fetchall() # 显示所有结果
return result # 更新SQL
def updata_one(self, sql):
self.cur.execute(sql)
self.conn.commit()
self.conn.close() if __name__ == '__main__':
op_mysql = OperationMysql()
res = op_mysql.search_one("SELECT * from odi_order WHERE order_no='12222'")
print(res)

3.TestCase:测试用例层

  • test_case:用例数据
import unittest
from HTMLReport import logger
import requests from Business.url import erp_url class Category(unittest.TestCase):
"""ERP属性接口""" def setUp(self):
self.session = requests.Session()
logger().info("获取会话") def tearDown(self):
self.session.close()
logger().info("关闭会话") def test_type_list(self):
"""get请求方式"""
s = self.session
querystry = {}
r = s.get(erp_url + '/xxx.list', params=querystry)
logger().info(f"返回数据{r.json()}")
self.assertEqual("success", r.json().get("msg"))
def test_pay_success_recommend(self):
"""Post请求方式"""
s = self.session
payload = {
"token": login_token,
"p": "ios",
"v": "5.6.0",
"order_no": ""
}
r = s.post(erp_url + '/xxxxx/aaa', data=payload)
logger().info(f"返回数据:{r.json()}")
self.assertEqual('success', r.json().get('msg'))

4.TestSuite:测试套件封装

  • suite_api:测试套件
import unittest
from Test_Case.refactor import test_order def get_suite():
suite = unittest.TestSuite()
loader = unittest.TestLoader() suite.addTests(loader.loadTestsFromTestCase(test_order.Apitests)) return suite

5.Run:主运行文件

import unittest
from Test_Suite import suite_api
import HTMLReport
import time
suite = unittest.TestSuite()
suite.addTests(suite_api.get_suite())
HTMLReport.TestRunner(
title="XXX项目测试报告",
description="测试人员:CesareCheung",
report_file_name=f"testreport",
thread_count=50
).run(suite)

6.框架整体结构图:
Python+Unittest+Requests+PyMysql+HTMLReport  接口自动化框架