1、通过全局变量存放用例数据
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : GetData.py
class GetData:
Cookie = None
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : http_request.py
import requests
class HttpRequest:
def http_request(self, url, data, method):
result = None
if method.lower() == 'post':
result = requests.request("POST", url, data=data)
elif method.lower() == 'get':
result = requests.request("GET", url, data=data)
else:
print("错误")
return result
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : test_http.py
import unittest
from test_excel_case import GetData
from test_excel_case.http_request import HttpRequest
class TestHttp(unittest.TestCase):
def setUp(self):
self.login_url = "https://xxxx.com/xxxxi/login"
def __init__(self, methodName, url, data, method, expected): #通过初始化函数传参
super(TestHttp, self).__init__(methodName) # 父类的方法保留了
self.url = url
self.data = data
self.method = method
self.expected = expected
def test_api(self): #接口用例
res = HttpRequest().http_request(self.url, self.data, self.method)
if res.cookies:#如果cookie有的话,那么就更新cookie
setattr(GetData,'Cookie',res.cookies) #反射
try:
self.assertEqual(self.expected,res.json()['code'])
except AssertionError as e:
print("test_api's error is {}".format(e))
raise e
print(res)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : test_suite.py
import HTMLTestRunner
import unittest
from test_excel_case.test_http import TestHttp
test_data = [{"url": "https://xxxx.com/xxxxi/login",
"data": {"username": "testlxm", "password": "testlxm"}, "expected": 1000, "method": "post"},
{"url": "https://xxxx.com/xxxxi/login",
"data": {"username": "testlxm", "password": "123456"}, "expected": 1000, "method": "post"}]
suite = unittest.TestSuite()
for item in test_data: #创建用例
suite.addTest(TestHttp('test_api', test_data[0]['url'], test_data[0]['data'], test_data[0]['method'],
test_data[0]['expected']))
with open("test_summer.html","wb") as file:
testrunner = HTMLTestRunner.HTMLTestRunner(stream=file, verbosity=2, title=None, description=None)
testrunner.run(suite)
#正常登录后,返回的数据
{
"code" : 1000,
"msg" : "OK",
"data" : {
"guid" : "def8b5a9c4d4354a6a4618",
"token" : "3242ac20-55c5-40fb-9ec3-62143b5cea52",
"loginId" : "testlxm",
"username" : "testlxm",
"sex" : "1",
"email" : "testlxm@xx.com.cn",
"mobile" : "15621252325",
"isAdmin" : null,
"tenantId" : "tenant_system",
"tenantName" : "租户",
"redirectUrl" : null,
"isButton" : [ ],
"icon" : "/imagepool/2019-04-03/6664088899.png",
"roleId" : "4"
}
}