#!/usr/bin/env python
# -*- coding:utf-8 -*-
# *************************************
# @Time : 2019/7/1
# @Author : Zhang Fan
# @Desc : RobotFramework Library
# @File : MyKeyworks.py
# @Update : 2019/8/23
# *************************************
from robot.api import logger
import configparser
import jsonpointer
import jsonpatch
import datetime
import chardet
import random
import string
import json
import time
class MyKeyword(object):
"""
===================================================================
===================== MyKeyword ======================
===================================================================
"""
@staticmethod
def detect_code(self, byte_string):
"""检测字节串编码.
参数:
byte_string:字节串
示例:
| Detect Code | ${
byte_string} | #返回字节串编码,比如'utf-8' |
"""
return chardet.detect(byte_string)['encoding']
def get_config_value(self, cfg_path, section, name):
"""获取配置文件中指定节点下的指定选项值.
参数:
cfg_path:配置文件路径
section:节点名
name:选项名
示例:
| Get Config Value | ${
CURDIR}\\config.ini | service_info | address |
"""
cfg = configparser.ConfigParser()
cfg.read(cfg_path)
return cfg.get(section, name)
"""
===============================================================
===================== Json Handle ====================
===============================================================
"""
def parse_json(self, json_string):
"""
解析JSON文档并返回数据结构.
参数:
json_string:JSON文档
示例:
| ${
result}= | Parse Json | [1, 2, 3] |
| Length Should Be | ${
result} | 3 |
"""
try:
return json.loads(json_string)
except ValueError as e:
raise ValueError("Could not parse '%s' as JSON: %s" % (json_string, e))
def stringify_json(self, data):
"""
将数据结构转换为包含其JSON字符串表示形式的字符串.
参数:
data:数据结构
示例:
| ${
data} = | Create List | 1 2 3 |
| ${
json_string}= | Stringify JSON | ${
data} |
| Should Be Equal As Strings | ${
json_string} | ["1", "2", "3"] |
"""
try:
return json.dumps(data, ensure_ascii=False)
except ValueError as e:
raise ValueError("Could not stringify '%r' to JSON: %s" % (data, e))
def get_json_value(self, json_string, json_pointer):
"""
获取JSON中指定目标节点值.
参数:
json_string:JSON文档
json_pointer:JSON节点
示例:
| ${
result}= | Get Json Value | {
"foo": {
"bar": [1,2,3]}} | /foo/bar |
| Should Be Equal | ${
result} | [1, 2, 3] | |
"""
try:
json_string = json.loads(str(json_string))
except:
json_string = eval(str(json_string))
return jsonpointer.resolve_pointer(json_string, json_pointer)
def set_json_value(self, json_string, json_pointer, json_value):
"""
设置JSON中指定目标节点值.
参数:
json_string:JSON文档
json_pointer:JSON节点
json_value:JSON值
示例:
| ${
result}= | Set Json Value | {
"foo": {
"bar": [1,2,3]}} | /foo | 12 |
| Should Be Equal | ${
result} | {
"foo": 12} | | |
"""
try:
json_string = json.loads(str(json_string))
except:
json_string = eval(str(json_string))
json_new = jsonpatch.apply_patch(json_string, [{
'op': 'add', 'path': json_pointer,
'value': self.parse_json(json_value)}])
return self.stringify_json(json_new)
"""
===================================================================
==================== DateTime Handle =====================
===================================================================
"""
def calc_time_diff(self, date1, date2=None, format_=''):
"""计算与当前的时间差,返回秒数.
参数:
date: 日期字符串(支持多种日期格式,以及时间戳)
format_: 日期格式,默认为空
示例:
| Calc Time Diff | Jul 30, 2019 10:24:36 AM |
| Calc Time Diff | 2019-07-30T10:24:36Z |
| Calc Time Diff | 2019-07-30 10:24:36.000 |
| Calc Time Diff | 2019-07-30 10:24:36 |
| Calc Time Diff | 20190730102436 |
| Calc Time Diff | 1564453476000 |
"""
def format_date(date, format_=''):
if not format_:
if all(x in date for x in ['-', ' ', ':', '.']):
format_ = "%Y-%m-%d %H:%M:%S.%f"
elif all(x in date for x in ['-', 'T', ':', 'Z']):
format_ = "%Y-%m-%dT%H:%M:%SZ"
elif all(x in date for x in [' ', ',', ':']):
format_ = "%b %d, %Y %I:%M:%S %p"
elif all(x in date for x in ['-', ' ', ':']):
format_ = "%Y-%m-%d %H:%M:%S"
else:
format_ = "%Y%m%d%H%M%S"
try:
timestamp = time.mktime(time.strptime(date, format_))
return int(timestamp * 1000)
except ValueError as e:
raise ValueError(e)
if not date2:
date2 = int(time.time() * 1000)
else:
date_string2 = str(date2).strip('b').strip('u').replace("'", '').replace('"', '')
date2 = format_date(date_string2, format_)
date_string1 = str(date1).strip('b').strip('u').replace("'", '').replace('"', '')
if not date_string1:
return date_string1
if date_string1.isdigit() and len(date_string1) == 13:
return int(abs(date2 - int(date_string1))/1000)
date1 = format_date(date_string1, format_)
return int(abs(date2 - date1)/1000)
希望本文对你有所帮助~~如果对软件测试、接口测试、自动化测试、面试经验交流感兴趣可以加入我们。642830685,免费领取最新软件测试大厂面试资料和Python自动化、接口、框架搭建学习资料!技术大牛解惑答疑,同行一起交流。