Skip to content

Commit

Permalink
Add Validate More Redis Config
Browse files Browse the repository at this point in the history
  • Loading branch information
tung.tq committed Dec 20, 2023
1 parent a49e0e4 commit 7eb9bcd
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 8 deletions.
15 changes: 15 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,26 @@ func (c MySQLConfig) PrintDSN() string {

func (c Config) validateRedisServers() {
serverIDs := map[uint32]struct{}{}
serverAddrs := map[string]struct{}{}

for _, s := range c.RedisServers {
if s.ID <= 0 {
panic("redis server id must not be empty")
}
if len(s.Addr) == 0 {
panic("redis server address must not be empty")
}

_, existed := serverIDs[s.ID]
if existed {
panic(fmt.Sprintf("duplicated redis server id '%d'", s.ID))
}
serverIDs[s.ID] = struct{}{}

_, existed = serverAddrs[s.Addr]
if existed {
panic(fmt.Sprintf("duplicated redis server address '%s'", s.Addr))
}
serverAddrs[s.Addr] = struct{}{}
}
}
61 changes: 53 additions & 8 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,58 @@ func TestLoadConfig(t *testing.T) {
}

func TestValidateServerIDs(t *testing.T) {
c := Config{
RedisServers: []RedisConfig{
{ID: 11},
{ID: 11},
},
}
assert.PanicsWithValue(t, "duplicated redis server id '11'", func() {
c.validateRedisServers()
t.Run("duplicated", func(t *testing.T) {
c := Config{
RedisServers: []RedisConfig{
{ID: 11, Addr: "localhost:6379"},
{ID: 11, Addr: "localhost:6380"},
},
}
assert.PanicsWithValue(t, "duplicated redis server id '11'", func() {
c.validateRedisServers()
})
})

t.Run("server id empty", func(t *testing.T) {
c := Config{
RedisServers: []RedisConfig{
{ID: 0},
},
}
assert.PanicsWithValue(t, "redis server id must not be empty", func() {
c.validateRedisServers()
})
})

t.Run("server addr empty", func(t *testing.T) {
c := Config{
RedisServers: []RedisConfig{
{
ID: 11,
Addr: "",
},
},
}
assert.PanicsWithValue(t, "redis server address must not be empty", func() {
c.validateRedisServers()
})
})

t.Run("server addr duplicated", func(t *testing.T) {
c := Config{
RedisServers: []RedisConfig{
{
ID: 11,
Addr: "addr1",
},
{
ID: 12,
Addr: "addr1",
},
},
}
assert.PanicsWithValue(t, "duplicated redis server address 'addr1'", func() {
c.validateRedisServers()
})
})
}

0 comments on commit 7eb9bcd

Please sign in to comment.