gpui-test

zed-industries/zed

Для написания, отладки и воспроизведения тестов GPUI в Zed: аргументы gpui::test, TestAppContext, seeds, ITERATIONS/SEED и трассировки задач.

Звёзды95 246
Авторzed-industries
Установок23

Установка

SKILL.md

GPUI Test Debugging

Use this skill when the user asks about #[gpui::test], GPUI test seeds or iterations, deterministic scheduler failures, parking/pending task failures, or how to reproduce a flaky GPUI test.

What #[gpui::test] does

#[gpui::test] expands to a normal Rust #[test], so it runs under standard Rust test runners such as cargo test and cargo nextest.

It wraps the body in GPUI's deterministic test dispatcher/scheduler and can run the same test multiple times with different seeds. The seed controls scheduler task interleavings and any StdRng argument injected into the test.

The macro supports both synchronous and asynchronous tests.

Supported function arguments

The macro recognizes arguments by type name:

Test kindSupported arguments
Sync and async&TestAppContext, &mut TestAppContext, StdRng
Async onlyBackgroundExecutor
Sync only&App, &mut App

StdRng is seeded from the current GPUI test seed, and BackgroundExecutor is backed by the same deterministic test dispatcher.

Attribute arguments

Use these forms on #[gpui::test(arguments)]:

  • No arguments: runs once with seed 0, unless SEED is set.
  • seed = N: adds a single explicit seed.
  • seeds(...): adds multiple explicit seeds.
  • iterations = N: runs sequential seeds starting at 0 by default.
  • retries = N: retries a failing run up to N times before surfacing the failure.
  • on_failure = "path::to::function": calls the function after final failure, before resuming the panic.
  • iterations can be combined with explicit seed / seeds; explicit seeds are appended to the 0..iterations range.
  • If the SEED environment variable is set, it takes precedence over explicit seeds.
  • With SEED=N and ITERATIONS=M or iterations = M, the harness runs seeds N..N+M.

Environment variables

GPUI test macro / scheduler execution

  • SEED=<u64> — chooses the scheduler seed. Use this to reproduce a failure printed as failing seed: N. It also seeds injected StdRng arguments. For #[gpui::property_test], it controls the scheduler seed and GPUI applies it to the proptest config for deterministic case generation.
  • ITERATIONS=<usize> — overrides the iterations = ... value at runtime. Use to sweep many seeds without editing the test.
  • PENDING_TRACES=1 or PENDING_TRACES=true — captures and prints pending task traces when the test scheduler panics with Parking forbidden. Use this when run_until_parked() or teardown reports pending work.
  • GPUI_RUN_UNTIL_PARKED_LOG=1 — logs when allow_parking() is enabled. Use to find tests that explicitly permit parking/pending work.
  • DEBUG_SCHEDULER=1 — prints scheduler clock/timer debugging from scheduler::TestScheduler.

Lower-level scheduler tests

  • SCHEDULER_NONINTERACTIVE=1 — suppresses interactive seed progress output in scheduler::TestScheduler::many. This does not affect the #[gpui::test] harness path.

General Rust test debugging vars often useful with GPUI tests

  • RUST_BACKTRACE=1 or RUST_BACKTRACE=full — show panic backtraces.
  • RUST_LOG=<filter> — enable logs when the test initializes logging.
  • ZED_HEADLESS=1 — forces GPUI platform guessing toward headless mode; useful for tests that otherwise interact with platform/window setup.

Prefer env vars over editing the test when narrowing a reproduction.

Reproducing a specific GPUI test

  1. Identify the crate/package and test name.

  2. Run the narrowest test filter first, skip to 3. if a failing seed is known.

    cargo -q test -p <crate-name> <test_name> -- --nocapture
    
  3. If the failure mentions a seed, rerun exactly that seed.

    SEED=<seed> cargo -q test -p <crate-name> <test_name> -- --nocapture
    
  4. If the failure is flaky and no seed is known, sweep seeds.

    ITERATIONS=100 cargo -q test -p <crate-name> <test_name> -- --nocapture
    

    When the harness prints failing seed: <seed>, switch to SEED=<seed> for all future debugging.

  5. If the failure is Parking forbidden, rerun with pending traces.

    PENDING_TRACES=1 cargo -q test -p <crate-name> <test_name> -- --nocapture
    

    If a failing seed was printed or is already known, include it too:

    SEED=<seed> PENDING_TRACES=1 cargo -q test -p <crate-name> <test_name> -- --nocapture
    

    Inspect the pending traces for a task that was spawned but not awaited, detached, completed, or intentionally allowed to park.

  6. If timing or timer advancement is involved, prefer GPUI scheduler timers in tests:

    cx.background_executor().timer(duration).await;
    

    Avoid smol::Timer::after(...) in GPUI tests that rely on run_until_parked(), because GPUI's scheduler may not track it.

  7. Minimize the reproduction.

    • Keep the failing SEED fixed.
    • Reduce ITERATIONS to 1 or remove it once a seed is known.
    • Remove unrelated setup only after confirming the same seed still fails.
    • Preserve scheduler-sensitive awaits/yields; removing them can mask the bug.
    • If randomness is test-controlled via StdRng, log or assert the generated scenario after fixing the scheduler seed.
  8. Validate the fix.

    • Run the fixed seed.
    • Run a modest seed sweep, e.g. ITERATIONS=20, if the failure was scheduler-sensitive.
    • Run the relevant crate's test filter or broader suite if the touched code has shared behavior.

Common diagnosis patterns

Seed-dependent assertion failure

Likely caused by a scheduler interleaving or by StdRng-driven test data. Fix SEED, reproduce, and inspect which task or generated scenario differs.

Parking forbidden

Usually means a foreground/background task is still pending when the scheduler expected the test to make progress or finish. Look for:

  • A task that should be awaited but was dropped.
  • A task that should be detached with error logging.
  • A timer or receiver that is waiting forever.
  • A missing cx.run_until_parked() after triggering async work in a test.
  • A missing cx.advance_clock(...) to wait for debounced work in a test.
  • Use of non-GPUI timers or executors that the test scheduler cannot drive.

Rerun with PENDING_TRACES=1 before changing code.

Non-determinism / wrong thread

The scheduler can report activity from an unexpected thread. Look for work escaping GPUI's foreground/background executors, direct thread spawns, or external async runtimes not controlled by the test dispatcher.

Tests pass alone but fail in sweeps

Use the failing seed from sweep output. Avoid assuming test order unless the runner is explicitly serial. Check globals, leaked entities/tasks, and state not reset by test initialization.

Writing GPUI tests

  • Prefer #[gpui::test] for tests that need TestAppContext, deterministic executors, fake time, or scheduler interleaving coverage.
  • Add iterations = N when the test is intentionally checking interleavings.
  • Use StdRng as a test argument when randomized test data should follow the same seed as the scheduler.
  • Use cx.background_executor().timer(duration).await for delays/timeouts in GPUI tests.
  • Do not add or increase retries while fixing a test unless the user explicitly asks or the test already documents why probabilistic tolerance is intentional. Retries can mask the failure instead of fixing it.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: gpui-test](https://darkplay.ru/ai/skills/zed-industries-zed-gpui-test)

Описание

Используйте при написании, отладке или воспроизведении тестов GPUI в Zed, включая аргументы gpui::test, параметры TestAppContext, seed планировщика, воспроизведение ITERATIONS/SEED, зависания parking и трассировки ожидающих задач.

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

E2e Runneraffaan-m · Специалист по E2E-тестам на Vercel Agent Browser и Playwright: генерация, запуск и…
225 587 ★
Fastapi Revieweraffaan-m · Проверяет FastAPI-приложения: async, DI, Pydantic, безопасность, OpenAPI и тесты.
225 587 ★
Gan Evaluatoraffaan-m · GAN Harness — агент-оценщик: тестирует приложение через Playwright и даёт обратную связь.
225 587 ★
Pr Test Analyzeraffaan-m · Оценивает качество и полноту покрытия тестами в pull request.
225 587 ★
Spec Mineraffaan-m · Извлекает поведенческие спецификации из кода для OpenSpec в виде блоков Requirement и…
225 587 ★
Tdd Guideaffaan-m · Специалист по TDD: сначала тесты, покрытие 80%+.
225 587 ★
example-skillsanthropics · Набор примеров навыков, демонстрирующих разные возможности: создание навыков, разработку…
17 комп.
pr-review-toolkitanthropics · Комплексные агенты для ревью PR, специализирующиеся на комментариях, тестах, обработке…
34 комп.
ruflo-browserruvnet · Агентная автоматизация браузера на Playwright для тестирования, скрапинга и…
240 комп.
ruflo-neural-traderruvnet · Нейросетевые торговые стратегии: самообучающиеся модели LSTM/Transformer/N-BEATS с…
240 комп.

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8