From 50ba9cfb04e257fafa3fdd566f9f70a1986339e8 Mon Sep 17 00:00:00 2001 From: Stefan Majewsky Date: Tue, 18 Aug 2026 11:30:54 +0200 Subject: assert: add Panics, PanicsWith I want to use this for test coverage in microprom. This turned out to be a bigger change than expected because testcapture has a dependency on assert, which I had to invert to be able to use testcapture.Capture() in assert. --- assert/panic.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 assert/panic.go (limited to 'assert/panic.go') diff --git a/assert/panic.go b/assert/panic.go new file mode 100644 index 0000000..69828a4 --- /dev/null +++ b/assert/panic.go @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: 2026 Stefan Majewsky +// SPDX-License-Identifier: Apache-2.0 + +package assert + +import ( + "go.xyrillian.de/gg/testcapture" +) + +// Panics runs the provided action and fails the test if it does not panic. +// On success, the error value passed to the call of panic is returned. +func Panics(t TestingTB, action func()) any { + return PanicsWith[any](t, action) +} + +// PanicsWith is like Panics(), but also checks if the recovered error value +// is of type T, failing the test if the type assertion fails. +func PanicsWith[T any](t TestingTB, action func()) T { + t.Helper() + result := testcapture.Capture(t.Context(), t.Name(), func(_ TestingTB) { + action() + }) + if result.Outcome != testcapture.OutcomePanicked { + t.Fatal("did not panic") + } + value, ok := result.Panic.(T) + if !ok { + var zero T + t.Fatalf("panicked with incorrect type: expected %T, but got %#v", zero, result.Panic) + } + return value +} -- cgit v1.3.1