Skip to content

Commit

Permalink
Add UnwrapUnitSafe function
Browse files Browse the repository at this point in the history
  • Loading branch information
jwillp committed Sep 12, 2024
1 parent 76c4b58 commit 9e6ea5c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
5 changes: 5 additions & 0 deletions pkg/specter/unitloading.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ func UnwrapUnit[T any](unit Unit) (value T, ok bool) {
return v, ok
}

func UnwrapUnitSafe[T any](unit Unit) T {
t, _ := UnwrapUnit[T](unit)
return t
}

func (w *WrappingUnit) ID() UnitID {
return w.id
}
Expand Down
27 changes: 27 additions & 0 deletions pkg/specter/unitloading_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -447,3 +447,30 @@ func TestUnwrapUnit(t *testing.T) {
})
}
}

func TestUnwrapUnitSafe(t *testing.T) {

type testCase struct {
name string
when specter.Unit
then string
}
tests := []testCase{
{
name: "Unwrap of non wrapped unit should return zero value",
when: testutils.NewUnitStub("id", "kind", specter.Source{}),
then: "",
},
{
name: "Unwrap of a wrapped unit should return the value",
when: specter.UnitOf("hello", "id", "kind", specter.Source{}),
then: "hello",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotValue := specter.UnwrapUnitSafe[string](tt.when)
assert.Equal(t, tt.then, gotValue)
})
}
}

0 comments on commit 9e6ea5c

Please sign in to comment.