go-zero/core/discov/subscriber_test.go

196 lines
2.8 KiB
Go
Raw Normal View History

2020-07-30 22:56:39 +08:00
package discov
import (
"testing"
"zero/core/discov/internal"
"github.com/stretchr/testify/assert"
)
const (
actionAdd = iota
actionDel
)
func TestContainer(t *testing.T) {
type action struct {
act int
key string
val string
}
tests := []struct {
name string
do []action
expect []string
}{
{
name: "add one",
do: []action{
{
act: actionAdd,
key: "first",
val: "a",
},
},
expect: []string{
"a",
},
},
{
name: "add two",
do: []action{
{
act: actionAdd,
key: "first",
val: "a",
},
{
act: actionAdd,
key: "second",
val: "b",
},
},
expect: []string{
"a",
"b",
},
},
{
name: "add two, delete one",
do: []action{
{
act: actionAdd,
key: "first",
val: "a",
},
{
act: actionAdd,
key: "second",
val: "b",
},
{
act: actionDel,
key: "first",
},
},
2020-07-31 10:47:20 +08:00
expect: []string{"b"},
2020-07-30 22:56:39 +08:00
},
{
name: "add two, delete two",
do: []action{
{
act: actionAdd,
key: "first",
val: "a",
},
{
act: actionAdd,
key: "second",
val: "b",
},
{
act: actionDel,
key: "first",
2020-07-31 10:47:20 +08:00
},
{
act: actionDel,
key: "second",
},
},
expect: []string{},
},
{
name: "add three, dup values, delete two",
do: []action{
{
act: actionAdd,
key: "first",
2020-07-30 22:56:39 +08:00
val: "a",
},
2020-07-31 10:47:20 +08:00
{
act: actionAdd,
key: "second",
val: "b",
},
{
act: actionAdd,
key: "third",
val: "a",
},
{
act: actionDel,
key: "first",
},
2020-07-30 22:56:39 +08:00
{
act: actionDel,
key: "second",
2020-07-31 10:47:20 +08:00
},
},
expect: []string{"a"},
},
{
name: "add three, dup values, delete two, delete not added",
do: []action{
{
act: actionAdd,
key: "first",
val: "a",
},
{
act: actionAdd,
key: "second",
2020-07-30 22:56:39 +08:00
val: "b",
},
2020-07-31 10:47:20 +08:00
{
act: actionAdd,
key: "third",
val: "a",
},
{
act: actionDel,
key: "first",
},
{
act: actionDel,
key: "second",
},
{
act: actionDel,
key: "forth",
},
2020-07-30 22:56:39 +08:00
},
2020-07-31 10:47:20 +08:00
expect: []string{"a"},
2020-07-30 22:56:39 +08:00
},
}
2020-07-31 10:47:20 +08:00
exclusives := []bool{true, false}
2020-07-30 22:56:39 +08:00
for _, test := range tests {
2020-07-31 10:47:20 +08:00
for _, exclusive := range exclusives {
t.Run(test.name, func(t *testing.T) {
c := newContainer(exclusive)
2020-07-31 10:58:30 +08:00
assert.Nil(t, c.getValues())
2020-07-31 10:47:20 +08:00
for _, order := range test.do {
if order.act == actionAdd {
c.OnAdd(internal.KV{
Key: order.key,
Val: order.val,
})
} else {
c.OnDelete(internal.KV{
Key: order.key,
Val: order.val,
})
}
2020-07-30 22:56:39 +08:00
}
2020-07-31 11:14:48 +08:00
2020-07-31 10:47:20 +08:00
assert.True(t, c.dirty.True())
assert.ElementsMatch(t, test.expect, c.getValues())
assert.False(t, c.dirty.True())
assert.ElementsMatch(t, test.expect, c.getValues())
})
}
2020-07-30 22:56:39 +08:00
}
}