Browse Source

Merge pull request #5298 from purpleidea/feat/newurlsmap

pkg/types: Build a urls map from a string map
Xiang Li 9 years ago
parent
commit
29c77dee74
2 changed files with 56 additions and 2 deletions
  1. 14 0
      pkg/types/urlsmap.go
  2. 42 2
      pkg/types/urlsmap_test.go

+ 14 - 0
pkg/types/urlsmap.go

@@ -40,6 +40,20 @@ func NewURLsMap(s string) (URLsMap, error) {
 	return cl, nil
 }
 
+// NewURLsMapFromStringMap takes a map of strings and returns a URLsMap. The
+// string values in the map can be multiple values separated by the sep string.
+func NewURLsMapFromStringMap(m map[string]string, sep string) (URLsMap, error) {
+	var err error
+	um := URLsMap{}
+	for k, v := range m {
+		um[k], err = NewURLs(strings.Split(v, sep))
+		if err != nil {
+			return nil, err
+		}
+	}
+	return um, nil
+}
+
 // String turns URLsMap into discovery-formatted name-to-URLs sorted by name.
 func (c URLsMap) String() string {
 	var pairs []string

+ 42 - 2
pkg/types/urlsmap_test.go

@@ -15,10 +15,9 @@
 package types
 
 import (
+	"github.com/coreos/etcd/pkg/testutil"
 	"reflect"
 	"testing"
-
-	"github.com/coreos/etcd/pkg/testutil"
 )
 
 func TestParseInitialCluster(t *testing.T) {
@@ -113,3 +112,44 @@ func TestNewURLsMapIPV6(t *testing.T) {
 		t.Errorf("cluster = %#v, want %#v", c, wc)
 	}
 }
+
+func TestNewURLsMapFromStringMapEmpty(t *testing.T) {
+	mss := make(map[string]string)
+	urlsMap, err := NewURLsMapFromStringMap(mss, ",")
+	if err != nil {
+		t.Errorf("Unexpected error: %v", err)
+	}
+	s := ""
+	um, err := NewURLsMap(s)
+	if err != nil {
+		t.Errorf("Unexpected error: %v", err)
+	}
+
+	if um.String() != urlsMap.String() {
+		t.Errorf("Expected:\n%+v\ngot:\n%+v", um, urlsMap)
+	}
+}
+
+func TestNewURLsMapFromStringMapNormal(t *testing.T) {
+	mss := make(map[string]string)
+	mss["host0"] = "http://127.0.0.1:2379,http://127.0.0.1:2380"
+	mss["host1"] = "http://127.0.0.1:2381,http://127.0.0.1:2382"
+	mss["host2"] = "http://127.0.0.1:2383,http://127.0.0.1:2384"
+	mss["host3"] = "http://127.0.0.1:2385,http://127.0.0.1:2386"
+	urlsMap, err := NewURLsMapFromStringMap(mss, ",")
+	if err != nil {
+		t.Errorf("Unexpected error: %v", err)
+	}
+	s := "host0=http://127.0.0.1:2379,host0=http://127.0.0.1:2380," +
+		"host1=http://127.0.0.1:2381,host1=http://127.0.0.1:2382," +
+		"host2=http://127.0.0.1:2383,host2=http://127.0.0.1:2384," +
+		"host3=http://127.0.0.1:2385,host3=http://127.0.0.1:2386"
+	um, err := NewURLsMap(s)
+	if err != nil {
+		t.Errorf("Unexpected error: %v", err)
+	}
+
+	if um.String() != urlsMap.String() {
+		t.Errorf("Expected:\n%+v\ngot:\n%+v", um, urlsMap)
+	}
+}