测试网站:https://www.ketangpai.com/
测试功能:登录功能
测试用例:正常登录、密码为空、用户名为空、密码错误
测试方法:用例数据存储在excel中,通过获取excel数据进行测试,并生成测试报告
通过fiddler抓取网站登录api接口:https://www.ketangpai.com/UserApi/login
注:可以自己注册一个是账号测试一下,本次所用用户名、密码已修改不可直接使用
image.png
一、先写了三个工具类方便后面使用
# http_request.py #requests请求判断是否为get请求,返回请求结果
# -*-coding: utf8 -*-
import requests
class HttpRequest(object):
def http_request(self, url, data, method, expected=None, cookie=None):
if method.lower() == 'get':
res = requests.get(url, data=None, cookies=cookie, verify=False)
#verify暂时忽略ssl证书警告
else:
res = requests.post(url, data, cookies=cookie, verify=False)
return res
#get_data.py
# -*-coding: utf8 -*- #Cookie全局变量
class GetData(object):
Cookie = None
# -*-coding: utf8 -*-
# do_excel.py
#先安装openpyxl,只允许.xlsx格式的文件。
#新建excel文件时不可以在项目内部直接建,可在桌面或安装目录下建好复制过来
from openpyxl import load_workbook
class DoExcel(object):
def __init__(self, file_name, sheet_name):
self.file_name = file_name #excel文件名
self.sheet_name = sheet_name #表单名
def get_data(self):
wb = load_workbook(self.file_name)
sheet = wb[self.sheet_name]
max_row = sheet.max_row #最大行数
test_data = []
for row in range(1, max_row + 1):
sub_data = {}
sub_data['url'] = sheet.cell(row, 1).value #单元格值
sub_data['data'] = sheet.cell(row, 2).value
sub_data['expected'] = sheet.cell(row, 3).value
sub_data['method'] = sheet.cell(row, 4).value
test_data.append(sub_data)
return test_data
if __name__ == '__main__':
print(DoExcel('data.xlsx', 'login_data').get_data())
二、测试登录功能
#test_login.py
import unittest
from practise.utils.get_data import GetData
from practise.utils.http_request import HttpRequest
class TestHttpRequest(unittest.TestCase):
def __init__(self, methodName, url, data, method, expected):#通过初始化函数传参
super(TestHttpRequest, self).__init__(methodName)#保留父类的方法
self.url = url
self.data = data
self.method = method
self.expected = expected
def setUp(self):
pass
def test_api(self):
res = HttpRequest().http_request(
self.url,
self.data,
self.method,
self.expected,
getattr(GetData, 'Cookie')
)
if res.cookies: # 如果cookie有的话,那就更新COOKIE
setattr(GetData, 'Cookie', res.cookies)
try:
self.assertEqual(self.expected, res.json()['info'])
except AssertionError as e:
print('test_api的错误是:{}'.format(e))
raise e
# print(res.json())
#test_suite.py 用例数据
import unittest
import json
from HtmlTestRunner import HTMLTestRunner
from practise.cases.test_login import TestHttpRequest
from practise.do_excel import DoExcel
test_data = DoExcel('data.xlsx', 'login_data').get_data()
suite = unittest.TestSuite()
for item in test_data:
suite.addTest(
TestHttpRequest(
'test_api',
item['url'],
eval(item['data']),#eval的作用是把字符串变为原来的形式(字典)
item['method'],
item['expected']
)
)
with open('test_login_report.html', 'w', encoding='utf8') as file:
runner = HTMLTestRunner(
output="./reports/",
stream=file,
verbosity=2,
descriptions=True
)
runner.run(suite)
表内数据(信息已修改,需要可以自己注册测试)image.png
image.png
image.png