自动化测试元素定位不到问题,该如何解决?

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

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

  1. # 获取当前秒级时间戳

  2. def millisecond(add=0):

  3. return int(time.time()) + add

  4. # 获取当前毫秒级时间戳

  5. def millisecond_new():

  6. t = time.time()

  7. return int(round(t * 1000))

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

2. 当前日期字符串获取

# 获取当前时间日期: 20211009

  1. def getNowTime(tianshu=0):

  2. shijian = int(time.strftime('%Y%m%d')) - tianshu

  3. print(shijian)

  4. return shijian

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

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

  1. def json_json():

  2. with open("源文件地址", "r") as f, open("目标文件地址", "a+") as a:

  3. a.write("{")

  4. for line in f.readlines():

  5. if "[" in line.strip() or "{" in line.strip():

  6. formatted_line = "'" + line.strip().replace(":", "':").replace(" ", "") + ","

  7. print(formatted_line) # 输出修复后的行

  8. a.write(formatted_line + "\n")

  9. else:

  10. formatted_line = "'" + line.strip().replace(":", "':'").replace(" ", "") + "',"

  11. print(formatted_line) # 输出修复后的行

  12. a.write(formatted_line + "\n")

  13. a.write("}")

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

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

  1. from urllib.parse import urlsplit, parse_qs

  2. def query_json(url):

  3. query = urlsplit(url).query

  4. params = dict(parse_qs(query))

  5. cleaned_params = {k: v[0] for k, v in params.items()}

  6. return cleaned_params

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

5.文件注释提取​​​​​​​

  1. import os

  2. def get_first_line_comments(directory, output_file):

  3. python_files = sorted([f for f in os.listdir(directory) if f.endswith('.py') and f != '__init__.py'])

  4. comments_and_files = []

  5. for file in python_files:

  6. filepath = os.path.join(directory, file)

  7. with open(filepath, 'r', encoding='utf-8') as f:

  8. first_line = f.readline().strip()

  9. if first_line.startswith('#'):

  10. comment = first_line[1:].strip()

  11. comments_and_files.append((file, comment))

  12. with open(output_file, 'w', encoding='utf-8') as out:

  13. for filename, comment in comments_and_files:

  14. out.write(f"{filename}: {comment}\n")

  15. # 示例用法

  16. get_first_line_comments('指定文件夹', '指定生成文件路径.txt')

  17. get_first_line_comments()函数遍历指定目录下的.py文件,提取每份文件的第

一行注释(以#开头),并将文件名与注释对应关系写入指定的文本文件中。

6.读取配置INI文件​​​​​​​

  1. import sys

  2. import os

  3. import configparser

  4. class ReadConfig:

  5. def __init__(self, config_path):

  6. self.path = config_path

  7. def read_sqlConfig(self, fileName="sql.ini"):

  8. read_mysqlExecuteCon = configparser.ConfigParser()

  9. read_mysqlExecuteCon.read(os.path.join(self.path, fileName), encoding="utf-8")

  10. return read_mysqlExecuteCon._sections

  11. def read_hostsConfig(self, fileName="hosts.ini"):

  12. read_hostsCon = configparser.ConfigParser()

  13. read_hostsCon.read(os.path.join(self.path, fileName), encoding="utf-8")

  14. return read_hostsCon._sections

  15. # 示例用法

  16. config_reader = ReadConfig('配置文件所在路径')

  17. sql_config = config_reader.read_sqlConfig()

  18. hosts_config = config_reader.read_hostsConfig()["hosts"]

ReadConfig类封装了对INI配置文件的读取操作,支持读取sql.ini和hosts.ini文件。通过实例化该类并指定配置文件路径,即可方便地获取所需配置信息。

7.设置全局文件路径​​​​​​​

  1. import os

  2. def setFilePath(filePath):

  3. current_module_path = os.path.dirname(os.path.abspath(__file__))

  4. project_root_path = os.path.dirname(os.path.dirname(current_module_path))

  5. path = os.path.join(project_root_path, filePath.lstrip('/'))

  6. return os.path.abspath(path)

  7. # 示例用法

  8. confPath = setFilePath("地址文件路径")

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

感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

 

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!有需要的小伙伴可以点击下方小卡片领取   

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值