Перейти к содержанию
Skillpedia
Тестирование8.0k · #12694

property-based-testing

Что он делает

Направляет тестирование на свойства, когда тест формулирует правило для всех входных данных, а инструмент ищет контрпримеры. Он нужен разработчикам, которым нужны тесты, охватывающие гораздо больше, чем подобранный вручную список примеров.

Когда использовать

  • ✓Когда разработчику нужны тесты, которые охватывают весь диапазон входных данных, а не несколько примеров.
  • ✓Когда разработчик тестирует пару кодер и декодер, парсер или функцию сортировки.
  • ✓Когда разработчик хочет проверить инвариант контракта Solidity с помощью инструмента фаззинга.

Ссылка на скилл

https://github.com/trailofbits/skills/blob/main/plugins/property-based-testing/skills/property-based-testing/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/trailofbits/skills/blob/main/plugins/property-based-testing/skills/property-based-testing/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Напиши тесты на свойства для моего JSON-кодера и декодера, чтобы они проверяли каждый цикл туда и обратно.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Скилл находит в коде свойства, например циклы туда и обратно, идемпотентность или инварианты, и пишет тесты, которые их формулируют. Он проверяет, есть ли у кода четкая форма для тестирования, и предлагает рефакторинг, если ее нет.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

Property-Based Testing

An example test asserts one point. A property asserts a rule over the whole input domain and lets the generator hunt for the counterexample. That trade is worth making when the code has an algebraic shape — an inverse, an invariant, an oracle — and not otherwise. Code with no such shape gets example tests; saying so is a valid outcome.

Check first whether the shape is missing or merely buried. A calculation wrapped in I/O, a string built by concatenation, an in-place mutation — each has a property and no seam to assert it through. See references/refactoring.md before concluding there is nothing to assert.

Property catalog

Property Formula Where it applies
Roundtrip decode(encode(x)) == x Serialization, conversion pairs
Inverse f(g(x)) == x encrypt/decrypt, compress/decompress
Oracle new(x) == reference(x) Optimization, refactoring, reimplementation
Idempotence f(f(x)) == f(x) Normalization, formatting, sorting
Invariant Holds before and after Any transformation, contract state
Easy to verify is_sorted(sort(x)) Complex algorithms with cheap checkers
Commutativity f(a, b) == f(b, a) Binary and set operations
Associativity f(f(a,b), c) == f(a, f(b,c)) Combining operations
Identity f(x, e) == x Operations with a neutral element

Strength ordering, weakest to strongest: no crash → type preservation → invariant → idempotence → roundtrip / oracle.

Assert the strongest property the code supports. "No crash" alone rarely justifies the dependency — if that is all you can find, either a small rearrangement exposes something stronger, or the honest report is that this code is a poor PBT candidate. Rule out the first before settling for the second.

The two ways a property test asserts nothing

  • Tautology. assert add(a, b) == a + b restates the implementation; no bug they share can fail it. Pick a property that constrains the function without recomputing it. Note the exception: f(x) == f(x) is a genuine determinism property when f is not obviously pure — serializers over dicts or sets, hashing, anything reading the clock.
  • Vacuity. assume() that filters out nearly every input passes without exercising anything, and self-contradictory assume() passes having run zero cases. Push constraints into the strategy so the generator produces valid inputs directly.

Where to look next

Load the one that matches the task in front of you:

Task File
Writing new tests, designing strategies references/generating.md
The code has no property to assert yet references/refactoring.md
Reviewing existing property tests references/reviewing.md
A property test just failed references/interpreting-failures.md
Library choice, Echidna and Medusa references/libraries.md

Introducing PBT to a project that lacks it

If the project already uses a PBT library, just write the tests in it. If it does not, adding one is a dependency decision that belongs to the user — offer it once with the specific property you would write, and take the answer either way.

Частые вопросы

Это лучше примерных тестов?

Не всегда. Скилл говорит, что код без четкого правила для проверки должен оставаться с примерными тестами.

Какие инструменты он охватывает?

В описании указаны Hypothesis, fast-check, proptest, jqwik, rapid, Echidna и Medusa.

Что такое свойство?

Это правило, которое должно выполняться для любых допустимых входных данных, например декодирование закодированного значения возвращает исходное.

Подробности

Оригинальное описание автора

Writes, reviews, and debugs property-based tests — Hypothesis, fast-check, proptest, jqwik, rapid, and Echidna or Medusa for Solidity invariants. Use whenever tests should cover a whole input domain instead of a hand-picked list of examples: encode/decode and serialize/deserialize pairs, parsers, canonicalizers and normalizers, validators, numeric and Decimal types, comparators and sort order, data structures, and smart-contract state invariants. Also use when adding cases to an existing @given, fast-check, or proptest suite, when judging whether existing property tests assert anything real, a

repo: trailofbits/skills

Популярность

Звёзды на GitHub
8.0k
Место в рейтинге
#12694
Лицензия
CC-BY-SA-4.0
Обновлён
02.11.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

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