2022-09-14 03:38:22 +00:00
|
|
|
package dynamic
|
|
|
|
|
|
|
|
import (
|
2022-09-14 11:11:38 +00:00
|
|
|
"encoding/json"
|
2022-09-14 03:38:22 +00:00
|
|
|
"reflect"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Strategy struct {
|
2022-09-14 11:11:38 +00:00
|
|
|
Field1 fixedpoint.Value `json:"field1" modifiable:"true"`
|
|
|
|
Field2 float64 `json:"field2"`
|
|
|
|
field3 float64 `json:"field3" modifiable:"true"`
|
|
|
|
Field4 *fixedpoint.Value `json:"field4" modifiable:"true"`
|
2022-09-14 03:38:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestGetModifiableFields(t *testing.T) {
|
|
|
|
s := Strategy{}
|
|
|
|
val := reflect.ValueOf(s)
|
|
|
|
GetModifiableFields(val, func(tagName, name string) {
|
2022-09-14 11:11:38 +00:00
|
|
|
assert.NotEqual(t, tagName, "field2")
|
|
|
|
assert.NotEqual(t, name, "Field2")
|
|
|
|
assert.NotEqual(t, tagName, "field3")
|
|
|
|
assert.NotEqual(t, name, "Field3")
|
|
|
|
|
2022-09-14 03:38:22 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestGetModifiableField(t *testing.T) {
|
2022-09-14 11:11:38 +00:00
|
|
|
// val must be get from pointer.Elem(), otherwise the fields will be unaddressable
|
|
|
|
s := &Strategy{Field1: fixedpoint.NewFromInt(1)}
|
|
|
|
val := reflect.ValueOf(s).Elem()
|
2022-09-14 03:38:22 +00:00
|
|
|
_, ok := GetModifiableField(val, "Field1")
|
|
|
|
assert.True(t, ok)
|
|
|
|
_, ok = GetModifiableField(val, "Field2")
|
|
|
|
assert.False(t, ok)
|
|
|
|
_, ok = GetModifiableField(val, "Field3")
|
|
|
|
assert.False(t, ok)
|
|
|
|
_, ok = GetModifiableField(val, "Random")
|
|
|
|
assert.False(t, ok)
|
2022-09-14 11:11:38 +00:00
|
|
|
field, ok := GetModifiableField(val, "Field1")
|
|
|
|
assert.True(t, ok)
|
|
|
|
x := reflect.New(field.Type())
|
|
|
|
xi := x.Interface()
|
|
|
|
assert.NoError(t, json.Unmarshal([]byte("\"3.1415%\""), &xi))
|
|
|
|
assert.True(t, field.CanAddr())
|
|
|
|
field.Set(x.Elem())
|
|
|
|
assert.Equal(t, s.Field1.String(), "0.031415")
|
|
|
|
field, _ = GetModifiableField(val, "Field4")
|
|
|
|
x = reflect.New(field.Type())
|
|
|
|
xi = x.Interface()
|
|
|
|
assert.NoError(t, json.Unmarshal([]byte("311"), &xi))
|
|
|
|
field.Set(x.Elem())
|
|
|
|
assert.Equal(t, s.Field4.String(), "311")
|
2022-09-14 03:38:22 +00:00
|
|
|
}
|