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

2024软件测试面试刷题,这个小程序(永久刷题),靠它快速找到工作了!(刷题APP的天花板)_软件测试刷题小程序-优快云博客文章浏览阅读3k次,点赞86次,收藏13次。你知不知道有这么一个软件测试面试的刷题小程序。里面包含了面试常问的软件测试基础题,web自动化测试、app自动化测试、接口测试、性能测试、自动化测试、安全测试及一些常问到的人力资源题目。最主要的是他还收集了像阿里、华为这样的大厂面试真题,还有互动交流板块……_软件测试刷题小程序​编辑https://blog.youkuaiyun.com/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.youkuaiyun.com/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.youkuaiyun.com/AI_Green/article/details/134931243?spm=1001.2014.3001.5502https://blog.youkuaiyun.com/AI_Green/article/details/134931243?spm=1001.2014.3001.5502https://blog.youkuaiyun.com/AI_Green/article/details/134931243?spm=1001.2014.3001.5502https://blog.youkuaiyun.com/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.youkuaiyun.com/AI_Green/article/details/134931243?spm=1001.2014.3001.5502https://blog.youkuaiyun.com/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.youkuaiyun.com/AI_Green/article/details/134931243?spm=1001.2014.3001.5502https://blog.youkuaiyun.com/AI_Green/article/details/134931243?spm=1001.2014.3001.5502https://blog.youkuaiyun.com/AI_Green/article/details/134931243?spm=1001.2014.3001.5502icon-default.png?t=N7T8https://blog.youkuaiyun.com/AI_Green/article/details/134931243?spm=1001.2014.3001.5502

在日常编程工作中,我们常常需要处理各种与时间、数据格式及配置文件相关的问题。本文整理了一系列实用的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()函数根据提供的相对路径,结合当前模块的绝对路径,计算出项目根目录下的目标文件或目录的绝对路径,便于在项目中统一管理资源位置。

行动吧,在路上总比一直观望的要好,未来的你肯定会感谢现在拼搏的自己!如果想学习提升找不到资料,没人答疑解惑时,请及时加入群: 759968159,里面有各种测试开发资料和技术可以一起交流哦。

最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】

软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值