You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求推荐可生成多类型随机数据的Python Fuzzing(模糊测试)库

适合生成多类型随机测试数据的Python模糊测试库推荐

针对你需要给add_two_numbers函数的参数生成整数、字符串、字母数字等随机值的需求,以下是几款实用的Python库:

1. Faker

专门用于生成贴近真实场景的各类假数据,支持整数、字符串、字母数字、日期等几十种数据类型,用法简单直观。
示例代码:

from faker import Faker
fake = Faker()

# 生成随机整数、字符串、字母数字组合
def test_add_two_numbers():
    for _ in range(100):
        x = fake.random_int(min=-1000, max=1000)
        y = fake.text(max_nb_chars=10)
        # 或者生成字母数字组合
        y = fake.bothify(text='??###')
        try:
            result = add_two_numbers(x, y)
            print(f"输入x={x}, y={y},结果:{result}")
        except Exception as e:
            print(f"输入x={x}, y={y}时出错:{e}")

2. Hypothesis

一款基于属性的测试框架,属于模糊测试范畴,能自动生成符合指定类型的随机数据,还会在测试失败时自动缩小案例,帮助定位问题。
示例代码:

from hypothesis import given
import hypothesis.strategies as st

@given(x=st.integers(), y=st.text() | st.alphanumeric())
def test_add_two_numbers_hypothesis(x, y):
    try:
        result = add_two_numbers(x, y)
        print(f"输入x={x}, y={y},结果:{result}")
    except Exception as e:
        print(f"输入x={x}, y={y}时出错:{e}")

test_add_two_numbers_hypothesis()

3. Atheris

Google开发的模糊测试库,支持生成任意类型的随机数据,可与libFuzzer集成,适合深入的代码安全性测试,也能满足基础的多类型数据生成需求。
示例代码:

import atheris
import sys

def test_add_two_numbers_atheris(data):
    fdp = atheris.FuzzedDataProvider(data)
    x = fdp.ConsumeInt(32)
    y = fdp.ConsumeString(10)
    try:
        result = add_two_numbers(x, y)
        print(f"输入x={x}, y={y},结果:{result}")
    except Exception as e:
        print(f"输入x={x}, y={y}时出错:{e}")

atheris.Setup(sys.argv, test_add_two_numbers_atheris)
atheris.Fuzz()

这些库都能满足你生成多类型随机测试数据的需求,其中Faker适合生成贴近真实的假数据,Hypothesis侧重属性测试与案例缩小,Atheris则更适合深度模糊测试场景。

内容的提问来源于stack exchange,提问作者Rajiv Bhalla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 12:45:36