pkg/flags: fix UniqueURLs'Set to remove duplicates in UniqueURLs'uss

From the name of func 'UniqueURLsFromFlag', we can tell that UniqueURLs'uss
should not have duplicates. The current implemention of UniqueURLs'Set
has a bug to make it unique. This PR fixes it.

Signed-off-by: Jes Cok <xigua67damn@gmail.com>
This commit is contained in:
Jes Cok 2023-07-26 20:17:17 +08:00
parent 05d7c10043
commit 137cc0332f
2 changed files with 32 additions and 5 deletions

View File

@ -49,7 +49,11 @@ func (us *UniqueURLs) Set(s string) error {
us.Values = make(map[string]struct{})
us.uss = make([]url.URL, 0)
for _, v := range ss {
us.Values[v.String()] = struct{}{}
x := v.String()
if _, exists := us.Values[x]; exists {
continue
}
us.Values[x] = struct{}{}
us.uss = append(us.uss, v)
}
return nil

View File

@ -15,9 +15,12 @@
package flags
import (
"flag"
"net/url"
"reflect"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestValidateURLsValueBad(t *testing.T) {
@ -66,8 +69,28 @@ func TestNewURLsValue(t *testing.T) {
}
for i := range tests {
uu := []url.URL(*NewURLsValue(tests[i].s))
if !reflect.DeepEqual(tests[i].exp, uu) {
t.Fatalf("#%d: expected %+v, got %+v", i, tests[i].exp, uu)
}
require.Equal(t, tests[i].exp, uu)
}
}
func TestUniqueURLsFromFlag(t *testing.T) {
const name = "test"
urls := []string{
"https://1.2.3.4:1",
"https://1.2.3.4:2",
"https://1.2.3.4:3",
"https://1.2.3.4:1",
}
fs := flag.NewFlagSet(name, flag.ExitOnError)
u := NewUniqueURLsWithExceptions(strings.Join(urls, ","))
fs.Var(u, name, "usage")
uss := UniqueURLsFromFlag(fs, name)
require.Equal(t, len(u.Values), len(uss))
um := make(map[string]struct{})
for _, x := range uss {
um[x.String()] = struct{}{}
}
require.Equal(t, u.Values, um)
}