接口自动化框架里常用的小工具

开发
在日常编程工作中,我们常常需要处理各种与时间、数据格式及配置文件相关的问题。本文整理了一系列实用的Python代码片段,涵盖了日期时间转换、数据格式化与转换、获取文件注释以及读取配置文件等内容,助力开发者提升工作效率,轻松应对常见任务。

在日常编程工作中,我们常常需要处理各种与时间、数据格式及配置文件相关的问题。本文整理了一系列实用的Python代码片段,涵盖了日期时间转换、数据格式化与转换、获取文件注释以及读取配置文件等内容,助力开发者提升工作效率,轻松应对常见任务。

1. 秒级与毫秒级时间戳获取

# 获取当前秒级时间戳
def millisecond(add=0):
    return int(time.time()) + add
# 获取当前毫秒级时间戳
def millisecond_new():
    t = time.time()
    return int(round(t * 1000))

这两个函数分别提供了获取当前时间的秒级和毫秒级时间戳的功能。millisecond()函数允许传入一个可选参数add,用于增加指定的时间偏移量。

2. 当前日期字符串获取

#获取当前时间日期: 20211009
def getNowTime(tianshu=0):
shijian = int(time.strftime('%Y%m%d')) - tianshu
print(shijian)
return shijian

getNowTime()函数返回当前日期(格式为YYYYMMDD),并支持传入参数tianshu以减去指定天数。该函数适用于需要处理日期型数据且仅关注年月日的情况。

3.修复接口返回无引号JSON数据

def json_json():
    with open("源文件地址", "r") as f, open("目标文件地址", "a+") as a:
        a.write("{")
        for line in f.readlines():
            if "[" in line.strip() or "{" in line.strip():
                formatted_line = "'" + line.strip().replace(":", "':").replace(" ", "") + ","
                print(formatted_line)  # 输出修复后的行
                a.write(formatted_line + "\n")
            else:
                formatted_line = "'" + line.strip().replace(":", "':'").replace(" ", "") + "',"
                print(formatted_line)  # 输出修复后的行
                a.write(formatted_line + "\n")
        a.write("}")

此函数用于处理从接口复制的未正确格式化的JSON数据,修复缺失的引号,并将其写入新的文件。源文件与目标文件的路径需替换为实际路径。

4.将URL查询字符串转为JSON

from urllib.parse import urlsplit, parse_qs
def query_json(url):
    query = urlsplit(url).query
    params = dict(parse_qs(query))
    cleaned_params = {k: v[0] for k, v in params.items()}
    return cleaned_params

query_json()函数接收一个包含查询字符串的URL,解析其查询部分,将其转换为字典形式,并清理多值参数,只保留第一个值。

5.文件注释提取

import os
def get_first_line_comments(directory, output_file):
    python_files = sorted([f for f in os.listdir(directory) if f.endswith('.py') and f != '__init__.py'])
    comments_and_files = []
    for file in python_files:
        filepath = os.path.join(directory, file)
        with open(filepath, 'r', encoding='utf-8') as f:
            first_line = f.readline().strip()
            if first_line.startswith('#'):
                comment = first_line[1:].strip()
                comments_and_files.append((file, comment))
    with open(output_file, 'w', encoding='utf-8') as out:
        for filename, comment in comments_and_files:
            out.write(f"{filename}: {comment}\n")
# 示例用法
get_first_line_comments('指定文件夹', '指定生成文件路径.txt')
get_first_line_comments()函数遍历指定目录下的.py文件,提取每份文件的第
一行注释(以#开头),并将文件名与注释对应关系写入指定的文本文件中。

6.读取配置INI文件

import sys
import os
import configparser
class ReadConfig:
    def __init__(self, config_path):
        self.path = config_path
    def read_sqlConfig(self, fileName="sql.ini"):
        read_mysqlExecuteCon = configparser.ConfigParser()
        read_mysqlExecuteCon.read(os.path.join(self.path, fileName), encoding="utf-8")
        return read_mysqlExecuteCon._sections
    def read_hostsConfig(self, fileName="hosts.ini"):
        read_hostsCon = configparser.ConfigParser()
        read_hostsCon.read(os.path.join(self.path, fileName), encoding="utf-8")
        return read_hostsCon._sections
# 示例用法
config_reader = ReadConfig('配置文件所在路径')
sql_config = config_reader.read_sqlConfig()
hosts_config = config_reader.read_hostsConfig()["hosts"]
ReadConfig类封装了对INI配置文件的读取操作,支持读取sql.ini和hosts.ini文件。通过实例化该类并指定配置文件路径,即可方便地获取所需配置信息。

7.设置全局文件路径

import os
def setFilePath(filePath):
    current_module_path = os.path.dirname(os.path.abspath(__file__))
    project_root_path = os.path.dirname(os.path.dirname(current_module_path))
    path = os.path.join(project_root_path, filePath.lstrip('/'))
    return os.path.abspath(path)
# 示例用法
confPath = setFilePath("地址文件路径")

setFilePath()函数根据提供的相对路径,结合当前模块的绝对路径,计算出项目根目录下的目标文件或目录的绝对路径,便于在项目中统一管理资源位置。

责任编辑:华轩 来源: 测试开发学习交流
相关推荐

2012-03-15 10:32:05

Windows系统网络故障

2022-08-29 10:11:28

PDFWord自动化工具

2023-09-13 11:40:12

2024-02-28 16:04:04

深拷贝Python

2022-05-16 09:20:00

开发工具

2009-11-19 08:48:10

Windows 7桌面工具

2010-07-01 10:24:30

UML小工具

2009-12-08 14:02:25

Windows 7小工

2022-04-11 15:34:29

机器学习AutoML开源

2022-05-22 07:29:24

工具插件客户端软件

2013-03-29 14:46:33

App开发小工具辅助工具

2010-05-19 19:10:42

2022-08-05 22:15:26

Python自动化测试

2011-03-10 09:03:35

Python

2011-04-12 12:53:17

2020-11-26 12:05:44

Python小工具代码

2021-11-05 06:57:50

架构工具代码

2021-05-20 11:30:17

Python工具代码

2021-05-10 11:06:31

Python工具代码

2020-02-14 11:00:59

开发者技能工具
点赞
收藏

51CTO技术栈公众号