property-based-test-generator
Generates property-based tests using Hypothesis (Python), fast-check (JavaScript/TypeScript), or QuickCheck (Haskell). Use when user asks to "generate property tests", "create hypothesis tests", "add property-based testing", or "generate fast-check tests".
What this skill does
# Property-Based Test Generator
Generates property-based tests that validate invariants and find edge cases automatically through randomized testing.
## When to Use
- "Generate property-based tests"
- "Create hypothesis tests for my function"
- "Add property tests to my code"
- "Generate fast-check tests"
- "Test function properties"
- "Find edge cases automatically"
## Instructions
### 1. Detect Language and Testing Framework
Check the project's language and existing test setup:
```bash
# Check for Python
[ -f "pytest.ini" ] || [ -f "setup.py" ] && echo "Python"
# Check for JavaScript/TypeScript
[ -f "package.json" ] && echo "JavaScript/TypeScript"
# Check existing test framework
grep -E "(jest|vitest|mocha|pytest|hypothesis)" package.json pyproject.toml requirements.txt 2>/dev/null
```
### 2. Install Property-Based Testing Library
**Python (Hypothesis):**
```bash
pip install hypothesis pytest
```
**JavaScript/TypeScript (fast-check):**
```bash
npm install --save-dev fast-check @types/jest
# or
npm install --save-dev fast-check vitest
```
**Haskell (QuickCheck):**
```bash
cabal install QuickCheck
```
### 3. Identify Function Properties
Analyze the function to test and identify invariants:
**Common Properties:**
- **Idempotence**: `f(f(x)) === f(x)`
- **Inverse**: `decode(encode(x)) === x`
- **Commutativity**: `f(a, b) === f(b, a)`
- **Associativity**: `f(f(a, b), c) === f(a, f(b, c))`
- **Identity**: `f(x, identity) === x`
- **Range**: Output always within valid range
- **Type safety**: Output type matches expected
- **No exceptions**: Function never throws for valid input
### 4. Generate Property-Based Tests
## Python with Hypothesis
**Basic Example:**
```python
from hypothesis import given, strategies as st
import pytest
# Function to test
def sort_list(items):
return sorted(items)
# Property: sorted list length equals original
@given(st.lists(st.integers()))
def test_sort_preserves_length(items):
result = sort_list(items)
assert len(result) == len(items)
# Property: sorted list is ordered
@given(st.lists(st.integers()))
def test_sort_creates_ordered_list(items):
result = sort_list(items)
for i in range(len(result) - 1):
assert result[i] <= result[i + 1]
# Property: sorted list contains same elements
@given(st.lists(st.integers()))
def test_sort_preserves_elements(items):
result = sort_list(items)
assert sorted(items) == result
```
**Advanced Strategies:**
```python
from hypothesis import given, strategies as st, assume
from datetime import datetime, timedelta
# Custom data structures
@st.composite
def users(draw):
return {
'id': draw(st.integers(min_value=1, max_value=1000000)),
'name': draw(st.text(min_size=1, max_size=50)),
'email': draw(st.emails()),
'age': draw(st.integers(min_value=18, max_value=120)),
'created_at': draw(st.datetimes(
min_value=datetime(2020, 1, 1),
max_value=datetime.now()
))
}
@given(users())
def test_user_validation(user):
# Validate user properties
assert user['age'] >= 18
assert '@' in user['email']
assert len(user['name']) > 0
assert user['created_at'] <= datetime.now()
```
**Testing with Preconditions:**
```python
@given(st.integers(), st.integers())
def test_division(a, b):
assume(b != 0) # Precondition: no division by zero
result = a / b
assert result * b == a # Property: inverse of multiplication
```
**Stateful Testing:**
```python
from hypothesis.stateful import RuleBasedStateMachine, rule, invariant
class ShoppingCart(RuleBasedStateMachine):
def __init__(self):
super().__init__()
self.items = []
self.total = 0
@rule(item=st.tuples(st.text(), st.floats(min_value=0, max_value=1000)))
def add_item(self, item):
name, price = item
self.items.append(item)
self.total += price
@rule()
def clear_cart(self):
self.items = []
self.total = 0
@invariant()
def total_matches_sum(self):
assert abs(self.total - sum(p for _, p in self.items)) < 0.01
TestCart = ShoppingCart.TestCase
```
## JavaScript/TypeScript with fast-check
**Basic Example:**
```typescript
import fc from 'fast-check';
// Function to test
function reverseString(str: string): string {
return str.split('').reverse().join('');
}
describe('reverseString', () => {
it('double reverse returns original', () => {
fc.assert(
fc.property(fc.string(), (str) => {
const reversed = reverseString(str);
const doubleReversed = reverseString(reversed);
return doubleReversed === str;
})
);
});
it('preserves string length', () => {
fc.assert(
fc.property(fc.string(), (str) => {
return reverseString(str).length === str.length;
})
);
});
it('first char becomes last char', () => {
fc.assert(
fc.property(fc.string({ minLength: 1 }), (str) => {
const reversed = reverseString(str);
return str[0] === reversed[reversed.length - 1];
})
);
});
});
```
**Complex Data Structures:**
```typescript
import fc from 'fast-check';
// Custom arbitraries
const userArbitrary = fc.record({
id: fc.integer({ min: 1, max: 1000000 }),
name: fc.string({ minLength: 1, maxLength: 50 }),
email: fc.emailAddress(),
age: fc.integer({ min: 18, max: 120 }),
roles: fc.array(fc.constantFrom('admin', 'user', 'guest'), { minLength: 1 })
});
describe('User validation', () => {
it('validates user structure', () => {
fc.assert(
fc.property(userArbitrary, (user) => {
return (
user.age >= 18 &&
user.email.includes('@') &&
user.roles.length > 0
);
})
);
});
});
```
**Array Properties:**
```typescript
describe('Array operations', () => {
it('map preserves length', () => {
fc.assert(
fc.property(
fc.array(fc.integer()),
fc.func(fc.integer()),
(arr, fn) => {
return arr.map(fn).length === arr.length;
}
)
);
});
it('filter result is subset', () => {
fc.assert(
fc.property(
fc.array(fc.integer()),
(arr) => {
const filtered = arr.filter(x => x > 0);
return filtered.every(x => arr.includes(x));
}
)
);
});
it('concat is associative', () => {
fc.assert(
fc.property(
fc.array(fc.integer()),
fc.array(fc.integer()),
fc.array(fc.integer()),
(a, b, c) => {
const left = a.concat(b).concat(c);
const right = a.concat(b.concat(c));
return JSON.stringify(left) === JSON.stringify(right);
}
)
);
});
});
```
**Shrinking Examples:**
```typescript
describe('Shrinking demonstration', () => {
it('finds minimal failing case', () => {
fc.assert(
fc.property(fc.array(fc.integer()), (arr) => {
// This will fail and shrink to smallest failing case
return arr.length < 5 || arr.some(x => x > 100);
}),
{ numRuns: 100 }
);
});
});
```
**Model-Based Testing:**
```typescript
import fc from 'fast-check';
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
size(): number {
return this.items.length;
}
}
describe('Stack', () => {
it('behaves like array', () => {
fc.assert(
fc.property(
fc.array(fc.integer()),
(operations) => {
const stack = new Stack<number>();
const model: number[] = [];
for (const op of operations) {
if (op >= 0) {
stack.push(op);
model.push(op);
} else {
const stackResult = stack.pop();
const modelResult = model.pop();
if (stackResult !== modelResult) return false;
}
}
return stack.size() ===Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.