当前位置: 首页 > news >正文

27. 自动化测试开发框架拓展之测试数据构造(一)

Python测试数据生成器深度解析

一、核心功能模块

1.1 基础数据生成

from faker import Factory
fake = Factory().create('zh_CN')  # 🌐 创建中文数据生成器def random_python_data():return fake.pystr(), \        # 📍 随机字符串(长度20)fake.pyint(), \           # 🔢 随机整数(-9999~9999)fake.pybool(), \          # ✅ 随机布尔值fake.pyfloat(), \         # 🎯 随机浮点数(正负皆可)fake.pytuple(nb_elements=2), \  # 🧩 2元素元组fake.pylist(nb_elements=2), \   # 📋 2元素列表fake.pydict(nb_elements=2)      # 📖 2键值对字典# 示例输出:
# ('qZRjvJgGQJTwIuNyKlOs', 7352, False, -183.42, 
#  (True, 'test'), [327, 'data'], {'field': 0.57, 'key': 'value'})

1.2 标识符与文本生成

def random_uuid():return fake.uuid4()  # 🔑 标准UUID格式def random_text():return fake.text()  # 📝 生成随机段落(默认200字符)def random_word():return fake.word(), fake.words()  # 🔠 返回(单词,单词列表)# 示例输出:
# UUID: a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11
# 文本: 决定经验运行.但是当前有关...
# 词组: ('建设', ['虽然', '图片'])

二、系统安全相关数据

2.1 文件路径生成

def random_image_url():return fake.image_url()  # 🌐 生成图片URLdef random_file_path():return fake.file_path()  # 📂 生成随机文件路径# 示例输出:
# 图片URL: https://dummyimage.com/250x250
# 文件路径: /path/to/file.txt

2.2 系统信息模拟

def random_os_info(os_type: str = 'win'):if os_type == 'win':return f"{fake.windows_platform_token()} {fake.linux_processor()}"# ...其他系统类型处理...# 示例输出:
# Windows 7 Home Premium x64 Edition build 7600 Intel Core i7

2.3 加密数据生成

def random_hash(raw_output: bool = False):return {'md5': fake.md5(raw_output),      # 🔒 32位十六进制'sha1': fake.sha1(raw_output),    # 🔐 40位十六进制'sha256:': fake.sha256(raw_output)  # ⚠️ 键名应为sha256}# 示例输出:
# {'md5': '5d41402abc4b2a76b9719d911017c592', 
#  'sha1': 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d',
#  'sha256:': '2cf24dba5fb0a30e26e83b2ac...'}

三、安全密码生成

3.1 密码生成函数

def random_password(length=10, special_chars=True, digits=True, upper_case=True, lower_case=True):return fake.password(length=length,               # 密码长度special_chars=special_chars, # 包含特殊字符digits=digits,               # 包含数字upper_case=upper_case,       # 包含大写字母lower_case=lower_case        # 包含小写字母)# 示例输出:
# 基础密码:A3m#pL9$q2
# 纯数字密码:4958271630(special_chars=False)

四、代码优化建议

4.1 现存问题清单

问题描述风险等级改进建议
SHA256键名多余冒号修正键名为’sha256’
未处理非法os_type参数添加默认值或异常抛出
文件路径使用硬编码分隔符使用os.path模块处理路径

4.2 改进代码示例

# 增强型OS信息生成
def random_os_info(os_type: str = 'win'):system_map = {'win': lambda: f"{fake.windows_platform_token()} {fake.linux_processor()}",'linux': fake.linux_processor,'mac': fake.mac_platform_token,'ios': fake.ios_platform_token,'android': fake.android_platform_token}return system_map.get(os_type.lower(), lambda: 'Unknown OS')()

五、企业级最佳实践

来自金融行业测试规范的要求

  1. 敏感数据(密码/HASH)必须进行脱敏处理
  2. 测试数据生成器需要与业务环境隔离
  3. 密码复杂度应符合PCI DSS标准:
    • 最小长度12位
    • 必须包含大小写字母+数字+特殊字符
    • 禁止使用连续字符(如1234、abcd)
  4. 使用加密存储测试数据
  5. 每个测试用例的数据必须可追溯(添加生成时间戳和版本号)
# 符合企业规范的密码生成
def enterprise_password():return fake.password(length=12,special_chars=True,digits=True,upper_case=True,lower_case=True,base_symbols='!@#$%^&*_=+-') + f'_{datetime.now().strftime("%Y%m%d")}'  # 添加日期标记

六、完整代码

"""
Python :3.13.3
Selenium: 4.31.0generator.py
"""# 数据类(构造常用数据类型、UUID、文本、词组、文件链接、文件路径)
# 安全类(构造操作系统信息、HASH加密、密码)
# 信息类(构造个人信息数据和表单信息数据:姓名、地址、电话、工作、证件号、银行卡号、公司)
# 网络类(构造IP MAC HTTP的客户端类型和文件类型,反反爬from faker import Factoryfake = Factory().create('zh_CN')# 常用数据类型
def random_python_data():return fake.pystr(), \fake.pyint(), \fake.pybool(), \fake.pyfloat(), \fake.pytuple(nb_elements=2), \fake.pylist(nb_elements=2), \fake.pydict(nb_elements=2)# UUID
def random_uuid():return fake.uuid4()# 文本
def random_text():return fake.text()# 词组
def random_word():return fake.word(), fake.words()# 文件链接
def random_image_url():return fake.image_url()# 文件路径
def random_file_path():return fake.file_path()# 构造操作系统信息
def random_os_info(os_type: str = 'win'):if os_type == 'win':return fake.windows_platform_token() + ' ' + fake.linux_processor()if os_type == 'linux':return fake.linux_processor()if os_type == 'mac':return fake.mac_platform_token()if os_type == 'ios':return fake.ios_platform_token()if os_type == 'android':return fake.android_platform_token()return None# 构造哈希值
def random_hash(raw_output: bool = False):return {'md5': fake.md5(raw_output), 'sha1': fake.sha1(raw_output), 'sha256:': fake.sha256(raw_output)}# 构造密码
def random_password(length=10, special_chars=True, digits=True, upper_case=True, lower_case=True):return fake.password(length=length,special_chars=special_chars,digits=digits,upper_case=upper_case,lower_case=lower_case)print(random_password())

「小贴士」:点击头像→【关注】按钮,获取更多软件测试的晋升认知不迷路! 🚀

http://www.xdnf.cn/news/635185.html

相关文章:

  • uniapp-商城-68-shop(1-商品列表,获取数据,utils、tofixed 、parseInt的使用)
  • 【b站计算机拓荒者】【2025】微信小程序开发教程 - chapter2 小程序核心
  • STM32八股【11】-----Linux Bootloader (U-Boot)
  • 嵌入式STM32学习—— 定时器中断(应用-利用定时器中断实现LED亮一秒灭一秒)
  • Q1:Go协程、Channel通道 被close后,读会带来什么问题?
  • ABP VNext + Webhook:订阅与异步回调
  • 6个跨境电商独立站平台
  • C++23 元编程工具新特性探索
  • 开发AR导航助手:ARKit+Unity+Mapbox全流程实战教程
  • 【Python 命名元祖】collections.namedtuple 学习指南
  • 反序列化之Wakeup方法绕过
  • Dify 本地源码安装教程
  • 【漫话机器学习系列】277.梯度裁剪(Gradient Clipping)
  • Redis数据安全分析
  • Java——优先级队列(堆)
  • 前沿探索之Kuikly框架
  • Java 虚拟机(JVM)原理与实战:打造高效稳定的运行环境
  • YOLOV8涨点技巧之空间通道协作注意力(SCCA)-应用于自动驾驶领域
  • 【公式】MathType公式右编号对齐
  • C/C++ 结构体:. 与 -> 的区别与用法及其STM32中的使用
  • 2025.5.25总结
  • Windows 11 [close recent file browsing history]
  • 对WireShark 中的UDP抓包数据进行解析
  • win11 禁用/恢复 内置笔记本键盘(保证管用)
  • 嵌入式软件--DAY8 IIC通讯下 硬件实现
  • 解决WPF短暂的白色闪烁(白色闪屏)
  • 从智能提效到产品赋能的架构实践
  • Pycharm and Flask 的学习心得(9)
  • PCB 通孔是电容性的,但不一定是电容器
  • CSS相关知识