Add CallFunctionWithRows() for help testing calls to QueryChunks

pull/2/head
Vinícius Garcia 2021-06-10 15:57:46 -03:00
parent 75330a12c5
commit 5b9b0dd00d
3 changed files with 43 additions and 15 deletions

View File

@ -5,7 +5,6 @@ import (
"testing"
gomock "github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
"github.com/tj/assert"
"github.com/vingarcia/ksql"
"github.com/vingarcia/ksql/nullable"
@ -198,19 +197,17 @@ func TestStreamAllUsers(t *testing.T) {
mockDB.EXPECT().QueryChunks(gomock.Any(), gomock.Any()).
DoAndReturn(func(ctx context.Context, parser ksql.ChunkParser) error {
fn, ok := parser.ForEachChunk.(func(users []UserEntity) error)
require.True(t, ok)
// Chunk 1:
err := fn([]UserEntity{
err := ksql.CallFunctionWithRows(parser.ForEachChunk, []map[string]interface{}{
{
ID: 1,
Name: nullable.String("fake name"),
Age: nullable.Int(42),
"id": 1,
"name": "fake name",
"age": 42,
},
{
ID: 2,
Name: nullable.String("another fake name"),
Age: nullable.Int(43),
"id": 2,
"name": "another fake name",
"age": 43,
},
})
if err != nil {
@ -218,11 +215,11 @@ func TestStreamAllUsers(t *testing.T) {
}
// Chunk 2:
err = fn([]UserEntity{
err = ksql.CallFunctionWithRows(parser.ForEachChunk, []map[string]interface{}{
{
ID: 3,
Name: nullable.String("yet another fake name"),
Age: nullable.Int(44),
"id": 3,
"name": "yet another fake name",
"age": 44,
},
})
return err

View File

@ -262,7 +262,7 @@ func FillSliceWith(entities interface{}, dbRows []map[string]interface{}) error
sliceType := sliceRef.Type()
if sliceType.Kind() != reflect.Ptr {
return fmt.Errorf(
"FillSliceWith: expected input to be a pointer to struct but got %v",
"FillSliceWith: expected input to be a pointer to a slice of structs but got %v",
sliceType,
)
}

31
test_helpers.go Normal file
View File

@ -0,0 +1,31 @@
package ksql
import (
"reflect"
"github.com/vingarcia/ksql/structs"
)
// CallFunctionWithRows was created for helping test the QueryChunks method
func CallFunctionWithRows(fn interface{}, rows []map[string]interface{}) error {
fnValue := reflect.ValueOf(fn)
chunkType, err := parseInputFunc(fn)
if err != nil {
return err
}
chunk := reflect.MakeSlice(chunkType, 0, len(rows))
// Create a pointer to a slice (required by FillSliceWith)
chunkPtr := reflect.New(chunkType)
chunkPtr.Elem().Set(chunk)
err = structs.FillSliceWith(chunkPtr.Interface(), rows)
if err != nil {
return err
}
err, _ = fnValue.Call([]reflect.Value{chunkPtr.Elem()})[0].Interface().(error)
return err
}