前提:已安装pycharm,已配置python环境
第一步:新建一个py类,用来执行all的测试用例
import HTMLTestReportCN
import unittest, os, yagmail# -*- coding: utf-8 -*-
"""
@Time : 2024/9/2 14:50
@Auth : dongjinjin
@IDE :PyCharm
"""def run_case(fileName, htmlName):#获取当前文件的路径test_dir = os.path.dirname(__file__)#定义执行gfyl_case.py用例discover = unittest.defaultTestLoader.discover(test_dir, pattern=fileName)print(discover)#定义存储测试报告的路径和文件名filename = os.path.dirname(os.path.dirname(test_dir)) + '/py-test-gfyl/report/' + htmlNamefp = open(filename, 'wb')runner = HTMLTestReportCN.HTMLTestRunner(stream=fp, title='接口自动化测试报告', description='Implementation Example with: ',tester='dongjinjin')print("""测试进行中,请耐心等候......""")try:#执行用例runner.run(discover)except Exception as e:raise eelse:print('测试结束,测试运行无异常')fp.close()email = yagmail.SMTP(user='1578845978@qq.com', password='tonhkqehtmnnibdf', host='smtp.qq.com')# 设置测试结果报告接收人邮箱及内容email.send(to='1578845978@qq.com', subject='接口自动化测试报告', contents='您好请查收', attachments=filename)if __name__ == '__main__':# 设置执行测试用例的文件和生成的测试报告文件名 并执行该脚本run_case('gfyl_cases.py', 'walletResult.html')
第二步:定义一个requests请求类,包括GET、POST接口请求方法
# -*- coding: utf-8 -*-
"""
@Time : 2024/9/2 15:43
@Auth : dongjinjin
@IDE :PyCharm
"""
import requests
from urllib.parse import urlparse, parse_qsclass h5apirequests:base_url = "接口url"token_value = None # 类变量,用于存储token@classmethoddef setUp(cls):# 目标URLurl = "h5访问链接url"# 发送GET请求response = requests.get(url)# 从响应中获取cookiecookies = response.url# 解析URLparsed_url = urlparse(cookies)query_params = parse_qs(parsed_url.fragment) # 因为token在hash后面,所以使用fragment# 获取token值cls.token_value = query_params.get('token', [None])[0] # 使用列表解析并获取第一个元素print(cls.token_value)@classmethoddef send_request(cls, method, api_method, params=None, json=None):full_url = f"{cls.base_url}/{api_method}" # 构建完整的URL地址token = cls.token_valueheaders = {'Content-Type': 'application/json','token': token}try:if method.upper() == 'GET':response = requests.get(full_url, headers=headers, params=params)elif method.upper() == 'POST':response = requests.post(full_url, headers=headers, json=json)else:raise ValueError(f"Unsupported method: {method}")response.raise_for_status() # 检查响应状态码return responseexcept requests.exceptions.RequestException as e:print(f"Request failed: {e}")return None# 测试代码
if __name__ == '__main__':h5apirequests.setUp() # 调用setUp获取tokeninstance = h5apirequests() # 创建实例api_method = 'getReimbursementUser'params = {'userId': 'd7a5071c937332c819fd668ef6aa03d7'}response = instance.send_request('GET', api_method, params=params)if response:print('\n返回结果:\n%s' % response.text)response_data = response.json()response_code = response_data.get('code')# # 断言code值是否为200# if (response_code != 200):# self.assertEqual(response_code, 200, "Response code is not 200")# else:# pass
第三步:创建一个存放测试用例执行结果的包
第四步:创建一个测试类存放单独接口调用的测试方法
import unittestfrom gfyl_requests.h5apirequests import h5apirequestsclass MyTestCase(unittest.TestCase):base_url = "接口url"def test_queryReferralDocuments(self):h5apirequests.setUp() # 调用setUp获取tokeninstance = h5apirequests() # 创建实例api_method = 'queryReferralDocuments'params = {'name': '测试二','jobNumber': '999999999','idCard': '110123197010121234'}response = instance.send_request('POST', api_method, json=params)if response:print('\n返回结果:\n%s' % response.text)response_data = response.json()response_code = response_data.get('code')# 断言code值是否为200if (response_code != 200):self.assertEqual(response_code, 200, "Response code is not 200")else:passdef test_getReimbursementUse(self):h5apirequests.setUp() # 调用setUp获取tokeninstance = h5apirequests() # 创建实例api_method = 'getReimbursementUser'params = {'userId': 'd7a5071c937332c819fd668ef6aa03d7'}response = instance.send_request('GET', api_method, params=params)if response:print('\n返回结果:\n%s' % response.text)response_data = response.json()response_code = response_data.get('code')# 断言code值是否为200if (response_code != 200):self.assertEqual(response_code, 200, "Response code is not 200")else:pass# if __name__ == '__main__':
# unittest.main()
第五步: 执行完all测试case,输出测试报告html格式的,可以通过浏览器打开查看