本文主要是慢慢积累Python中一些能提高效率的类库和装饰器,闲话少说,开始进入主题。
装饰器
装饰器是一种设计模式,用于修改或增强函数、方法或类的行为,而不需要改变其本身的代码。Python中的装饰器通常用@
符号和函数来实现。
# 自己编写的装饰器 def my_decorator(func):def wrapper():print("Something before")func()print("Something after")return wrapper# 引用自己编写的装饰器 @my_decorator def say_hello():print("Hello!")# 调用执行函数 say_hello()# 输出结果如下: Something before Hello! Something after
一、重试
【问题引申:接口网络抖动不稳如何做?回答:请求接口捕获异常和接口请求重试】
1 from retrying import retry 2 # 等待1秒后重试,最大重试次数为3 3 @retry(stop_max_attempt_number=3, wait_fixed=1000) 4 def test_foo(): 5 pass
二、接口返回值深度校验
【问题引申:接口返回值如何做校验?回答:用deepdiff可以做返回值类型及值不一致的校验】
1 from deepdiff import DeepDiff 2 def vaildate_json(expected, actual): 3 # 比较两个JSON对象的差异 4 diff = DeepDiff(expected, actual) 5 # 输出差异 6 if diff: 7 print("实际结果与预期结果不一致:") 8 print(diff) 9 return False 10 else: 11 print("实际结果与预期结果一致") 12 return True 13 14 # 需要比较的JSON对象 15 expected = { 16 "key1":33, 17 "key2":{ 18 "nested_key":"value", 19 "nested_list":[2,3,4] 20 } 21 } 22 actual = { 23 "key1":"33", 24 "key2":{ 25 "nested_key":"value", 26 "nested_list":[2,3,4] 27 } 28 } 29 # 调用函数进行比较 30 vaildate_json(expected,actual)
三、接口返回值取值:jsonpath
【问题引申:如何快速方便的获取json中的某一个值?回答:用jsonpath】
1 import jsonpath 2 actual = { 3 "key1":"33", 4 "key2":{ 5 "nested_key":"value", 6 "key1":"hankai", 7 "nested_list":[2,3,4] 8 } 9 } 10 list1 = jsonpath.jsonpath(actual,'$..key1') 11 print(list1) # ['33', 'hankai']
四、读取Excel并转换成列表:xToolkit
【问题引申:如何遍历Excel做接口自动化?回答:xToolkit库】
1 from xToolkit import xfile 2 3 # 读取Excel数据转换成列表 4 testdata = xfile.read("接口测试用例.xls").excel_to_dict(sheet=1) 5 print(testdata) 6 """ 7 [ 8 {'描述': '用户登录', '用例编号': 'shop_api_001', '接口URL': 'http://shoo.hu.com/index.php?s=api/user/login', '请求方式': 'post', 'URL参数': '{"application":"app","application_client_type": "weixin",}', '表单参数': '', 'JSON参数': ' {"accounts":"ce_hk","pwd": 123456,"type":"username"}', '预期状态码': 200, '预期返回内容': '', '备注': '', '提取参数': 'token', '需要参数': ''}, 9 {'描述': '加入购物车', '用例编号': 'shop_api_002', '接口URL': 'http://shoo.hu.com/index.php?s=api/cart/save', '请求方式': 'post', 'URL参数': '{"application":"app","application_client_type": "weixin",}', '表单参数': '', 'JSON参数': '{"goods_id": "2","spec": [{"type": "套餐","value": "套餐二"},{"type": "颜色","value": "银色"},{"type": "容量","value": "64G"}],"stock": 1}', '预期状态码': 200, '预期返回内容': '', '备注': '', '提取参数': '', '需要参数': 'token'} 10 ] 11 """
五、json
1 import json 2 3 # 定义一个字典 4 data = { 5 "name": "张三", 6 "age": 20, 7 "city": "北京" 8 } 9 json.dumps(data) # 字典编码成JSON字符串 10 json.loads(data) # JSON字符串解码为字典 11 12 json.dump(data, open("data.json", "w")) # 字典编码成JSON字符串并写入文件 13 json.load(open("data.json", "r")) # 从文件中读取JSON字符串并解码为字典
六、time
import time print(time.asctime()) # Wed Apr 24 17:33:12 2024 print(time.time()) # 1713951192.7047122 print(time.localtime()) # time.struct_time(tm_year=2018, tm_mon=8, tm_mday=8, tm_hour=12, tm_min=12, tm_sec=12, tm_wday=2, tm_yday=220, tm_isdst=0) print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 2024-04-24 17:33:12
import datetime# 获取当前时间 now = datetime.datetime.now() # 计算时间 start_time = now + datetime.timedelta(days=1) end_time = now + datetime.timedelta(days=30) # 格式化输出年月日时分秒 start_time = start_time.strftime("%Y-%m-%d %H:%M:%S") end_time = end_time.strftime("%Y-%m-%d %H:%M:%S") print("开始时间是:", start_time) 开始时间是: 2024-07-18 08:19:33 print("结束时间是:", end_time) 结束时间是: 2024-08-16 08:19:33
# 获取当前时间周一和周日 import datetime def get_current_week():monday, sunday = datetime.date.today(), datetime.date.today()one_day = datetime.timedelta(days=1)while monday.weekday() != 0:monday -= one_daywhile sunday.weekday() != 6:sunday += one_day# return monday, sunday# 返回时间字符串return datetime.datetime.strftime(monday, "%Y-%m-%d"), datetime.datetime.strftime(sunday, "%Y-%m-%d")print("周一是:",get_current_week()[0]) //周一是: 2024-07-22 print("周日是:",get_current_week()[1]) //周日是: 2024-07-28# 今天年月日 now = datetime.datetime.now().strftime("%Y-%m-%d") print(now) //打印今天的年月日# 日期获取周几 from datetime import datetime, timedelta def get_weekday(start_date, end_date, today_date):# 将日期字符串转换为日期对象start_date = datetime.strptime(start_date, "%Y-%m-%d")end_date = datetime.strptime(end_date, "%Y-%m-%d")today_date = datetime.strptime(today_date, "%Y-%m-%d")# 计算周一到周日的天数days_between = (end_date - start_date).days# 计算今天和周一之间的天数差days_from_monday = (today_date - start_date).days# 计算今天是周几,0代表周一,1代表周二,以此类推weekday = days_from_monday % 7# 返回周几的名称weekdays = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]return weekdays[weekday]# 示例 start_date = "2024-07-22" # 周一的日期 end_date = "2024-07-28" # 周日的日期 today_date = "2024-07-24" # 今天的日期print("今天是:", get_weekday(start_date, end_date, today_date)) //今天是: 周三
from datetime import datetime, timedelta def get_week_info():# 获取当前日期today = datetime.now()today_str = today.strftime("%Y-%m-%d")# 计算周一的日期monday = today - timedelta(days=today.weekday())monday_str = monday.strftime("%Y-%m-%d")# 计算周日的日期sunday = monday + timedelta(days=6)sunday_str = sunday.strftime("%Y-%m-%d")# 获取今天是周几,0代表周一,6代表周日weekday = today.weekday()weekday_name = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"][weekday]# 输出结果print(f"今天是:{weekday_name}")print(f"周一日期:{monday_str}")print(f"周日日期:{sunday_str}")# 返回所有信息return today_str, monday_str, sunday_str, weekday_nameget_week_info()打印结果如下: 今天是:周四 周一日期:2024-07-22 周日日期:2024-07-28
七、随机数生成
import random
# 生成10位随机数 print (''.join(str(random.choice(range(10))) for _ in range(10)))