Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

property-based-testing

БесплатноБез исполняемых скриптовНе проверен

Provides guidance for property-based testing across multiple languages and smart contracts. Use when writing tests, reviewing code with…

Roasbeefот Roasbeef★ 33 звезды на GitHub

Об этом скилле

Property-Based Testing Guide

Use this skill proactively during development when you encounter patterns where PBT provides stronger coverage than example-based tests.

Go / rapid (Primary for Go Code)

For Go code, always use pgregory.net/rapid as the property-based testing library. Do NOT use testing/quick -- it is limited, lacks proper shrinking, and has poor generator support.

Why rapid over testing/quick

  • Automatic shrinking of failing cases to minimal counterexamples.
  • Rich generator combinators: IntRange, SliceOf, Map, Custom, OneOf, Ptr, SampledFrom.
  • Stateful testing via rapid.StateMachine for testing stateful systems.
  • Integrates with standard *testing.T via rapid.Check.
  • Actively maintained with good documentation.

rapid Core Pattern

func TestRoundtrip(t *testing.T) {
    rapid.Check(t, func(t *rapid.T) {
        msg := genMessage().Draw(t, "msg")
        encoded := Encode(msg)
        decoded, err := Decode(encoded)
        if err != nil {
            t.Fatal(err)
        }
        if !reflect.DeepEqual(msg, decoded) {
            t.Fatalf("roundtrip failed: got %v, want %v", decoded, msg)
        }
    })
}

rapid Generators

Generator Description Example
rapid.Int() Any int rapid.Int().Draw(t, "n")
rapid.IntRange(lo, hi) Bounded int rapid.IntRange(0, 100).Draw(t, "n")
rapid.Int64() Any int64 rapid.Int64().Draw(t, "n")
rapid.Uint64() Any uint64 rapid.Uint64().Draw(t, "n")
rapid.Float64() Any float64 rapid.Float64().Draw(t, "f")
rapid.Bool() true or false rapid.Bool().Draw(t, "b")
rapid.String() Any string rapid.String().Draw(t, "s")
rapid.StringN(minLen, maxLen, maxRunes) Bounded string rapid.StringN(1, 50, -1).Draw(t, "s")
rapid.Byte() Single byte rapid.Byte().Draw(t, "b")
rapid.SliceOf(gen) Slice of elements rapid.SliceOf(rapid.Int()).Draw(t, "xs")
rapid.SliceOfN(gen, min, max) Bounded slice rapid.SliceOfN(rapid.Int(), 1, 10).Draw(t, "xs")
rapid.MapOf(keyGen, valGen) Map rapid.MapOf(rapid.String(), rapid.Int()).Draw(t, "m")
rapid.SampledFrom(slice) One of values rapid.SampledFrom([]string{"a","b"}).Draw(t, "s")
rapid.OneOf(gens...) One of generators rapid.OneOf(rapid.Int(), rapid.Int()).Draw(t, "n")
rapid.Just(val) Constant value rapid.Just(42).Draw(t, "n")
rapid.Ptr(gen, allowNil) Pointer rapid.Ptr(rapid.Int(), true).Draw(t, "p")
rapid.Map(gen, fn) Transform rapid.Map(rapid.Int(), func(n int) uint { return uint(n&0xff) })
rapid.Custom(fn) Custom generator See below

Custom Generators

func genMessage() *rapid.Generator[Message] {
    return rapid.Custom(func(t *rapid.T) Message {
        return Message{
            ID:       rapid.IntRange(1, 10000).Draw(t, "id"),
            Content:  rapid.StringN(0, 1000, -1).Draw(t, "content"),
            Priority: rapid.IntRange(1, 10).Draw(t, "priority"),
            Tags:     rapid.SliceOfN(rapid.StringN(1, 50, -1), 0, 20).Draw(t, "tags"),
        }
    })
}

Stateful Testing with rapid.StateMachine

For testing stateful systems (data structures, databases, protocol state machines):

type queueMachine struct {
    queue Queue           // System under test.
    model []int           // Reference model.
}

func (m *queueMachine) Init(t *rapid.T) {
    m.queue = NewQueue()
    m.model = nil
}

func (m *queueMachine) Push(t *rapid.T) {
    v := rapid.Int().Draw(t, "v")
    m.queue.Push(v)
    m.model = append(m.model, v)
}

func (m *queueMachine) Pop(t *rapid.T) {
    if len(m.model) == 0 {
        t.Skip("empty queue")
    }
    got := m.queue.Pop()
    want := m.model[0]
    m.model = m.model[1:]
    if got != want {
        t.Fatalf("got %d, want %d", got, want)
    }
}

func (m *queueMachine) Check(t *rapid.T) {
    if m.queue.Len() != len(m.model) {
        t.Fatalf("length mismatch: got %d, want %d", m.queue.Len(), len(m.model))
    }
}

func TestQueue(t *testing.T) {
    rapid.Check(t, rapid.Run[*queueMachine]())
}

Go Property Test Patterns

Roundtrip (encode/decode):

func TestCodecRoundtrip(t *testing.T) {
    rapid.Check(t, func(t *rapid.T) {
        original := genMessage().Draw(t, "msg")
        encoded, err := Encode(original)
        if err != nil {
            t.Fatal(err)
        }
        decoded, err := Decode(encoded)
        if err != nil {
            t.Fatal(err)
        }
        if !reflect.DeepEqual(original, decoded) {
            t.Fatalf("roundtrip failed: %v != %v", original, decoded)
        }
    })
}

Idempotence (normalization):

func TestNormalizeIdempotent(t *testing.T) {
    rapid.Check(t, func(t *rapid.T) {
        s := rapid.String().Draw(t, "s")
        once := Normalize(s)
        twice := Normalize(once)
        if once != twice {
Полный SKILL.md на GitHub

Установить property-based-testing в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

references/design.mdreferences/generating.mdreferences/interpreting-failures.mdreferences/libraries.mdreferences/refactoring.mdreferences/reviewing.mdreferences/strategies.md

FAQ

Что делает скилл property-based-testing?

Provides guidance for property-based testing across multiple languages and smart contracts. Use when writing tests, reviewing code with serialization/validation/parsing patterns, designing features, or when property-based testing would provide stronger coverage than example-based tests. For Go code, uses pgregory.net/rapid as the primary PBT framework.

Как установить скилл property-based-testing?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл property-based-testing запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить property-based-testing с