본문으로 건너뛰기
cccskills
무료GitHub에 공개

property-based-testing

Property-based testing (PBT) patterns with fast-check (JS/TS), Hypothesis (Python), and gopter (Go). Generate random inputs, define invariants, shrink failures to minimal cases. Adapted from Trail of Bits. Use when testing pure functions, parsers, serializers, state machines, or any code where example-based tests miss edge cases.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

연동 도구Gmail
설치 방법 보기

포함된 파일(1)

  • SKILL.md7.7 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Property-Based Testing

Instead of testing specific examples, define properties that must hold for ALL inputs. The framework generates hundreds of random inputs and finds the smallest failing case.

When to Use PBT

Use CaseProperty
Serialization roundtripdeserialize(serialize(x)) === x
Sort functionOutput is ordered AND contains same elements
ParserNever crashes on any input
Encoder/decoderdecode(encode(x)) === x
State machineInvariants hold after any sequence of operations
Math/financialAssociativity, commutativity, identity, bounds
API handlerNever returns 500 on valid input
Data transformationOutput schema matches specification

When NOT to Use PBT

  • UI rendering tests (use visual regression)
  • Integration tests with external services (use contract tests)
  • Tests that need specific business scenarios (use example tests)
  • Tests where the oracle is as complex as the implementation

fast-check (JavaScript/TypeScript)

Setup

npm install --save-dev fast-check

Basic Property

import fc from 'fast-check'

// Property: sorting is idempotent
test('sort is idempotent', () => {
  fc.assert(
    fc.property(fc.array(fc.integer()), (arr) => {
      const sorted = [...arr].sort((a, b) => a - b)
      const sortedTwice = [...sorted].sort((a, b) => a - b)
      expect(sorted).toEqual(sortedTwice)
    })
  )
})

// Property: serialization roundtrip
test('JSON roundtrip preserves data', () => {
  fc.assert(
    fc.property(fc.jsonValue(), (value) => {
      expect(JSON.parse(JSON.stringify(value))).toEqual(value)
    })
  )
})

Custom Arbitraries

// Generate valid email addresses
const emailArb = fc.tuple(
  fc.stringOf(fc.constantFrom(...'abcdefghijklmnopqrstuvwxyz0123456789'.split('')), { minLength: 1 }),
  fc.constantFrom('gmail.com', 'example.com', 'test.org')
).map(([local, domain]) => `${local}@${domain}`)

// Generate valid user objects
const userArb = fc.record({
  id: fc.uuid(),
  name: fc.string({ minLength: 1, maxLength: 100 }),
  email: emailArb,
  age: fc.integer({ min: 0, max: 150 }),
  role: fc.constantFrom('admin', 'user', 'viewer')
})

// Generate valid but adversarial strings
const adversarialStringArb = fc.oneof(
  fc.constant(''),
  fc.constant(' '),
  fc.constant('\0'),
  fc.constant('<script>alert(1)</script>'),
  fc.constant("Robert'); DROP TABLE users;--"),
  fc.constant('../../../etc/passwd'),
  fc.unicodeString(),
  fc.string({ minLength: 10000, maxLength: 100000 })  // Very long
)

Stateful Testing (Model-Based)

// Test a cache against a simple Map model
class CacheModel {
  private model = new Map<string, string>()

  set(key: string, value: string): void { this.model.set(key, value) }
  get(key: string): string | undefined { return this.model.get(key) }
  delete(key: string): void { this.model.delete(key) }
  size(): number { return this.model.size }
}

const cacheCommands = [
  fc.tuple(fc.string(), fc.string()).map(([k, v]) => ({
    check: (model: CacheModel) => true,
    run: (model: CacheModel, real: Cache) => {
      model.set(k, v)
      real.set(k, v)
      expect(real.get(k)).toBe(model.get(k))
    },
    toString: () => `set(${k}, ${v})`
  })),
  fc.string().map((k) => ({
    check: (model: CacheModel) => true,
    run: (model: CacheModel, real: Cache) => {
      model.delete(k)
      real.delete(k)
      expect(real.get(k)).toBe(model.get(k))
    },
    toString: () => `delete(${k})`
  }))
]

test('cache behaves like Map', () => {
  fc.assert(
    fc.property(fc.commands(cacheCommands), (cmds) => {
      const model = new CacheModel()
      const real = new Cache()
      fc.modelRun(() => ({ model, real }), cmds)
    })
  )
})

Hypothesis (Python)

Setup

pip install hypothesis

Basic Properties

from hypothesis import given, strategies as st, settings

@given(st.lists(st.integers()))
def test_sort_preserves_length(xs):
    assert len(sorted(xs)) == len(xs)

@given(st.lists(st.integers()))
def test_sort_preserves_elements(xs):
    assert sorted(sorted(xs)) == sorted(xs)

@given(st.text())
def test_encode_decode_roundtrip(s):
    assert s.encode('utf-8').decode('utf-8') == s

# With settings
@settings(max_examples=1000, deadline=None)
@given(st.dictionaries(st.text(), st.integers()))
def test_dict_operations(d):
    import json
    assert json.loads(json.dumps(d)) == d

Custom Strategies

from hypothesis import strategies as st

# Valid email strategy
emails = st.builds(
    lambda local, domain: f"{local}@{domain}",
    local=st.from_regex(r'[a-z0-9]{1,20}', fullmatch=True),
    domain=st.sampled_from(['gmail.com', 'example.com'])
)

# Valid user strategy
users = st.fixed_dictionaries({
    'name': st.text(min_size=1, max_size=100),
    'email': emails,
    'age': st.integers(min_value=0, max_value=150),
    'role': st.sampled_from(['admin', 'user', 'viewer'])
})

gopter (Go)

Setup

go get github.com/leanovate/gopter

Basic Property

func TestSortIdempotent(t *testing.T) {
    properties := gopter.NewProperties(gopter.DefaultTestParameters())

    properties.Property("sort is idempotent", prop.ForAll(
        func(xs []int) bool {
            sorted := make([]int, len(xs))
            copy(sorted, xs)
            sort.Ints(sorted)

            sortedTwice := make([]int, len(sorted))
            copy(sortedTwice, sorted)
            sort.Ints(sortedTwice)

            return reflect.DeepEqual(sorted, sortedTwice)
        },
        gen.SliceOf(gen.Int()),
    ))

    properties.TestingRun(t)
}

Property Catalog

Algebraic Properties

PropertyDefinitionExample
Identityf(x, identity) === xadd(x, 0) === x
Commutativityf(a, b) === f(b, a)add(a, b) === add(b, a)
Associativityf(f(a, b), c) === f(a, f(b, c))add(add(a, b), c) === add(a, add(b, c))
Idempotencyf(f(x)) === f(x)sort(sort(xs)) === sort(xs)
Roundtripg(f(x)) === xdecode(encode(x)) === x
Invariantproperty(f(x)) === truelength(sort(xs)) === length(xs)

Safety Properties

PropertyCheck
No crashFunction never throws for any valid input
Bounded outputOutput size is proportional to input size
No mutationInput is not modified by the function
DeterministicSame input always produces same output
MonotonicIf a <= b then f(a) <= f(b)

Shrinking

When a property fails, the framework automatically shrinks the failing input to the smallest case that still fails:

Original failing input: [482, -1, 0, 99, -384, 7, 42, 0, -1]
Shrunk to: [1, 0]

This tells you the bug is about: handling zero in a list with other elements

Tips:

  • Custom arbitraries should define custom shrinkers
  • If shrinking takes too long, limit with { endOnFailure: true }
  • Shrunk examples make great regression tests

Integration with vibecosystem

  • tdd-guide agent: Recommend PBT for pure functions and serialization
  • qa-engineer agent: Use PBT for edge case discovery
  • arbiter agent: Run PBT suites as part of test validation
  • mocksmith agent: Generate test data using PBT arbitraries

Inspired by Trail of Bits property-based-testing plugin.

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

WCAG 2.2 AA compliance, ARIA patterns, keyboard navigation, screen reader optimization

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

vibeeval/vibecosystem5382026년 8월 9일 업데이트

axe-core integration, WCAG 2.2 AA checklist, keyboard navigation testing, screen reader testing, and ARIA pattern validation.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

vibeeval/vibecosystem5382026년 8월 9일 업데이트

Steam-style achievement system with XP, levels, streaks, and skill trees. Gamifies the development workflow. 25 achievements across 5 categories.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

vibeeval/vibecosystem5382026년 8월 9일 업데이트

Framework for measuring and tracking agent response quality over time. Detects regressions before they reach production. Use when evaluating agent changes, auditing quality, or establishing performance baselines.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

vibeeval/vibecosystem5382026년 8월 9일 업데이트

Agent Context Isolation

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

vibeeval/vibecosystem5382026년 8월 9일 업데이트

Agent ve skill dosyalarinin yapisal dogrulamasi. Frontmatter kontrol, naming convention, zorunlu bolum kontrolu, tutarlilik denetimi. Yeni agent/skill eklendiginde veya mevcut dosyalar duzenlediginde otomatik calistirilir.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

vibeeval/vibecosystem5382026년 8월 9일 업데이트

vibeeval의 스킬 모두 보기

이 스킬의 문제 신고