1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # ************************************* 4 # @Time : 2019/7/1 5 # @Author : Zhang Fan 6 # @Desc : RobotFramework Library 7 # @File : MyKeyworks.py 8 # @Update : 2019/8/23 9 # ************************************* 10 from robot.api import logger 11 import configparser 12 import jsonpointer 13 import jsonpatch 14 import datetime 15 import chardet 16 import random 17 import string 18 import json 19 import time 20 21 22 class MyKeyword(object): 23 """ 24 =================================================================== 25 ===================== MyKeyword ====================== 26 =================================================================== 27 """ 28 @staticmethod 29 def detect_code(self, byte_string): 30 """检测字节串编码. 31 32 参数: 33 byte_string:字节串 34 35 示例: 36 | Detect Code | ${byte_string} | #返回字节串编码,比如'utf-8' | 37 """ 38 return chardet.detect(byte_string)['encoding'] 39 40 def get_config_value(self, cfg_path, section, name): 41 """获取配置文件中指定节点下的指定选项值. 42 43 参数: 44 cfg_path:配置文件路径 45 section:节点名 46 name:选项名 47 48 示例: 49 | Get Config Value | ${CURDIR}\\config.ini | service_info | address | 50 """ 51 cfg = configparser.ConfigParser() 52 cfg.read(cfg_path) 53 return cfg.get(section, name) 54 55 """ 56 =============================================================== 57 ===================== Json Handle ==================== 58 =============================================================== 59 """ 60 def parse_json(self, json_string): 61 """ 62 解析JSON文档并返回数据结构. 63 64 参数: 65 json_string:JSON文档 66 67 示例: 68 | ${result}= | Parse Json | [1, 2, 3] | 69 | Length Should Be | ${result} | 3 | 70 """ 71 try: 72 return json.loads(json_string) 73 except ValueError as e: 74 raise ValueError("Could not parse '%s' as JSON: %s" % (json_string, e)) 75 76 def stringify_json(self, data): 77 """ 78 将数据结构转换为包含其JSON字符串表示形式的字符串. 79 80 参数: 81 data:数据结构 82 83 示例: 84 | ${data} = | Create List | 1 2 3 | 85 | ${json_string}= | Stringify JSON | ${data} | 86 | Should Be Equal As Strings | ${json_string} | ["1", "2", "3"] | 87 """ 88 try: 89 return json.dumps(data, ensure_ascii=False) 90 except ValueError as e: 91 raise ValueError("Could not stringify '%r' to JSON: %s" % (data, e)) 92 93 def get_json_value(self, json_string, json_pointer): 94 """ 95 获取JSON中指定目标节点值. 96 97 参数: 98 json_string:JSON文档 99 json_pointer:JSON节点 100 101 示例: 102 | ${result}= | Get Json Value | {"foo": {"bar": [1,2,3]}} | /foo/bar | 103 | Should Be Equal | ${result} | [1, 2, 3] | | 104 """ 105 try: 106 json_string = json.loads(str(json_string)) 107 except: 108 json_string = eval(str(json_string)) 109 return jsonpointer.resolve_pointer(json_string, json_pointer) 110 111 def set_json_value(self, json_string, json_pointer, json_value): 112 """ 113 设置JSON中指定目标节点值. 114 115 参数: 116 json_string:JSON文档 117 json_pointer:JSON节点 118 json_value:JSON值 119 120 示例: 121 | ${result}= | Set Json Value | {"foo": {"bar": [1,2,3]}} | /foo | 12 | 122 | Should Be Equal | ${result} | {"foo": 12} | | | 123 """ 124 try: 125 json_string = json.loads(str(json_string)) 126 except: 127 json_string = eval(str(json_string)) 128 json_new = jsonpatch.apply_patch(json_string, [{'op': 'add', 'path': json_pointer, 129 'value': self.parse_json(json_value)}]) 130 return self.stringify_json(json_new) 131 132 133 """ 134 =================================================================== 135 ==================== DateTime Handle ===================== 136 =================================================================== 137 """ 138 def calc_time_diff(self, date1, date2=None, format_=''): 139 """计算与当前的时间差,返回秒数. 140 141 参数: 142 date: 日期字符串(支持多种日期格式,以及时间戳) 143 format_: 日期格式,默认为空 144 145 示例: 146 | Calc Time Diff | Jul 30, 2019 10:24:36 AM | 147 | Calc Time Diff | 2019-07-30T10:24:36Z | 148 | Calc Time Diff | 2019-07-30 10:24:36.000 | 149 | Calc Time Diff | 2019-07-30 10:24:36 | 150 | Calc Time Diff | 20190730102436 | 151 | Calc Time Diff | 1564453476000 | 152 """ 153 def format_date(date, format_=''): 154 if not format_: 155 if all(x in date for x in ['-', ' ', ':', '.']): 156 format_ = "%Y-%m-%d %H:%M:%S.%f" 157 elif all(x in date for x in ['-', 'T', ':', 'Z']): 158 format_ = "%Y-%m-%dT%H:%M:%SZ" 159 elif all(x in date for x in [' ', ',', ':']): 160 format_ = "%b %d, %Y %I:%M:%S %p" 161 elif all(x in date for x in ['-', ' ', ':']): 162 format_ = "%Y-%m-%d %H:%M:%S" 163 else: 164 format_ = "%Y%m%d%H%M%S" 165 try: 166 timestamp = time.mktime(time.strptime(date, format_)) 167 return int(timestamp * 1000) 168 except ValueError as e: 169 raise ValueError(e) 170 171 if not date2: 172 date2 = int(time.time() * 1000) 173 else: 174 date_string2 = str(date2).strip('b').strip('u').replace("'", '').replace('"', '') 175 date2 = format_date(date_string2, format_) 176 177 date_string1 = str(date1).strip('b').strip('u').replace("'", '').replace('"', '') 178 if not date_string1: 179 return date_string1 180 if date_string1.isdigit() and len(date_string1) == 13: 181 return int(abs(date2 - int(date_string1))/1000) 182 date1 = format_date(date_string1, format_) 183 return int(abs(date2 - date1)/1000) 184