Skip to content

Commit

Permalink
feat: add delegate binding support (#107)
Browse files Browse the repository at this point in the history
Signed-off-by: Charles-Edouard Brétéché <[email protected]>
  • Loading branch information
eddycharly authored Sep 19, 2024
1 parent 9269200 commit 5e4e8ae
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 15 deletions.
12 changes: 11 additions & 1 deletion pkg/binding/binding.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,18 @@ func (b *binding) Value() (any, error) {
return b.value, nil
}

func NewBinding(value any) Binding {
func NewBinding(value any) *binding {
return &binding{
value: value,
}
}

type delegate func() (any, error)

func (b delegate) Value() (any, error) {
return b()
}

func NewDelegate(delegate func() (any, error)) delegate {
return delegate
}
68 changes: 54 additions & 14 deletions pkg/binding/binding_test.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
package binding

import (
"reflect"
"testing"

"github.com/stretchr/testify/assert"
)

func TestNewBinding(t *testing.T) {
tests := []struct {
name string
value any
want Binding
want *binding
}{{
name: "nil",
value: nil,
Expand All @@ -29,9 +30,8 @@ func TestNewBinding(t *testing.T) {
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := NewBinding(tt.value); !reflect.DeepEqual(got, tt.want) {
t.Errorf("NewBinding() = %v, want %v", got, tt.want)
}
got := NewBinding(tt.value)
assert.Equal(t, tt.want, got)
})
}
}
Expand Down Expand Up @@ -65,16 +65,56 @@ func Test_binding_Value(t *testing.T) {
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := &binding{
value: tt.value,
}
got, err := b.Value()
if (err != nil) != tt.wantErr {
t.Errorf("binding.Value() error = %v, wantErr %v", err, tt.wantErr)
return
subj := NewBinding(tt.value)
got, err := subj.Value()
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("binding.Value() = %v, want %v", got, tt.want)
})
}
}

func Test_delegate_Value(t *testing.T) {
tests := []struct {
name string
value any
want any
wantErr bool
}{{
name: "nil",
value: nil,
want: nil,
wantErr: false,
}, {
name: "int",
value: int(42),
want: int(42),
wantErr: false,
}, {
name: "string",
value: "42",
want: "42",
wantErr: false,
}, {
name: "array",
value: []any{"42", 42},
want: []any{"42", 42},
wantErr: false,
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
subj := NewDelegate(func() (any, error) {
return tt.value, nil
})
got, err := subj.Value()
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
}
})
}
Expand Down

0 comments on commit 5e4e8ae

Please sign in to comment.