Skip to content

Commit 7fbe45f

Browse files
author
居强
committed
新增所有代码
0 parents  commit 7fbe45f

12 files changed

+327
-0
lines changed

.gitignore

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
.idea/**
2+
.cache/**
3+
core/.cache/**
4+
*.pyc
5+
core/*.pyc

constants.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#!/usr/bin/python
2+
# -*- coding: UTF-8 -*-
3+
# 通用包:常量
4+
5+
#!/usr/bin/python
6+
# -*- coding: UTF-8 -*-
7+
# 脚本功能:全部变量
8+
9+
10+
CASE_NUMBER = 0 # 用例编号
11+
CASE_NAME = 1 # 用例名称
12+
CASE_DATA = 2 # 用例参数
13+
CASE_URL = 3 # 用例接口地址
14+
CASE_METHOD = 4 # 用例请求类型
15+
CASE_CODE = 5 # 用例code
16+
CASE_HEADERS = 6 # 用例headers
17+
18+
SQL_ROW = 0 # 预执行SQL的行号
19+
SQL_COL = 1 # 预执行SQL的列号
20+
21+
FILE_NAME = 'test.xlsx'

core/__init__.py

Whitespace-only changes.

core/excel.py

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# !/usr/bin/python
2+
# -*- coding: UTF-8 -*-
3+
# author: 赫本z
4+
# 基础包: excel的封装
5+
6+
import xlrd
7+
workbook = None
8+
9+
def open_excel(path):
10+
"""
11+
打开excel
12+
:param path: 打开excel文件的位置
13+
"""
14+
global workbook
15+
if (workbook == None):
16+
workbook = xlrd.open_workbook(path, on_demand=True)
17+
18+
def get_sheet(sheetName):
19+
"""
20+
获取页名
21+
:param sheetName: 页名
22+
:return: workbook
23+
"""
24+
global workbook
25+
return workbook.sheet_by_name(sheetName)
26+
27+
def get_rows(sheet):
28+
"""
29+
获取行号
30+
:param sheet: sheet
31+
:return: 行数
32+
"""
33+
return sheet.nrows
34+
35+
def get_content(sheet, row, col):
36+
"""
37+
获取表格中内容
38+
:param sheet: sheet
39+
:param row: 行
40+
:param col: 列
41+
:return:
42+
"""
43+
return sheet.cell(row, col).value
44+
45+
def release(path):
46+
"""释放excel减少内存"""
47+
global workbook
48+
workbook.release_resources()
49+
del workbook
50+
# todo:没有验证是否可用

core/log.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#!/usr/bin/python
2+
# -*- coding: UTF-8 -*-
3+
# author: 赫本z
4+
# 基础包: 日志服务
5+
import logging
6+
7+
def get_logger():
8+
global logPath
9+
try:
10+
logPath
11+
except NameError:
12+
logPath = ""
13+
FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
14+
logging.basicConfig(level=logging.INFO, format=FORMAT)
15+
return logging

core/mysql.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#!/usr/bin/python
2+
# -*- coding: UTF-8 -*-
3+
# author: 赫本z
4+
# 基础包: MySQL
5+
6+
import pymysql.cursors
7+
import core.log as log
8+
9+
10+
logging = log.get_logger()
11+
conn = None
12+
13+
def connect(host, user, password, db, charset='utf8'):
14+
"""
15+
链接Mysql
16+
:param host: 地址
17+
:param user: 用户
18+
:param password: 密码
19+
:param db: 数据库名
20+
:param charset: 数据类型
21+
:return: 链接
22+
"""
23+
global conn
24+
if conn == None:
25+
conn = pymysql.connect(host=host,
26+
user=user,
27+
password=password,
28+
db=db,
29+
charset=charset,
30+
cursorclass=pymysql.cursors.DictCursor)
31+
return conn
32+
33+
34+
def execute(sql):
35+
"""
36+
执行SQL
37+
:param sql: 执行的SQL
38+
:return: 影响行数
39+
"""
40+
global conn
41+
try:
42+
with conn.cursor() as cursor:
43+
res = cursor.execute(sql)
44+
conn.commit()
45+
# 这里一定要写commit 不然提交的sql 都会被事务回滚
46+
return res
47+
except Exception, e:
48+
logging.error("sql is empty or error %s" % e)
49+
50+
51+
def close():
52+
"""
53+
关闭MySQL连接
54+
:return: None
55+
"""
56+
global conn
57+
conn.close()

core/request.py

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#!/usr/bin/python
2+
#-*- coding: UTF-8 -*-
3+
# 基础包:接口测试的封装
4+
5+
import requests
6+
import core.log as log
7+
import json
8+
9+
logging = log.get_logger()
10+
11+
def change_type(value):
12+
"""
13+
对dict类型进行中文识别
14+
:param value: 传的数据值
15+
:return: 转码后的值
16+
"""
17+
try:
18+
if isinstance(eval(value), str):
19+
return value
20+
if isinstance(eval(value), dict):
21+
result = eval(json.dumps(value))
22+
return result
23+
except Exception, e:
24+
logging.error("类型问题 %s", e)
25+
26+
27+
def api(method, url, data ,headers):
28+
"""
29+
自定义一个接口测试的方法
30+
:param method: 请求类型
31+
:param url: 地址
32+
:param data: 数据
33+
:param headers: 请求头
34+
:return: code码
35+
"""
36+
global results
37+
try:
38+
if method == ("post" or "POST"):
39+
results = requests.post(url, data, headers=headers)
40+
if method == ("get" or "GET"):
41+
results = requests.get(url, data, headers=headers)
42+
# if method == "put":
43+
# results = requests.put(url, data, headers=headers)
44+
# if method == "delete":
45+
# results = requests.delete(url, headers=headers)
46+
# if method == "patch":
47+
# results == requests.patch(url, data, headers=headers)
48+
# if method == "options":
49+
# results == requests.options(url, headers=headers)
50+
response = results.json()
51+
code = response.get("code")
52+
return code
53+
except Exception, e:
54+
logging.error("service is error", e)
55+
56+
57+
def content(method, url, data, headers):
58+
"""
59+
请求response自己可以自定义检查结果
60+
:param method: 请求类型
61+
:param url: 请求地址
62+
:param data: 请求参数
63+
:param headers: 请求headers
64+
:return: message信息
65+
"""
66+
global results
67+
try:
68+
if method == ("post" or "POST"):
69+
results = requests.post(url, data, headers=headers)
70+
if method == ("get" or "GET"):
71+
results = requests.get(url, data, headers=headers)
72+
if method == ("put" or "PUT"):
73+
results = requests.put(url, data, headers=headers)
74+
if method == ("patch" or "PATCH"):
75+
results = requests.patch(url, data, headers=headers)
76+
response = results.json()
77+
message = response.get("message")
78+
result = response.get("result")
79+
content = {"message": message, "result": result}
80+
return content
81+
except Exception, e:
82+
logging.error("请求失败 %s" % e)

function/__init__.py

Whitespace-only changes.

function/func.py

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#!/usr/bin/python
2+
# -*- coding: UTF-8 -*-
3+
# 业务包:通用函数
4+
5+
6+
import core.mysql as mysql
7+
import core.log as log
8+
import core.request as request
9+
import core.excel as excel
10+
import constants as cs
11+
from prettytable import PrettyTable
12+
13+
logging = log.get_logger()
14+
15+
16+
class ApiTest:
17+
"""接口测试业务类"""
18+
filename = cs.FILE_NAME
19+
20+
def __init__(self):
21+
pass
22+
23+
def prepare_data(self, host, user, password, db, sql):
24+
"""数据准备,添加测试数据"""
25+
mysql.connect(host, user, password, db)
26+
res = mysql.execute(sql)
27+
mysql.close()
28+
logging.info("Run sql: the row number affected is %s", res)
29+
return res
30+
31+
def get_excel_sheet(self, path, module):
32+
"""依据模块名获取sheet"""
33+
excel.open_excel(path)
34+
return excel.get_sheet(module)
35+
36+
def get_prepare_sql(self, sheet):
37+
"""获取预执行SQL"""
38+
return excel.get_content(sheet, cs.SQL_ROW, cs.SQL_COL)
39+
40+
def run_test(self, sheet, url):
41+
"""再执行测试用例"""
42+
rows = excel.get_rows(sheet)
43+
fail = 0
44+
for i in range(2, rows):
45+
testNumber = str(int(excel.get_content(sheet, i, cs.CASE_NUMBER)))
46+
testData = excel.get_content(sheet, i, cs.CASE_DATA)
47+
testName = excel.get_content(sheet, i, cs.CASE_NAME)
48+
testUrl = excel.get_content(sheet, i, cs.CASE_URL)
49+
testUrl = url + testUrl
50+
testMethod = excel.get_content(sheet, i, cs.CASE_METHOD)
51+
testHeaders = eval(excel.get_content(sheet, i, cs.CASE_HEADERS))
52+
testCode = excel.get_content(sheet, i, cs.CASE_CODE)
53+
actualCode = request.api(testMethod, testUrl, testData, testHeaders)
54+
expectCode = str(int(testCode))
55+
failResults = PrettyTable(["Number", "Method", "Url", "Data", "ActualCode", "ExpectCode"])
56+
failResults.align["Number"] = "l"
57+
failResults.padding_width = 1
58+
failResults.add_row([testNumber, testMethod, testUrl, testData, actualCode, expectCode])
59+
60+
if actualCode != expectCode:
61+
logging.info("FailCase %s", testName)
62+
print "FailureInfo"
63+
print failResults
64+
fail += 1
65+
else:
66+
logging.info("Number %s", testNumber)
67+
logging.info("TrueCase %s", testName)
68+
if fail > 0:
69+
return False
70+
return True

run.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#!/usr/bin/python
2+
# -*- coding: UTF-8 -*-
3+
# 验证包:接口测试脚本
4+
5+
import core.log as log
6+
from function.func import ApiTest
7+
8+
func = ApiTest()
9+
logging = log.get_logger()
10+
11+
"""1.外部输入参数"""
12+
13+
module = 'user'
14+
url = 'http://127.0.0.1:8080'
15+
16+
"""2.根据module获取Sheet"""
17+
logging.info("-------------- Execute TestCases ---------------")
18+
sheet = func.get_excel_sheet(func.filename, module)
19+
20+
# """3.数据准备"""
21+
# logging.info("-------------- Prepare data through MysqlDB --------------")
22+
# sql = func.get_prepare_sql(sheet)
23+
# func.prepare_data(host=host, user=user, password=password, db=db, sql=sql)
24+
25+
"""4.执行测试用例"""
26+
res = func.run_test(sheet, url)
27+
logging.info("-------------- Get the result ------------ %s", res)

test.xlsx

18.9 KB
Binary file not shown.

~$test.xlsx

171 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)