From d38181774f4e19df3ebe5c2330dcc8dc7a15791b Mon Sep 17 00:00:00 2001 From: Boris Nagaev Date: Wed, 18 Sep 2024 22:27:56 -0300 Subject: [PATCH] fn: generalize type of t in UnwrapOrFail It is needed to pass other types satisfying needed interfaces to methods Option.UnwrapOrFail and Result.UnwrapOrFail. An example of such a type is *lntest.HarnessTest. It embeds *testing.T and has all the methods but can't be passed directly as *testing.T, but can be passed now as an instance of Testing interface. --- fn/option.go | 17 ++++++++++++++--- fn/result.go | 3 +-- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/fn/option.go b/fn/option.go index 797f3a0ff0d..d83b1300c94 100644 --- a/fn/option.go +++ b/fn/option.go @@ -1,7 +1,5 @@ package fn -import "testing" - // Option[A] represents a value which may or may not be there. This is very // often preferable to nil-able pointers. type Option[A any] struct { @@ -56,9 +54,22 @@ func (o Option[A]) UnwrapOrFunc(f func() A) A { return ElimOption(o, f, func(a A) A { return a }) } +// Testing is a type passed to Test functions to manage test state. It has a +// subset of testing.T methods needed by Option.UnwrapOrFail and +// Result.UnwrapOrFail. +type Testing interface { + // Helper marks the calling function as a test helper function. + Helper() + + // Fatalf formats its arguments according to the format, analogous to + // Printf, and records the text in the error log, then marks the + // function as having failed and stops its execution. + Fatalf(format string, args ...any) +} + // UnwrapOrFail is used to extract a value from an option within a test // context. If the option is None, then the test fails. -func (o Option[A]) UnwrapOrFail(t *testing.T) A { +func (o Option[A]) UnwrapOrFail(t Testing) A { t.Helper() if o.isSome { diff --git a/fn/result.go b/fn/result.go index 93d2dd7d66b..ccb6833fb9a 100644 --- a/fn/result.go +++ b/fn/result.go @@ -2,7 +2,6 @@ package fn import ( "fmt" - "testing" ) // Result represents a value that can either be a success (T) or an error. @@ -111,7 +110,7 @@ func (r Result[T]) UnwrapOrElse(f func() T) T { } // UnwrapOrFail returns the success value or fails the test if it's an error. -func (r Result[T]) UnwrapOrFail(t *testing.T) T { +func (r Result[T]) UnwrapOrFail(t Testing) T { t.Helper() if r.IsErr() {