Python 介面自動化常用方法封裝
阿新 • • 發佈:2020-12-14
技術標籤:軟體測試自動化測試Pythonpython軟體測試自動化測試
#!/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自動化、介面、框架搭建學習資料!技術大牛解惑答疑,同行一起交流。