GCE: Fix Valid() to check for proper region/zone names

pull/6/head
Bowei Du 2018-01-19 11:48:52 -08:00
parent 47b89aaf8f
commit a2b222c94e
2 changed files with 24 additions and 11 deletions

View File

@ -18,6 +18,7 @@ package meta
import (
"fmt"
"regexp"
)
// Key for a GCP resource.
@ -39,6 +40,11 @@ const (
Global = "global"
)
var (
// locationRegexp is the format of regions/zone names in GCE.
locationRegexp = regexp.MustCompile("^[a-z](?:[-a-z0-9]+)?$")
)
// ZonalKey returns the key for a zonal resource.
func ZonalKey(name, zone string) *Key {
return &Key{name, zone, ""}
@ -79,10 +85,16 @@ func (k Key) String() string {
}
// Valid is true if the key is valid.
func (k *Key) Valid(typeName string) bool {
func (k *Key) Valid() bool {
if k.Zone != "" && k.Region != "" {
return false
}
switch {
case k.Region != "":
return locationRegexp.Match([]byte(k.Region))
case k.Zone != "":
return locationRegexp.Match([]byte(k.Zone))
}
return true
}

View File

@ -58,18 +58,19 @@ func TestKeyValid(t *testing.T) {
zone := "us-central1-b"
for _, tc := range []struct {
key *Key
typeName string
want bool
key *Key
want bool
}{
// Note: these test cases need to be synchronized with the
// actual settings for each type.
{GlobalKey("abc"), "UrlMap", true},
{&Key{"abc", zone, region}, "UrlMap", false},
{GlobalKey("abc"), true},
{RegionalKey("abc", region), true},
{ZonalKey("abc", zone), true},
{RegionalKey("abc", "/invalid/"), false},
{ZonalKey("abc", "/invalid/"), false},
{&Key{"abc", zone, region}, false},
} {
valid := tc.key.Valid(tc.typeName)
if valid != tc.want {
t.Errorf("key %+v, type %v; key.Valid() = %v, want %v", tc.key, tc.typeName, valid, tc.want)
got := tc.key.Valid()
if got != tc.want {
t.Errorf("key %+v; key.Valid() = %v, want %v", tc.key, got, tc.want)
}
}
}