5. 接口自动化框架---封装测试用例基类(base_test_case)

 1 """
 2 抽象出测试用例基类
 3     1. 提取Excel文件中的用例数据
 4     2. 自动处理鉴权请求头
 5     3. 生成一个没有被使用的手机号码
 6 """
 7 import unittest
 8 import settings
 9 
10 from common.request_handler import send_request
11 from common.log_handler import logger
12 from common.db_handler import db
13 from common.test_data_handler import get_data_from_excel, generate_phone_num
14 
15 
16 class BaseTestCase(unittest.TestCase):
17 
18     name = None   # 功能名称
19     logger = logger   # 日志处理器
20     db = db   # 数据库处理对象
21     auth_key = 'v1'   # 鉴权请求头
22     settings = settings   # 配置模块
23 
24     @classmethod
25     def setUpClass(cls) -> None:
26         # 类前置
27         cls.logger.info('========={}接口测试开始========='.format(cls.name))
28 
29     @classmethod
30     def tearDownClass(cls) -> None:
31         # 类后置
32         cls.logger.info('========={}接口测试结束========='.format(cls.name))
33 
34     @classmethod
35     def load_case(cls, sheet_name):
36         """
37         提取Excel文件中的用例数据
38         :param sheet_name: 表名
39         :return:
40         """
41         return get_data_from_excel(cls.settings.TEST_DATA_FILE, sheet_name)
42 
43     def send_request(self, url, method='GET', **kwargs):
44         # 自动处理鉴权请求头
45         kwargs.setdefault('headers', {})
46         kwargs['headers'].update(self.settings.CUSTOM_HEADERS[self.auth_key])
47 
48         if self.auth_key == 'v2':
49             pass
50         if self.auth_key == 'v3':
51             pass
52 
53         return send_request(url, method, **kwargs)
54 
55     @classmethod
56     def get_unused_phone_num(cls, sql_template="select id from table where mobile_phone='{}'"):
57         """
58         生成一个没有被使用的手机号码
59         :param sql_template: SQL模板,用来查询数据库中是否存在指定的电话号码,在下方的方法中使用format风格
60         :return: 手机号码
61         """
62         while True:
63             phone_num = generate_phone_num()
64             if not cls.db.exist(sql_template.format(phone_num)):
65                 return phone_num

 

posted @ 2022-03-21 13:17  WJ-HAHA  阅读(179)  评论(0编辑  收藏  举报