timeouts-and-async
Qué hace
Esta skill explica cómo evitar que las pruebas de Ginkgo tarden demasiado y cómo probar trabajos en segundo plano o diferidos. Está pensada para desarrolladores cuyas pruebas en Go se bloquean o se comportan de forma inconsistente.
Cuándo usarla
- ✓Cuando una prueba de Ginkgo se bloquea o supera su límite de tiempo.
- ✓Cuando necesitas comprobar un resultado que tarda en aparecer.
- ✓Cuando el código de prueba se ejecuta en goroutines y un fallo no se informa.
Link de la skill
https://github.com/onsi/ginkgo/blob/master/plugins/ginkgo/skills/timeouts-and-async/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“Mi prueba en Go se queda bloqueada para siempre al hablar con un proceso en segundo plano. ¿Cómo hago que se detenga después de unos segundos?”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
Muestra cómo poner límites de tiempo a las pruebas, pasar una señal de cancelación al código de prueba y esperar resultados con comprobaciones que siguen reintentando.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de GitHub.
Timeouts, interruptible nodes, and async testing
Builds on the failure mental model in ginkgo:overview (failure is a panic Ginkgo recovers; a goroutine that fails needs defer GinkgoRecover()). Docs: https://onsi.github.io/ginkgo/#spec-timeouts-and-interruptible-nodes and https://onsi.github.io/ginkgo/#patterns-for-asynchronous-testing.
Interruptible nodes: take a context, honor cancellation
A setup or subject node becomes interruptible simply by accepting a SpecContext (or plain context.Context) — Ginkgo supplies one automatically:
It("likes to sleep in", func(ctx context.Context) {
select {
case <-ctx.Done(): return // honor cancellation and exit promptly
case <-time.After(time.Hour): ...
}
}, NodeTimeout(time.Second))
On timeout or interrupt, Ginkgo cancels the context to tell the node to stop. Pass ctx down into every blocking call (libraryClient.SaveBook(ctx, book), exec.CommandContext(ctx, ...)) so the cancellation actually propagates. Only setup/subject nodes are interruptible — container nodes are not (they run at construction time).
ctx.Deadline()does NOT report the node's deadline. Ginkgo manages cancellation timing itself (to snapshot a progress report first), so it does not use aWithDeadlinecontext. Trust<-ctx.Done(), notDeadline().SpecContextsatisfiescontext.Context; you may wrap it (context.WithValue) and Ginkgo still cancels the result on time.
The timeout decorators (full reference → ginkgo:decorators)
| Decorator | Scope |
|---|---|
NodeTimeout(d) |
Deadline for one interruptible node. |
SpecTimeout(d) |
Deadline for the whole spec lifecycle — It only. |
GracePeriod(d) |
How long Ginkgo waits after cancelling before leaking the node. |
SpecTimeoutcan only be more lenient than a node'sNodeTimeout— it caps the sum of all nodes (BeforeEach+It+AfterEach); a per-nodeNodeTimeoutinside it is always more stringent.- Cleanup still runs after a timeout. When
SpecTimeoutfires, Ginkgo cancels the current node, runs anyDeferOnFailurecallbacks (not bound by the expiredSpecTimeout), then runsAfterEach/AfterAll/DeferCleanup(each under its ownNodeTimeout/grace). The timeout is a "mark failed" threshold, not a hard kill. - A node that ignores cancellation is "leaked," not killed. After the grace period Ginkgo gives up waiting and moves on. Leaking is deliberately preferred over hanging forever — but a leaked goroutine keeps running and can call
Fail/AddReportEntryand pollute a later spec. Always make blocking code respond toctx.Done(). DeferCleanup/DeferOnFailure/DescribeTableentries are interruptible too — give the cleanup/entry func actxfirst arg; don't capture and reuse the parent node'sctx(it's already cancelled by cleanup time).
Interrupting the whole suite
ginkgo --timeout=DURATION— suite-wide budget across all suites (default1h).Abort("reason")— end the suite immediately from within a spec (programmatic interrupt).SIGINT/SIGTERM(^C) — interrupt: cancel the current interruptible node, run its cleanup + reporting nodes, skip the rest, exit failed. Escalation: a 2nd interrupt skips cleanup (still runs reporting); a 3rd bails immediately. To inspect a suite without stopping it, sendSIGINFO/SIGUSR1for a progress report →ginkgo:debugging-failures.
Async assertions: Eventually / Consistently
Use Gomega's Eventually (polls until the matcher passes or it times out) and Consistently (polls and requires the matcher to hold the whole interval — the way to assert something doesn't happen). Three input shapes: bare values (channels, gbytes), functions returning (value[, error]), and functions taking a Gomega.
It("publishes a book", func(ctx SpecContext) {
buffer := gbytes.NewBuffer()
c := publisher.Publish(ctx, book, buffer) // pass ctx so it cancels cleanly
Eventually(ctx, buffer).Should(gbytes.Say(`Publish complete!`))
var result publisher.PublishResult
Eventually(ctx, c).WithTimeout(time.Second).Should(Receive(&result)) // poll, don't <-c
}, SpecTimeout(time.Second*30))
Propagate the spec deadline into the poll with .WithContext(ctx) or the positional Eventually(ctx, ...) — now a node timeout/interrupt makes the Eventually exit immediately instead of running its own clock. Gomega also **auto-injec
Preguntas frecuentes
¿Cómo pongo un límite de tiempo a una prueba?
La skill muestra cómo añadir una opción de tiempo límite a una prueba para que se detenga después de un tiempo fijado.
¿Qué significa cancelar aquí?
Significa que a la prueba se le indica que se detenga antes, para que el código que llama pueda terminar limpiamente.
¿Qué es Eventually en Gomega?
Es una comprobación que sigue intentándolo durante un tiempo hasta que un resultado sea verdadero.
Detalles
Descripción original del autor
Make Ginkgo specs interruptible and test asynchronous behavior — SpecContext/context.Context cancellable nodes, NodeTimeout/SpecTimeout/GracePeriod, the --timeout flag, Abort and SIGINT behavior, Gomega Eventually/Consistently (the func(g Gomega) form, .WithContext), and the defer GinkgoRecover() rule for goroutines. Use when a spec hangs or times out, polls for eventual consistency, tests channels/streams/processes, launches goroutines, or needs a deadline.
repo: onsi/ginkgo
Popularidad
- Estrellas en GitHub
- 9,1 mil
- Posición en el ranking
- #12309
- Licencia
- MIT
- Actualizada
- 9/10/2026
Comentarios
- …
Más skills de este repositorio
ci
9,1 milAyuda a tu agente a configurar pruebas de Ginkgo para la integración continua, con banderas recomendadas que detectan marcas de enfoque o pendientes olvidadas y pruebas inestables.
debugging-failures
9,1 milAyuda a tu agente a descubrir por qué fallaron las pruebas de Ginkgo, leyendo la línea de resumen y extrayendo de un informe JSON las pruebas y mensajes exactos que fallaron.
decorators
9,1 milAyuda a tu agente a usar bien los decoradores de pruebas de Ginkgo, como Serial, Ordered, Label, Focus y los tiempos límite, explicando qué hace cada uno.
filtering
9,1 milAyuda a tu agente a ejecutar solo algunas pruebas de Ginkgo, usando pending, skip, focus, etiquetas, restricciones de versión y filtros de archivo en el orden de prioridad correcto.
Skills parecidas
test-driven-development
311 milEnseña a tu agente a escribir primero una prueba que falle, verla fallar y después escribir el código más pequeño que la hace pasar, antes de construir cualquier función o corrección.
verification-before-completion
311 milEnseña a tu agente a ejecutar comprobaciones reales y leer su resultado antes de afirmar que una tarea, una corrección o una compilación está completa o en buen estado.
migrate-to-shoehorn
310 milSustituye los casts de tipo arriesgados de tus archivos de prueba por la librería shoehorn, para que las pruebas usen datos parciales y sigan pasando las comprobaciones de tipos.