Skip to content

Commit

Permalink
add support to convert testcase variables from one type to an another
Browse files Browse the repository at this point in the history
  • Loading branch information
adamluzsi committed Feb 4, 2023
1 parent b1dd3c4 commit d75a913
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 0 deletions.
25 changes: 25 additions & 0 deletions let/As.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package let

import (
"fmt"
"github.com/adamluzsi/testcase"
"reflect"
)

func As[To, From any](Var testcase.Var[From]) testcase.Var[To] {
asID++
fromType := reflect.TypeOf((*From)(nil)).Elem()
toType := reflect.TypeOf((*To)(nil)).Elem()
if !fromType.ConvertibleTo(toType) {
panic(fmt.Sprintf("you can't have %s as %s", fromType.String(), toType.String()))
}
return testcase.Var[To]{
ID: fmt.Sprintf("%s AS %T #%d", Var.ID, *new(To), asID),
Init: func(t *testcase.T) To {
var rFrom = reflect.ValueOf(Var.Get(t))
return rFrom.Convert(toType).Interface().(To)
},
}
}

var asID int // adds extra safety that there won't be a name collision between two variables
49 changes: 49 additions & 0 deletions let/As_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package let_test

import (
"github.com/adamluzsi/testcase"
"github.com/adamluzsi/testcase/assert"
"github.com/adamluzsi/testcase/let"
"github.com/adamluzsi/testcase/sandbox"
"testing"
"time"
)

func TestAs(t *testing.T) {
t.Run("primitive type", func(t *testing.T) {
type MyString string

s := testcase.NewSpec(t)
v1 := let.String(s)
v2 := let.As[MyString](v1)

s.Test("", func(t *testcase.T) {
t.Must.Equal(MyString(v1.Get(t)), v2.Get(t))
})
})

t.Run("interface type", func(t *testing.T) {
type TimeAfterer interface {
After(u time.Time) bool
}

s := testcase.NewSpec(t)
v1 := let.Time(s)
v2 := let.As[TimeAfterer](v1)

s.Test("", func(t *testcase.T) {
t.Must.Equal(TimeAfterer(v1.Get(t)), v2.Get(t))
})
})

t.Run("panics on incorrect conversation", func(t *testing.T) {
ro := sandbox.Run(func() {
s := testcase.NewSpec(t)
v1 := let.Time(s)
_ = let.As[string](v1)
})
assert.False(t, ro.OK)
assert.False(t, ro.Goexit)
assert.NotNil(t, ro.PanicValue)
})
}
11 changes: 11 additions & 0 deletions let/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,14 @@ func ExampleWith_testcaseTFunc() {
t.Log(v.Get(t))
})
}

func ExampleAs() {
s := testcase.NewSpec((testing.TB)(nil))

type MyString string
str := let.As[MyString](let.String(s))

s.Test("", func(t *testcase.T) {
t.Log(str.Get(t))
})
}

0 comments on commit d75a913

Please sign in to comment.