Skip to content

Commit

Permalink
fn: generalize type of t in UnwrapOrFail
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
starius committed Sep 19, 2024
1 parent 13a7bec commit 7c97536
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
17 changes: 14 additions & 3 deletions fn/option.go
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
3 changes: 1 addition & 2 deletions fn/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package fn

import (
"fmt"
"testing"
)

// Result represents a value that can either be a success (T) or an error.
Expand Down Expand Up @@ -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() {
Expand Down

0 comments on commit 7c97536

Please sign in to comment.