Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API Keys: Use OpenAPI for tests #1211

Merged
merged 1 commit into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ require (
github.com/go-openapi/strfmt v0.21.8
github.com/grafana/amixr-api-go-client v0.0.11
github.com/grafana/grafana-api-golang-client v0.26.0
github.com/grafana/grafana-openapi-client-go v0.0.0-20231129154433-006c3acf5e73
github.com/grafana/grafana-openapi-client-go v0.0.0-20231208125730-b6492d2ae05f
github.com/grafana/machine-learning-go-client v0.5.0
github.com/grafana/synthetic-monitoring-agent v0.19.1
github.com/grafana/synthetic-monitoring-api-go-client v0.7.0
Expand Down Expand Up @@ -44,7 +44,7 @@ require (
github.com/go-openapi/loads v0.21.2 // indirect
github.com/go-openapi/spec v0.20.9 // indirect
github.com/go-openapi/swag v0.22.4 // indirect
github.com/go-openapi/validate v0.22.2 // indirect
github.com/go-openapi/validate v0.22.3 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/go-cmp v0.6.0 // indirect
Expand Down
8 changes: 4 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ github.com/go-openapi/swag v0.21.1/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/e
github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14=
github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogBU=
github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14=
github.com/go-openapi/validate v0.22.2 h1:Lda8nadL/5kIvS5mdXCAIuZ7IVXvKFIppLnw+EZh+n0=
github.com/go-openapi/validate v0.22.2/go.mod h1:kVxh31KbfsxU8ZyoHaDbLBWU5CnMdqBUEtadQ2G4d5M=
github.com/go-openapi/validate v0.22.3 h1:KxG9mu5HBRYbecRb37KRCihvGGtND2aXziBAv0NNfyI=
github.com/go-openapi/validate v0.22.3/go.mod h1:kVxh31KbfsxU8ZyoHaDbLBWU5CnMdqBUEtadQ2G4d5M=
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/gobs/pretty v0.0.0-20180724170744-09732c25a95b h1:/vQ+oYKu+JoyaMPDsv5FzwuL2wwWBgBbtj/YLCi4LuA=
Expand Down Expand Up @@ -116,8 +116,8 @@ github.com/grafana/amixr-api-go-client v0.0.11 h1:jlE+5t0tRuCtjbpM81j70Dr2J4eCyS
github.com/grafana/amixr-api-go-client v0.0.11/go.mod h1:N6x26XUrM5zGtK5zL5vNJnAn2JFMxLFPPLTw/6pDkFE=
github.com/grafana/grafana-api-golang-client v0.26.0 h1:Eu2YsfUezYngy8ifvmLybgluIcn/2IS9u1xkzuYstEM=
github.com/grafana/grafana-api-golang-client v0.26.0/go.mod h1:uNLZEmgKtTjHBtCQMwNn3qsx2mpMb8zU+7T4Xv3NR9Y=
github.com/grafana/grafana-openapi-client-go v0.0.0-20231129154433-006c3acf5e73 h1:OjE71HRSldBF/6GypUB/6rS3ENHYnxYdKE4PpQ+aCug=
github.com/grafana/grafana-openapi-client-go v0.0.0-20231129154433-006c3acf5e73/go.mod h1:nPuLRjbjyil4xL658KpMAjKodgI0pUt/OdaCJ11lJQM=
github.com/grafana/grafana-openapi-client-go v0.0.0-20231208125730-b6492d2ae05f h1:BYEmWlwwy+f8kI1nB4orGxvFQV1P2zXU+M/Xy8y/D/0=
github.com/grafana/grafana-openapi-client-go v0.0.0-20231208125730-b6492d2ae05f/go.mod h1:LwkzHzVOQG/fFIZmPvLxU2SrtLyxx+YAkx6ykw5sTfQ=
github.com/grafana/machine-learning-go-client v0.5.0 h1:Q1K+MPSy8vfMm2jsk3WQ7O77cGr2fM5hxwtPSoPc5NU=
github.com/grafana/machine-learning-go-client v0.5.0/go.mod h1:QFfZz8NkqVF8++skjkKQXJEZfpCYd8S0yTWJUpsLLTA=
github.com/grafana/synthetic-monitoring-agent v0.19.1 h1:ImH6JG8ZJ1h+KP7lJV6nkYyImAXtEthMaoLRpP4Hd0M=
Expand Down
17 changes: 17 additions & 0 deletions internal/resources/grafana/common_check_exists_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"strconv"
"strings"

"github.com/go-openapi/runtime"
goapi "github.com/grafana/grafana-openapi-client-go/client"
"github.com/grafana/grafana-openapi-client-go/client/api_keys"
"github.com/grafana/grafana-openapi-client-go/models"
"github.com/grafana/terraform-provider-grafana/internal/common"
"github.com/grafana/terraform-provider-grafana/internal/resources/grafana"
Expand All @@ -32,6 +34,21 @@ var (
return payloadOrError(resp, err)
},
)
apiKeyCheckExists = newCheckExistsHelper(
func(k *models.APIKeyDTO) string { return strconv.FormatInt(k.ID, 10) },
func(client *goapi.GrafanaHTTPAPI, id string) (*models.APIKeyDTO, error) {
resp, err := client.APIKeys.GetAPIkeys(api_keys.NewGetAPIkeysParams())
if err != nil {
return nil, err
}
for _, k := range resp.Payload {
if strconv.FormatInt(k.ID, 10) == id {
return k, nil
}
}
return nil, &runtime.APIError{Code: 404}
},
)
annotationsCheckExists = newCheckExistsHelper(
func(a *models.Annotation) string { return strconv.FormatInt(a.ID, 10) },
func(client *goapi.GrafanaHTTPAPI, id string) (*models.Annotation, error) {
Expand Down
86 changes: 15 additions & 71 deletions internal/resources/grafana/resource_api_key_test.go
Original file line number Diff line number Diff line change
@@ -1,33 +1,29 @@
package grafana_test

import (
"errors"
"fmt"
"strconv"
"testing"

"github.com/grafana/grafana-openapi-client-go/models"
"github.com/grafana/terraform-provider-grafana/internal/common"
"github.com/grafana/terraform-provider-grafana/internal/resources/grafana"
"github.com/grafana/terraform-provider-grafana/internal/testutils"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func TestAccGrafanaAuthKey_basic(t *testing.T) {
testutils.CheckOSSTestsEnabled(t)

var apiKey models.APIKeyDTO
testName := acctest.RandString(10)

resource.ParallelTest(t, resource.TestCase{
ProviderFactories: testutils.ProviderFactories,
CheckDestroy: testAccGrafanaAuthKeyCheckDestroy,
CheckDestroy: apiKeyCheckExists.destroyed(&apiKey, nil),
Steps: []resource.TestStep{
{
Config: testAccGrafanaAuthKeyConfig(testName, "Admin", 0, false),
Check: resource.ComposeTestCheckFunc(
testAccGrafanaAuthKeyCheckExists,
apiKeyCheckExists.exists("grafana_api_key.foo", &apiKey),
resource.TestMatchResourceAttr("grafana_api_key.foo", "id", defaultOrgIDRegexp),
resource.TestCheckResourceAttr("grafana_api_key.foo", "org_id", "1"),
resource.TestCheckResourceAttrSet("grafana_api_key.foo", "key"),
Expand All @@ -39,7 +35,7 @@ func TestAccGrafanaAuthKey_basic(t *testing.T) {
{
Config: testAccGrafanaAuthKeyConfig(testName+"-modified", "Viewer", 300, false),
Check: resource.ComposeTestCheckFunc(
testAccGrafanaAuthKeyCheckExists,
apiKeyCheckExists.exists("grafana_api_key.foo", &apiKey),
resource.TestMatchResourceAttr("grafana_api_key.foo", "id", defaultOrgIDRegexp),
resource.TestCheckResourceAttrSet("grafana_api_key.foo", "key"),
resource.TestCheckResourceAttr("grafana_api_key.foo", "name", testName+"-modified"),
Expand All @@ -55,16 +51,17 @@ func TestAccGrafanaAuthKey_inOrg(t *testing.T) {
testutils.CheckOSSTestsEnabled(t)

var org models.OrgDetailsDTO
var apiKey models.APIKeyDTO
testName := acctest.RandString(10)

resource.ParallelTest(t, resource.TestCase{
ProviderFactories: testutils.ProviderFactories,
CheckDestroy: testAccGrafanaAuthKeyCheckDestroy,
CheckDestroy: orgCheckExists.destroyed(&org, nil),
Steps: []resource.TestStep{
{
Config: testAccGrafanaAuthKeyConfig(testName, "Admin", 0, true),
Check: resource.ComposeTestCheckFunc(
testAccGrafanaAuthKeyCheckExists,
apiKeyCheckExists.exists("grafana_api_key.foo", &apiKey),
resource.TestCheckResourceAttrSet("grafana_api_key.foo", "key"),
resource.TestCheckResourceAttr("grafana_api_key.foo", "name", testName),
resource.TestCheckResourceAttr("grafana_api_key.foo", "role", "Admin"),
Expand All @@ -76,71 +73,18 @@ func TestAccGrafanaAuthKey_inOrg(t *testing.T) {
checkResourceIsInOrg("grafana_api_key.foo", "grafana_organization.test"),
),
},
// Check API key deletion within an organization
{
Config: testutils.WithoutResource(t, testAccGrafanaAuthKeyConfig(testName, "Admin", 0, true), "grafana_api_key.foo"),
Check: resource.ComposeTestCheckFunc(
orgCheckExists.exists("grafana_organization.test", &org),
apiKeyCheckExists.destroyed(&apiKey, &org),
),
},
},
})
}

func testAccGrafanaAuthKeyCheckExists(s *terraform.State) error {
return testAccGrafanaAuthKeyCheckExistsBool(s, true)
}

func testAccGrafanaAuthKeyCheckDestroy(s *terraform.State) error {
return testAccGrafanaAuthKeyCheckExistsBool(s, false)
}

func testAccGrafanaAuthKeyCheckExistsBool(s *terraform.State, shouldExist bool) error {
c := testutils.Provider.Meta().(*common.Client).GrafanaAPI

for _, rs := range s.RootModule().Resources {
if rs.Type != "grafana_api_key" {
continue
}

orgID, idStr := grafana.SplitOrgResourceID(rs.Primary.ID)
id, err := strconv.ParseInt(idStr, 10, 32)
if err != nil {
return err
}

// If orgID > 1, always check that they key doesn't exist in the default org
if orgID > 1 {
keys, err := c.GetAPIKeys(false)
if err != nil {
return err
}

for _, key := range keys {
if key.ID == id {
return errors.New("API key exists in the default org")
}
}

c = c.WithOrgID(orgID)
}

keys, err := c.GetAPIKeys(false)
if err != nil {
return err
}

for _, key := range keys {
if key.ID == id {
if shouldExist {
return nil
} else {
return errors.New("API key still exists")
}
}
}

if shouldExist {
return errors.New("API key was not found")
}
}

return nil
}

func testAccGrafanaAuthKeyConfig(name, role string, secondsToLive int, inOrg bool) string {
config := ""

Expand Down
9 changes: 4 additions & 5 deletions internal/resources/grafana/resource_folder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"strings"
"testing"

gapi "github.com/grafana/grafana-api-golang-client"
"github.com/grafana/grafana-openapi-client-go/models"

"github.com/grafana/terraform-provider-grafana/internal/common"
Expand Down Expand Up @@ -244,18 +243,18 @@ func TestAccFolder_createFromDifferentRoles(t *testing.T) {
var name = acctest.RandomWithPrefix(tc.role + "-key")

// Create an API key with the correct role and inject it in envvars. This auth will be used when the test runs
client := testutils.Provider.Meta().(*common.Client).GrafanaAPI
key, err := client.CreateAPIKey(gapi.CreateAPIKeyRequest{
client := grafana.OAPIGlobalClient(testutils.Provider.Meta())
resp, err := client.APIKeys.AddAPIkey(&models.AddAPIKeyCommand{
Name: name,
Role: tc.role,
})
if err != nil {
t.Fatal(err)
}
defer client.DeleteAPIKey(key.ID)
defer client.APIKeys.DeleteAPIkey(resp.Payload.ID)
oldValue := os.Getenv("GRAFANA_AUTH")
defer os.Setenv("GRAFANA_AUTH", oldValue)
os.Setenv("GRAFANA_AUTH", key.Key)
os.Setenv("GRAFANA_AUTH", resp.Payload.Key)

config := fmt.Sprintf(`
resource "grafana_folder" "bar" {
Expand Down