Skip to content

Commit

Permalink
Fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanhristovski committed Aug 20, 2024
1 parent 5cef48e commit b979c7c
Show file tree
Hide file tree
Showing 9 changed files with 189 additions and 46 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
41 changes: 41 additions & 0 deletions internal/provider/data_source_org_team_member_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package provider

import (
"os"
"testing"

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

func TestAccOrgTeamMemberDataSource(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
// Read testing
{
Config: testOrgTeamMemberDataSourceConfig(),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("data.dockerhub_org_team_member.test", "org_name", os.Getenv("DOCKERHUB_ORG_NAME")),
resource.TestCheckResourceAttr("data.dockerhub_org_team_member.test", "team_name", "example-team"),
resource.TestCheckResourceAttr("data.dockerhub_org_team_member.test", "members.#", "2"), // assuming there are two members
resource.TestCheckResourceAttr("data.dockerhub_org_team_member.test", "members.0.username", "user1"),
resource.TestCheckResourceAttr("data.dockerhub_org_team_member.test", "members.1.username", "user2"),
),
},
},
})
}

func testOrgTeamMemberDataSourceConfig() string {
return `
provider "dockerhub" {
host = "https://hub.docker.com/v2"
}
data "dockerhub_org_team_member" "test" {
org_name = "` + os.Getenv("DOCKERHUB_ORG_NAME") + `"
team_name = "example-team"
}
`
}
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"
"log"
"strings"

"github.com/docker/terraform-provider-dockerhub/internal/pkg/hubclient"
"github.com/docker/terraform-provider-dockerhub/internal/pkg/repositoryutils"
Expand Down Expand Up @@ -77,6 +79,7 @@ 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)
Expand All @@ -85,6 +88,9 @@ func (r *RepositoryResource) Create(ctx context.Context, req resource.CreateRequ
plan.Namespace = types.StringValue(createResp.Namespace)
plan.Description = types.StringValue(createResp.Description)
plan.FullDescription = types.StringValue(createResp.FullDescription)
if plan.FullDescription.IsNull() {
plan.FullDescription = types.StringValue("")
}
plan.Private = types.BoolValue(createResp.IsPrivate)
plan.PullCount = types.Int64Value(createResp.PullCount)

Expand All @@ -95,19 +101,31 @@ 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

// Log before getting the state
log.Println("Fetching the state for deletion")

diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
log.Println("Error occurred while fetching the state")
return
}

// Log before attempting to delete the repository
log.Printf("Attempting to delete repository with ID: %s", state.ID.ValueString())

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
}

// Log successful deletion
log.Printf("Successfully deleted repository with ID: %s", state.ID.ValueString())
}

// Metadata implements resource.Resource.
Expand Down Expand Up @@ -136,8 +154,11 @@ 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)
if state.FullDescription.IsNull() {
state.FullDescription = types.StringValue("")
}
state.Private = types.BoolValue(getResp.IsPrivate)
state.PullCount = types.Int64Value(getResp.PullCount)

Expand Down Expand Up @@ -179,7 +200,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 +244,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 @@ -237,10 +258,42 @@ func (r *RepositoryResource) Update(ctx context.Context, req resource.UpdateRequ

plan.Description = types.StringValue(updateResp.Description)
plan.FullDescription = types.StringValue(updateResp.FullDescription)
if plan.FullDescription.IsNull() {
plan.FullDescription = types.StringValue("")
}

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

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),
})...)
}

func stringNullIfEmpty(s string) types.String {
if s == "" {
return types.StringNull()
}
return types.StringValue(s)
}
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
Loading

0 comments on commit b979c7c

Please sign in to comment.