chore: make merging action config more resilient
This commit is contained in:
parent
a5c2aea3ac
commit
6ef578cc3e
2 changed files with 47 additions and 17 deletions
|
|
@ -6,6 +6,7 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/fatih/structs"
|
||||
"github.com/imdario/mergo"
|
||||
)
|
||||
|
||||
// ActionConfig defines an action to take on event
|
||||
|
|
@ -21,23 +22,8 @@ type ActionConfig struct {
|
|||
// Merge merges all non-nil properties of the additional config into the base config.
|
||||
// The receiver's config remains immutable.
|
||||
func (a ActionConfig) Merge(m ActionConfig) ActionConfig {
|
||||
if m.Mode != nil {
|
||||
a.Mode = m.Mode
|
||||
}
|
||||
if m.MinCurrent != nil {
|
||||
a.MinCurrent = m.MinCurrent
|
||||
}
|
||||
if m.MaxCurrent != nil {
|
||||
a.MaxCurrent = m.MaxCurrent
|
||||
}
|
||||
if m.MinSoc != nil {
|
||||
a.MinSoc = m.MinSoc
|
||||
}
|
||||
if m.TargetSoc != nil {
|
||||
a.TargetSoc = m.TargetSoc
|
||||
}
|
||||
if m.Priority != nil {
|
||||
a.Priority = m.Priority
|
||||
if err := mergo.MergeWithOverwrite(&a, m); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
|
|
|||
44
api/actionconfig_test.go
Normal file
44
api/actionconfig_test.go
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestMerge(t *testing.T) {
|
||||
pv := ModePV
|
||||
one := 1
|
||||
six := 6.0
|
||||
old := ActionConfig{
|
||||
Mode: &pv,
|
||||
Priority: &one,
|
||||
MinCurrent: &six,
|
||||
}
|
||||
|
||||
now := ModeNow
|
||||
two := 2
|
||||
three := 3
|
||||
new := ActionConfig{
|
||||
Mode: &now,
|
||||
MinSoc: &three,
|
||||
Priority: &two,
|
||||
}
|
||||
|
||||
dst := old.Merge(new)
|
||||
|
||||
// unmodified
|
||||
assert.Equal(t, old, ActionConfig{
|
||||
Mode: &pv,
|
||||
Priority: &one,
|
||||
MinCurrent: &six,
|
||||
}, "old modified")
|
||||
|
||||
// overwritten
|
||||
assert.Equal(t, dst, ActionConfig{
|
||||
Mode: &now,
|
||||
MinCurrent: &six,
|
||||
MinSoc: &three,
|
||||
Priority: &two,
|
||||
}, "new wrong")
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue