Skip to content

Commit

Permalink
Merge pull request #14 from docker/fix-tests
Browse files Browse the repository at this point in the history
Fix tests
  • Loading branch information
ryanhristovski authored Aug 20, 2024
2 parents 5cef48e + 22d142a commit c6bad93
Show file tree
Hide file tree
Showing 8 changed files with 133 additions and 50 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Ignore Terraform state files
*.tfstate
*.tfstate.backup
21 changes: 3 additions & 18 deletions internal/pkg/hubclient/client_access_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"context"
"encoding/json"
"fmt"
"io"
)

type AccessToken struct {
Expand Down Expand Up @@ -42,11 +41,6 @@ type AccessTokenPage struct {
Results []AccessToken `json:"results"`
}

type AccessTokenDeleteResponse struct {
Detail string `json:"detail"`
Message string `json:"message"`
}

func (c *Client) GetAccessToken(ctx context.Context, accessTokenID string) (AccessToken, error) {
if !isValidUUID(accessTokenID) {
return AccessToken{}, fmt.Errorf("accessTokenID is required")
Expand Down Expand Up @@ -77,21 +71,12 @@ func (c *Client) UpdateAccessToken(ctx context.Context, accessTokenID string, ac
return accessTokenUpdated, err
}

func (c *Client) DeleteAccessToken(ctx context.Context, accessTokenID string) (AccessTokenDeleteResponse, error) {
func (c *Client) DeleteAccessToken(ctx context.Context, accessTokenID string) error {
if !isValidUUID(accessTokenID) {
return AccessTokenDeleteResponse{}, fmt.Errorf("accessTokenID is required")
return fmt.Errorf("accessTokenID is required")
}

accessTokenDeleteResponse := AccessTokenDeleteResponse{}
err := c.sendRequest(ctx, "DELETE", fmt.Sprintf("/access-tokens/%s", accessTokenID), nil, &accessTokenDeleteResponse)
if err != nil {
// TODO: deleting access token returns a EOF, this is temporary to allow for tests to pass
if err == io.EOF {
fmt.Printf("Received EOF while deleting access token with ID: %s - Treating as successful deletion\n", accessTokenID)
return accessTokenDeleteResponse, nil
}
}
return accessTokenDeleteResponse, err
return c.sendRequest(ctx, "DELETE", fmt.Sprintf("/access-tokens/%s", accessTokenID), nil, nil)
}

func (c *Client) CreateAccessToken(ctx context.Context, accessToken AccessTokenCreateParams) (AccessToken, error) {
Expand Down
12 changes: 8 additions & 4 deletions internal/provider/data_source_repositories_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package provider

import (
"os"
"testing"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
Expand All @@ -13,21 +14,24 @@ func TestAccRepositoriesDataSource(t *testing.T) {
Steps: []resource.TestStep{
// Read testing
{
Config: testReposExampleDataSourceConfig,
Config: testReposExampleDataSourceConfig(),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("data.dockerhub_repositories.test", "id", "ryanhristovski/repositories"),
resource.TestCheckResourceAttr("data.dockerhub_repositories.test", "id", os.Getenv("DOCKERHUB_USERNAME")+"/repositories"),
),
},
},
})
}

const testReposExampleDataSourceConfig = `
func testReposExampleDataSourceConfig() string {
return `
provider "dockerhub" {
host = "https://hub-stage.docker.com/v2"
}
data "dockerhub_repositories" "test" {
namespace = "ryanhristovski"
namespace = "` + os.Getenv("DOCKERHUB_USERNAME") + `"
max_number_results = 10
}
`
}
8 changes: 1 addition & 7 deletions internal/provider/resource_access_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,6 @@ func (r *AccessTokenResource) Create(ctx context.Context, req resource.CreateReq
TokenLabel: data.TokenLabel.ValueString(),
}

// Log the request data
fmt.Printf("Creating access token with: %+v\n", createReq)

at, err := r.client.CreateAccessToken(ctx, createReq)
if err != nil {
resp.Diagnostics.AddError("Unable to create access token", err.Error())
Expand Down Expand Up @@ -183,9 +180,6 @@ func (r *AccessTokenResource) Update(ctx context.Context, req resource.UpdateReq
IsActive: fromPlan.IsActive.ValueBool(),
}

// Log the update request data
fmt.Printf("Updating access token with: %+v\n", updateReq)

at, err := r.client.UpdateAccessToken(ctx, fromState.UUID.ValueString(), updateReq)
if err != nil {
resp.Diagnostics.AddError("Unable to update access token", err.Error())
Expand All @@ -210,7 +204,7 @@ func (r *AccessTokenResource) Delete(ctx context.Context, req resource.DeleteReq
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)

_, err := r.client.DeleteAccessToken(ctx, data.UUID.ValueString())
err := r.client.DeleteAccessToken(ctx, data.UUID.ValueString())
if isNotFound(err) {
return
} else if err != nil {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package provider
import (
"context"
"fmt"
"strings"
"log"

"github.com/docker/terraform-provider-dockerhub/internal/pkg/hubclient"
"github.com/docker/terraform-provider-dockerhub/internal/pkg/repositoryutils"
Expand Down Expand Up @@ -77,14 +79,15 @@ func (r *RepositoryResource) Create(ctx context.Context, req resource.CreateRequ
createResp, err := r.client.CreateRepository(ctx, plan.Namespace.ValueString(), createReq)
if err != nil {
resp.Diagnostics.AddError("Docker Hub API error creating repository", "Could not create repository, unexpected error: "+err.Error())
return
}

id := repositoryutils.NewID(createResp.Namespace, createResp.Name)
plan.ID = types.StringValue(id)
plan.Name = types.StringValue(createResp.Name)
plan.Namespace = types.StringValue(createResp.Namespace)
plan.Description = types.StringValue(createResp.Description)
plan.FullDescription = types.StringValue(createResp.FullDescription)
plan.Description = stringNullIfEmpty(createResp.Description)
plan.FullDescription = stringNullIfEmpty(createResp.FullDescription)
plan.Private = types.BoolValue(createResp.IsPrivate)
plan.PullCount = types.Int64Value(createResp.PullCount)

Expand All @@ -95,18 +98,20 @@ func (r *RepositoryResource) Create(ctx context.Context, req resource.CreateRequ
}
}

// Delete implements resource.Resource.
func (r *RepositoryResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state RepositoryResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
log.Println("Error occurred while fetching the state")
return
}

err := r.client.DeleteRepository(ctx, state.ID.ValueString())
if err != nil {
log.Printf("Failed to delete repository with ID: %s, error: %v", state.ID.ValueString(), err)
resp.Diagnostics.AddError("Docker Hub API error deleting repository", "Could not delete repository, unexpected error: "+err.Error())
return
}
}

Expand Down Expand Up @@ -136,8 +141,8 @@ func (r *RepositoryResource) Read(ctx context.Context, req resource.ReadRequest,
state.ID = types.StringValue(repositoryutils.NewID(getResp.Namespace, getResp.Name))
state.Name = types.StringValue(getResp.Name)
state.Namespace = types.StringValue(getResp.Namespace)
state.Description = types.StringValue(getResp.Description)
state.FullDescription = types.StringValue(getResp.FullDescription)
state.Description = stringNullIfEmpty(getResp.Description)
state.FullDescription = stringNullIfEmpty(getResp.FullDescription)
state.Private = types.BoolValue(getResp.IsPrivate)
state.PullCount = types.Int64Value(getResp.PullCount)

Expand Down Expand Up @@ -179,7 +184,7 @@ func (r *RepositoryResource) Schema(_ context.Context, _ resource.SchemaRequest,
Optional: true,
},
"full_description": schema.StringAttribute{
MarkdownDescription: "Repository name",
MarkdownDescription: "Repository full description",
Required: false,
Optional: true,
},
Expand Down Expand Up @@ -223,7 +228,7 @@ func (r *RepositoryResource) Update(ctx context.Context, req resource.UpdateRequ

updateResp, err := r.client.UpdateRepository(ctx, plan.ID.ValueString(), updateReq)
if err != nil {
resp.Diagnostics.AddError("Docker Hub API error creating repository", "Could not create repository, unexpected error: "+err.Error())
resp.Diagnostics.AddError("Docker Hub API error updating repository", "Could not update repository, unexpected error: "+err.Error())
return
}

Expand All @@ -235,12 +240,41 @@ func (r *RepositoryResource) Update(ctx context.Context, req resource.UpdateRequ
}
}

plan.Description = types.StringValue(updateResp.Description)
plan.FullDescription = types.StringValue(updateResp.FullDescription)
plan.Description = stringNullIfEmpty(updateResp.Description)
plan.FullDescription = stringNullIfEmpty(updateResp.FullDescription)

diags = resp.State.Set(ctx, plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}

func stringNullIfEmpty(s string) types.String {
if s == "" {
return types.StringNull()
}
return types.StringValue(s)
}

func (r *RepositoryResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
// The ID passed during the import operation is expected to be in the form of "namespace/name"
idParts := strings.Split(req.ID, "/")
if len(idParts) != 2 {
resp.Diagnostics.AddError(
"Unexpected Import Identifier",
fmt.Sprintf("Expected import identifier with format 'namespace/name', got: %s", req.ID),
)
return
}

namespace := idParts[0]
name := idParts[1]

// Set the ID, namespace, and name in the state
resp.Diagnostics.Append(resp.State.Set(ctx, &RepositoryResourceModel{
ID: types.StringValue(req.ID),
Namespace: types.StringValue(namespace),
Name: types.StringValue(name),
})...)
}
17 changes: 5 additions & 12 deletions internal/provider/resource_repository_team_permission_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
func TestAccRepositoryTeamPermission(t *testing.T) {
orgName := "dockerterraform"
teamName := "test" + randString(10)
repoName := "timstest"
repoName := "test" + randString(10)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Expand All @@ -21,7 +21,7 @@ func TestAccRepositoryTeamPermission(t *testing.T) {
// create
Config: testAccRepositoryTeamPermission(orgName, teamName, repoName, hubclient.TeamRepoPermissionLevelRead),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrPair("dockerhub_repository_team_permission.test", "repo_id", "data.dockerhub_repository.test", "id"),
resource.TestCheckResourceAttrPair("dockerhub_repository_team_permission.test", "repo_id", "dockerhub_repository.test", "id"),
resource.TestCheckResourceAttrPair("dockerhub_repository_team_permission.test", "team_id", "dockerhub_org_team.test", "id"),
resource.TestCheckResourceAttr("dockerhub_repository_team_permission.test", "permission", hubclient.TeamRepoPermissionLevelRead),
),
Expand All @@ -36,7 +36,7 @@ func TestAccRepositoryTeamPermission(t *testing.T) {
},
ResourceName: "dockerhub_repository_team_permission.test",
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrPair("dockerhub_repository_team_permission.test", "repo_id", "data.dockerhub_repository.test", "id"),
resource.TestCheckResourceAttrPair("dockerhub_repository_team_permission.test", "repo_id", "dockerhub_repository.test", "id"),
resource.TestCheckResourceAttrPair("dockerhub_repository_team_permission.test", "team_id", "dockerhub_org_team.test", "id"),
resource.TestCheckResourceAttr("dockerhub_repository_team_permission.test", "permission", hubclient.TeamRepoPermissionLevelRead),
),
Expand All @@ -45,7 +45,7 @@ func TestAccRepositoryTeamPermission(t *testing.T) {
// update permission
Config: testAccRepositoryTeamPermission(orgName, teamName, repoName, hubclient.TeamRepoPermissionLevelAdmin),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrPair("dockerhub_repository_team_permission.test", "repo_id", "data.dockerhub_repository.test", "id"),
resource.TestCheckResourceAttrPair("dockerhub_repository_team_permission.test", "repo_id", "dockerhub_repository.test", "id"),
resource.TestCheckResourceAttrPair("dockerhub_repository_team_permission.test", "team_id", "dockerhub_org_team.test", "id"),
resource.TestCheckResourceAttr("dockerhub_repository_team_permission.test", "permission", hubclient.TeamRepoPermissionLevelAdmin),
),
Expand All @@ -70,13 +70,6 @@ resource "dockerhub_org_team" "test" {
}
resource "dockerhub_repository" "test" {
namespace = "%[1]s"
name = "%[3]s"
description = "Test Repository for Terraform"
full_description = "Full description for the test repository"
}
data "dockerhub_repository" "test" {
namespace = "%[1]s"
name = "%[3]s"
}`, orgName, teamName, repoName)
Expand All @@ -87,7 +80,7 @@ func testAccRepositoryTeamPermission(orgName, teamName, repoName string, permiss
%[1]s
resource "dockerhub_repository_team_permission" "test" {
repo_id = data.dockerhub_repository.test.id
repo_id = dockerhub_repository.test.id
team_id = dockerhub_org_team.test.id
permission = "%[2]s"
}
Expand Down
70 changes: 70 additions & 0 deletions internal/provider/resource_repository_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package provider

import (
"os"
"testing"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
)

func TestRepositoryResource(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{
Config: testRepositoryResourceConfig(),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrSet("dockerhub_repository.test", "id"),
resource.TestCheckResourceAttr("dockerhub_repository.test", "name", "example-repo"),
resource.TestCheckResourceAttr("dockerhub_repository.test", "namespace", os.Getenv("DOCKERHUB_USERNAME")),
resource.TestCheckResourceAttr("dockerhub_repository.test", "description", "Example repository"),
resource.TestCheckResourceAttr("dockerhub_repository.test", "full_description", ""),
resource.TestCheckResourceAttr("dockerhub_repository.test", "private", "false"),
),
},
{
Config: testRepositoryResourceConfigUpdated(),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("dockerhub_repository.test", "description", "Updated example repository"),
resource.TestCheckResourceAttr("dockerhub_repository.test", "full_description", ""),
resource.TestCheckResourceAttr("dockerhub_repository.test", "private", "true"),
),
},
{
ResourceName: "dockerhub_repository.test",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIdentifierAttribute: "id",
ImportStateIdFunc: func(state *terraform.State) (string, error) {
return state.RootModule().Resources["dockerhub_repository.test"].Primary.Attributes["id"], nil
},
},
},
})
}

func testRepositoryResourceConfig() string {
return `
resource "dockerhub_repository" "test" {
name = "example-repo"
namespace = "` + os.Getenv("DOCKERHUB_USERNAME") + `"
description = "Example repository"
full_description = ""
private = false
}
`
}

func testRepositoryResourceConfigUpdated() string {
return `
resource "dockerhub_repository" "test" {
name = "example-repo"
namespace = "` + os.Getenv("DOCKERHUB_USERNAME") + `"
description = "Updated example repository"
full_description = ""
private = true
}
`
}

0 comments on commit c6bad93

Please sign in to comment.