Skip to content

Commit

Permalink
project_id validated in datasource (#6691) (#12846)
Browse files Browse the repository at this point in the history
Signed-off-by: Modular Magician <magic-modules@google.com>

Signed-off-by: Modular Magician <magic-modules@google.com>
  • Loading branch information
modular-magician committed Oct 20, 2022
1 parent db21c4e commit e4e1fc6
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .changelog/6691.txt
@@ -0,0 +1,3 @@
```release-note:enhancement
cloudplatform: Validated `project_id` for `google_project` data-source
```
1 change: 1 addition & 0 deletions google/data_source_google_project.go
Expand Up @@ -12,6 +12,7 @@ func dataSourceGoogleProject() *schema.Resource {

addOptionalFieldsToSchema(dsSchema, "project_id")

dsSchema["project_id"].ValidateFunc = validateDSProjectID()
return &schema.Resource{
Read: datasourceGoogleProjectRead,
Schema: dsSchema,
Expand Down
14 changes: 14 additions & 0 deletions google/validation.go
Expand Up @@ -212,6 +212,20 @@ func validateProjectID() schema.SchemaValidateFunc {
}
}

func validateDSProjectID() schema.SchemaValidateFunc {
return func(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
ids := strings.Split(value, "/")
value = ids[len(ids)-1]

if !regexp.MustCompile("^" + ProjectRegex + "$").MatchString(value) {
errors = append(errors, fmt.Errorf(
"%q project_id must be 6 to 30 with lowercase letters, digits, hyphens and start with a letter. Trailing hyphens are prohibited.", value))
}
return
}
}

func validateProjectName() schema.SchemaValidateFunc {
return func(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
Expand Down
23 changes: 23 additions & 0 deletions google/validation_test.go
Expand Up @@ -271,6 +271,29 @@ func TestValidateProjectID(t *testing.T) {
}
}

func TestValidateDSProjectID(t *testing.T) {
x := []StringValidationTestCase{
// No errors
{TestName: "basic", Value: "foobar"},
{TestName: "with numbers", Value: "foobar123"},
{TestName: "short", Value: "foofoo"},
{TestName: "long", Value: "foobarfoobarfoobarfoobarfoobar"},
{TestName: "has projects", Value: "projects/foo-bar"},
{TestName: "has multiple projects", Value: "projects/projects/foobar"},
{TestName: "has a hyphen", Value: "foo-bar"},

// With errors
{TestName: "empty", Value: "", ExpectError: true},
{TestName: "has an uppercase letter", Value: "foo-Bar", ExpectError: true},
{TestName: "has a final hyphen", Value: "foo-bar-", ExpectError: true},
}

es := testStringValidationCases(x, validateDSProjectID())
if len(es) > 0 {
t.Errorf("Failed to validate project ID's: %v", es)
}
}

func TestValidateProjectName(t *testing.T) {
x := []StringValidationTestCase{
// No errors
Expand Down

0 comments on commit e4e1fc6

Please sign in to comment.