| name | fuzzing-input-generator |
| description | Generate randomized and edge-case inputs to detect unexpected failures, bugs, and security vulnerabilities through fuzz testing. Use when creating test cases for robustness testing, generating adversarial inputs, testing error handling, finding edge cases, or security testing. Produces Python test code with fuzzing inputs for strings, numbers, and structured data focusing on edge cases, invalid inputs, and random valid inputs. Triggers when users ask to generate fuzz tests, create randomized test inputs, test edge cases, find bugs through fuzzing, or generate adversarial test cases. |
Fuzzing Input Generator
Overview
Generate comprehensive fuzz testing inputs to uncover bugs, crashes, and security vulnerabilities by systematically testing functions with edge cases, invalid inputs, and randomized data.
Workflow
1. Analyze the Target Function
Understand what needs to be fuzzed:
Identify input types:
- Strings (text, paths, URLs, etc.)
- Numbers (integers, floats)
- Booleans
- Collections (lists, dicts, sets)
- Structured data (JSON, XML)
- Files or binary data
- Combinations of above
Understand expected behavior:
- What are valid inputs?
- What should happen with invalid inputs?
- Are there documented constraints?
- What error handling exists?
Extract function signature:
def process_user_input(name: str, age: int, email: str) -> dict:
"""Process user registration data."""
2. Select Fuzzing Strategy
Choose appropriate fuzzing approaches:
Edge Case Fuzzing
Test boundary conditions and special values:
- Empty inputs
- Very large inputs
- Minimum/maximum values
- Zero, negative numbers
- Special characters
- Null/None values
Invalid Input Fuzzing
Test with malformed or incorrect data:
- Wrong types
- Invalid formats
- Out-of-range values
- Malformed structures
- Encoding issues
Random Valid Fuzzing
Generate random but technically valid inputs:
- Random strings of various lengths
- Random numbers in valid ranges
- Random but well-formed structures
- Valid but unusual combinations
Security Fuzzing
Test for vulnerabilities:
- Injection attacks (SQL, command, XSS)
- Path traversal
- Buffer overflows
- Format string attacks
- Unicode exploits
3. Generate Fuzz Test Code
Create Python test functions with fuzzing inputs.
Basic Template
import pytest
import random
import string
def fuzz_<function_name>():
"""Fuzz test for <function_name>."""
edge_cases = [
]
invalid_inputs = [
]
def generate_random_valid():
pass
for input_data in edge_cases:
try:
result = function_under_test(input_data)
except Exception as e:
pass
for input_data in invalid_inputs:
pass
for _ in range(100):
random_input = generate_random_valid()
4. Generate Input Categories
Create comprehensive input sets for each parameter type. See fuzzing-patterns.md for extensive patterns.
String Inputs
def generate_string_fuzz_inputs():
"""Generate fuzz inputs for string parameters."""
return [
"",
" ",
" ",
"\t",
"\n",
"\r\n",
"a",
"a" * 100,
"a" * 10000,
"a" * 1000000,
"!@#$%^&*()",
"'",
"\"",
"\\",
"<script>alert(1)</script>",
"🔥",
"你好",
"مرحبا",
"'; DROP TABLE users--",
"../../../etc/passwd",
"${var}",
"%s%s%s",
"{0}{1}{2}",
"\x00",
"test\x00test",
]
Number Inputs
def generate_number_fuzz_inputs():
"""Generate fuzz inputs for numeric parameters."""
return [
0,
1,
-1,
2**31 - 1,
-2**31,
2**63 - 1,
-2**63,
0.0,
-0.0,
float('inf'),
float('-inf'),
float('nan'),
1e308,
1e-308,
0.1 + 0.2,
None,
"123",
"not a number",
[],
{},
]
Structured Data Inputs
def generate_json_fuzz_inputs():
"""Generate fuzz inputs for JSON/dict parameters."""
return [
{},
[],
None,
{"number": "123"},
{"bool": "true"},
{"array": "[]"},
{"a": {"b": {"c": {"d": {"e": "deep"}}}}},
[[[[["nested"]]]]],
{f"key{i}": i for i in range(1000)},
[i for i in range(10000)],
{"": "empty key"},
{"key with spaces": "value"},
{"key.with.dots": "value"},
{"str": "text", "num": 123, "bool": True, "null": None, "arr": [1, 2]},
,
,
,
]
5. Write Complete Test Functions
Generate executable test code:
Example 1: String Processing Function
import pytest
import random
import string
def test_fuzz_process_username():
"""Fuzz test for username processing."""
def process_username(username: str) -> str:
"""Function under test."""
if not username:
raise ValueError("Username cannot be empty")
if len(username) > 50:
raise ValueError("Username too long")
return username.strip().lower()
edge_cases = [
"",
" ",
"a",
"A" * 50,
"A" * 51,
" user ",
"User123",
"user@name",
"user\nname",
"🔥user",
"\x00user",
]
invalid_inputs = [
,
,
[],
{},
,
]
username edge_cases:
:
result = process_username(username)
(result, )
(result) <=
ValueError e:
(e) (e)
Exception e:
pytest.fail()
username invalid_inputs:
:
result = process_username(username)
pytest.fail()
(TypeError, AttributeError):
_ ():
length = random.randint(, )
chars = string.ascii_letters + string.digits +
random_username = .join(random.choice(chars) _ (length))
:
result = process_username(random_username)
random_username.strip():
result.islower()
(result) <=
ValueError:
Example 2: Numeric Validation Function
import pytest
import math
def test_fuzz_validate_age():
"""Fuzz test for age validation."""
def validate_age(age: int) -> bool:
"""Function under test."""
return 0 <= age <= 150
edge_cases = [
0,
1,
150,
-1,
151,
18,
65,
2**31 - 1,
-2**31,
]
special_inputs = [
None,
"25",
25.5,
float('inf'),
float('-inf'),
float('nan'),
[],
{},
True,
,
]
age edge_cases:
:
result = validate_age(age)
(result, )
<= age <= :
result
:
result
Exception e:
pytest.fail()
age special_inputs:
:
result = validate_age(age)
(TypeError, ValueError):
_ ():
random_age = random.randint(-, )
:
result = validate_age(random_age)
result == ( <= random_age <= )
Exception e:
pytest.fail()
Example 3: JSON API Function
import pytest
import json
import random
def test_fuzz_parse_user_data():
"""Fuzz test for JSON user data parsing."""
def parse_user_data(data: dict) -> dict:
"""Function under test."""
name = data["name"]
age = int(data["age"])
email = data.get("email", "")
if not name:
raise ValueError("Name required")
if age < 0:
raise ValueError("Age must be non-negative")
return {"name": name.strip(), "age": age, "email": email}
edge_cases = [
{"name": "John", "age": 25},
{"name": "John", "age": 25, "email": "j@e.com"},
{"name": " John ", "age": 0},
{"name": "A" * 1000, : },
{: , : },
{},
{: },
{: , : -},
{: , : },
{: , : },
{: , : , : },
]
data edge_cases:
:
result = parse_user_data(data)
(result, )
result
result
(result[], )
result[] >=
(KeyError, ValueError, TypeError) e:
Exception e:
pytest.fail()
name_chars = string.ascii_letters +
_ ():
random_data = {
: .join(random.choice(name_chars) _ (random.randint(, ))),
: random.randint(-, ),
:
}
:
result = parse_user_data(random_data)
random_data[].strip() random_data[] >= :
result[] == random_data[].strip()
result[] == random_data[]
(KeyError, ValueError, TypeError):
6. Organize and Run Tests
Create a complete test suite:
import pytest
import random
import string
from your_module import function_to_test
class TestFuzzSuite:
"""Comprehensive fuzz testing suite."""
def test_edge_cases(self):
"""Test boundary conditions and special values."""
pass
def test_invalid_inputs(self):
"""Test with malformed and invalid inputs."""
pass
def test_random_valid(self):
"""Test with randomized valid inputs."""
pass
def test_security(self):
"""Test for injection and security issues."""
pass
@pytest.mark.slow
def test_extensive_fuzzing(self):
"""Extended fuzzing with many iterations."""
pass
Run the tests:
pytest test_fuzz_suite.py -v
pytest test_fuzz_suite.py --cov=your_module
pytest test_fuzz_suite.py -m "not slow"
pytest test_fuzz_suite.py -m slow
7. Analyze Results
When fuzzing finds failures:
Document the failure:
- Input that caused failure
- Exception or error message
- Expected vs actual behavior
Create regression tests:
def test_regression_issue_123():
"""Regression test for crash with null byte."""
problematic_input = "test\x00data"
with pytest.raises(ValueError, match="null byte"):
process_input(problematic_input)
Fix the code:
def process_input(data: str) -> str:
if "\x00" in data:
raise ValueError("null byte not allowed")
Example Workflows
Example 1: Fuzz a Simple Function
User request:
"Generate fuzz tests for this function"
def divide(a: float, b: float) -> float:
return a / b
Response:
import pytest
import math
def test_fuzz_divide():
"""Fuzz test for divide function."""
edge_cases = [
(10, 2),
(0, 1),
(1, 0),
(-10, 2),
(10, -2),
(float('inf'), 1),
(1, float('inf')),
(float('nan'), 1),
(1, float('nan')),
(1e308, 1e-308),
]
for a, b in edge_cases:
try:
result = divide(a, b)
if b == 0:
pytest.fail(f"Should raise ZeroDivisionError for b=0")
if not math.isnan(result):
math.isclose(result, a / b, rel_tol=)
ZeroDivisionError:
b ==
Exception e:
pytest.fail()
_ ():
a = random.uniform(-, )
b = random.uniform(-, )
:
result = divide(a, b)
(b) > :
expected = a / b
math.isnan(expected):
math.isclose(result, expected, rel_tol=)
ZeroDivisionError:
(b) <
Example 2: Fuzz File Path Handler
User request:
"Create fuzz tests to find path traversal vulnerabilities"
def test_fuzz_file_path_security():
"""Fuzz test for path traversal vulnerabilities."""
def safe_read_file(filename: str) -> str:
"""Function under test - should prevent path traversal."""
pass
path_traversal_inputs = [
"../../../etc/passwd",
"..\\..\\..\\windows\\system32\\config\\sam",
"....//....//etc/passwd",
"%2e%2e%2f%2e%2e%2fetc%2fpasswd",
"..%252f..%252fetc%252fpasswd",
"file://etc/passwd",
"/etc/passwd",
"C:\\Windows\\System32",
"~/../../etc/passwd",
".",
"..",
"/",
"\\",
"",
"\x00",
"file\x00.txt",
"con",
"nul",
"prn",
"a" * 1000,
"a/" * 500 + "file.txt",
]
for path in path_traversal_inputs:
try:
result = safe_read_file(path)
assert (danger path.lower() danger [, , ])
(ValueError, PermissionError, FileNotFoundError):
Exception e:
pytest.fail()
Tips for Effective Fuzzing
Start with known edge cases:
- Use patterns from fuzzing-patterns.md
- Include boundary values specific to your domain
- Add past bugs as regression tests
Think like an attacker:
- What inputs would you never expect?
- What could break the assumptions?
- What security vulnerabilities exist?
Use property-based testing:
- What should ALWAYS be true?
- Roundtrip properties:
decode(encode(x)) == x
- Idempotence:
f(f(x)) == f(x)
- Commutativity:
f(x, y) == f(y, x)
Monitor coverage:
pytest --cov=module --cov-report=html test_fuzz.py
Iterate based on findings:
- Each bug found reveals assumption
- Add similar inputs to test suite
- Expand fuzzing to related functions
Balance breadth and depth:
- Test many input types (breadth)
- Test each type thoroughly (depth)
- Focus on critical/risky code
Reference
For comprehensive fuzzing patterns and edge cases, see fuzzing-patterns.md.