Skip to content

Commit

Permalink
Implement specter.UnwrapUnit (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
jwillp authored Sep 10, 2024
1 parent 9df068f commit 7cda1ca
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
9 changes: 9 additions & 0 deletions pkg/specter/unitloading.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,15 @@ func UnitOf[T any](v T, id UnitID, kind UnitKind, source Source) *WrappingUnit[T
}
}

func UnwrapUnit[T any](unit Unit) (value T, ok bool) {
w, ok := unit.(*WrappingUnit[T])
if !ok {
return value, false
}

return w.wrapped, true
}

func (w *WrappingUnit[T]) ID() UnitID {
return w.id
}
Expand Down
37 changes: 37 additions & 0 deletions pkg/specter/unitloading_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -410,3 +410,40 @@ func TestUnitLoaderAdapter(t *testing.T) {
assert.Nil(t, units)
})
}

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

0 comments on commit 7cda1ca

Please sign in to comment.