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 "" " detection coding octet string. 31 is 32 Parameters: 33 is byte_string: byte string 34 is 35 Example: 36 | Detect Code | $ byte_string {} | # of bytes returned coding sequence, such as 'UTF-. 8' | 37 [ "" " 38 is return chardet.detect (byte_string) [ ' encoding ' ] 39 40 DEF get_config_value (Self, cfg_path, sectionTop, name): 41 is " "" Get specified in the profile option values specified node. 42 43 parameters: 44 is cfg_path: Profile Path 45 sectionTop: node name 46 is name: Option name 47 48 Example: 49 | Config the Get the Value | $ {} \\ the CURDIR the config.ini | SERVICE_INFO | address | 50 "" " 51 is CFG = configparser.ConfigParser () 52 is cfg.read (cfg_path) 53 is return cfg.get (sectionTop, name) 54 is 55 "" " 56 is ========================= ====================================== 57 =========== Json the Handle ==================== ========== 58 ================================================== ============= 59 "" " 60 DEF parse_json (Self, json_string): 61 is " "" 62 is parse the document and returns the data structure of JSON. 63 is 64 parameters: 65 json_string: JSON document 66 67 example: 68 | $ {Result} = | the Parse Json | [. 1, 2,. 3] | 69 | Should the Length of Be | $ {Result} |. 3 | 70 "" " 71 is the try : 72 return json.loads (json_string) 73 is the except a ValueError AS E: 74 The raise a ValueError ( " Could Not the parse '% S' AS JSON:% S " % (json_string, E)) 75 76 DEF stringify_json (Self, Data): 77 "" " 78 to convert the data structure containing the string representation thereof JSON . in the form of a string of 79 80 parameters: 81 data: data structure 82 83 example: 84 | $ {data} = | the Create List | 2. 1. 3 | 85 | $ json_string} = {| stringify the JSON | $ {data} | 86 | Should Be Equal As Strings | $ {json_string} | [ "1", "2", "3"] | 87 "" " 88 the try : 89 return json.dumps (Data, ensure_ascii = False) 90 the except a ValueError AS E: 91 is The raise a ValueError ( " Could Not the stringify 'R & lt%' to the JSON:% S " % (Data, E)) 92 93 DEF get_json_value (Self, json_string, json_pointer): 94 "" " 95 acquires the specified target node value in JSON. 96 97 parameters: 98 json_string: JSON document 99 json_pointer: JSON node 100 101 example: 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 "" " calculating the difference between the current time and returns the number of seconds. 140 141 is Parameters: 142 DATE: date string (support multiple date formats, and time stamp) 143 format_: date format, default is empty 144 145 example: 146 | Time Calc Diff | Jul-30, 2019 10:24:36 AM | 147 | Time Calc 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 185 def generate_guid(self): 186 """随机生成GUID字符串.""" 187 def _random(num): 188 return ''.join(random.sample(string.ascii_uppercase + string.digits, num)) 189 guid = '-'.join([_random(8), _random(4), _random(4), _random(4), _random(12)]) 190 return guid 191 192 193 if __name__ == '__main__': 194 print('This is test.') 195 mk = MyKeyword()