terraform-provider-docker/internal/provider/resource_docker_registry_image_test.go
Manuel Vogel 0588c2071b
chore/refactor tests (#201)
* chore: format test configs for datasources

* chore: outlines load test config helper and structure

* docs(contributing): add command for resouce tests

to have an example of the regex

* refactor: move container test configs into separate files

* fix: add insecure_skip_verify for image pulls

to fix the local test setup with invalid certs

* chore(ci): remove insecure registry adaption

* chore: regenerate website

* chore: update gitignore for scipts/testing dir

* fix: replace nodejs services with go versions

* fix: move testing program versions in separate files

* test: reactivate flaky test from travis

* chore: fix linter on all go files

* fix(linter): testing go servers

* chore(ci): add env for go version

* chore(ci): name workflow steps

also moves description of available docker versions in to acc dockerfile

* Revert "test: reactivate flaky test from travis"

This reverts commit b02654acc4d6b7d02c8f3ba090e6a3f248741b10.

* docs: fix provider-ssh example

* chore: use alpine als final image for tests

* refactor: move test configs from folder into testname.tf files

* refactor: image delete log is now debug and indented

* refactor: image test config into seprate files

* refactor: move network test config into seperate files

* refactor: move plugin test config into seperate files

* chore: rename registry image test file

* refactor: move registry_image test config into seperate files

* chore: format secret test configs

* refactor: inline volume test configs

* fix: remove unused volume label test function

* refactor: move service test configs into seperate files

* test: reactivate and fix service test

* chore: simplify insecure skip verify add to http client

* chore(ci): debug into service test

* chore(ci): add testacc setup

* chore: format tf config for provider test

* chore(ci): add debug output for config.json

* fix: check service auth for emptyness

* fix: remove re-read of provider auth config

because the bug occured only in CI as the meta object might be GCd

* test: pass auth to service instead of provider

* chore: reactivate all acc tests

* test: outlines service inspect json check for full spec

* test: add service inspect json checks

* test: finish service inspect json checks

* chore(service): move test helper to end to of the file

* chore: move mapEquals to test helpers

* test: add json inspect for config

* chore: add debug inspect log for plugin, secret and volume

* test: add json inspect for secret

* test: add json inspect for image

* test: add json inspect for network

* test: add json inspect for plugin

* test: add json inspect for volume

* test: inline ds plugin test configs

* test: inline network configs

* test: move ds reg image configs into separate files

* test: reactivates container upload checks

* chore: adapt issues ref from old to new xw repo

* fix: reactivate network ingress test

and provide helpers for removing the default ingress network and leaving the swamr

* docs: rerun website gen

* test: fix reg image build and keep test

* chore: add name to todo

* chore: move ds network and plugin specs to file

* chore: format provider test spec

* chore: use simpler error message for empty strings
2021-05-31 16:11:49 +09:00

196 lines
7.8 KiB
Go

package provider
import (
"context"
"fmt"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"testing"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/go-units"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)
func TestAccDockerRegistryImageResource_mapping(t *testing.T) {
assert := func(condition bool, msg string) {
if !condition {
t.Errorf("assertion failed: wrong build parameter %s", msg)
}
}
dummyProvider := New("dev")()
dummyResource := dummyProvider.ResourcesMap["docker_registry_image"]
dummyResource.CreateContext = func(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
build := d.Get("build").([]interface{})[0].(map[string]interface{})
options := createImageBuildOptions(build)
assert(options.SuppressOutput == true, "SuppressOutput")
assert(options.RemoteContext == "fooRemoteContext", "RemoteContext")
assert(options.NoCache == true, "NoCache")
assert(options.Remove == true, "Remove")
assert(options.ForceRemove == true, "ForceRemove")
assert(options.PullParent == true, "PullParent")
assert(options.Isolation == container.Isolation("hyperv"), "Isolation")
assert(options.CPUSetCPUs == "fooCpuSetCpus", "CPUSetCPUs")
assert(options.CPUSetMems == "fooCpuSetMems", "CPUSetMems")
assert(options.CPUShares == int64(4), "CPUShares")
assert(options.CPUQuota == int64(5), "CPUQuota")
assert(options.CPUPeriod == int64(6), "CPUPeriod")
assert(options.Memory == int64(1), "Memory")
assert(options.MemorySwap == int64(2), "MemorySwap")
assert(options.CgroupParent == "fooCgroupParent", "CgroupParent")
assert(options.NetworkMode == "fooNetworkMode", "NetworkMode")
assert(options.ShmSize == int64(3), "ShmSize")
assert(options.Dockerfile == "fooDockerfile", "Dockerfile")
assert(len(options.Ulimits) == 1, "Ulimits")
assert(reflect.DeepEqual(*options.Ulimits[0], units.Ulimit{
Name: "foo",
Hard: int64(1),
Soft: int64(2),
}), "Ulimits")
assert(len(options.BuildArgs) == 1, "BuildArgs")
// DevSkim: ignore DS137138
assert(*options.BuildArgs["HTTP_PROXY"] == "http://10.20.30.2:1234", "BuildArgs")
assert(len(options.AuthConfigs) == 1, "AuthConfigs")
assert(reflect.DeepEqual(options.AuthConfigs["foo.host"], types.AuthConfig{
Username: "fooUserName",
Password: "fooPassword",
Auth: "fooAuth",
Email: "fooEmail",
ServerAddress: "fooServerAddress",
IdentityToken: "fooIdentityToken",
RegistryToken: "fooRegistryToken",
}), "AuthConfigs")
assert(reflect.DeepEqual(options.Labels, map[string]string{"foo": "bar"}), "Labels")
assert(options.Squash == true, "Squash")
assert(reflect.DeepEqual(options.CacheFrom, []string{"fooCacheFrom", "barCacheFrom"}), "CacheFrom")
assert(reflect.DeepEqual(options.SecurityOpt, []string{"fooSecurityOpt", "barSecurityOpt"}), "SecurityOpt")
assert(reflect.DeepEqual(options.ExtraHosts, []string{"fooExtraHost", "barExtraHost"}), "ExtraHosts")
assert(options.Target == "fooTarget", "Target")
assert(options.SessionID == "fooSessionId", "SessionID")
assert(options.Platform == "fooPlatform", "Platform")
assert(options.Version == types.BuilderVersion("1"), "Version")
assert(options.BuildID == "fooBuildId", "BuildID")
// output
d.SetId("foo")
d.Set("sha256_digest", "bar")
return nil
}
dummyResource.UpdateContext = func(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
return nil
}
dummyResource.DeleteContext = func(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
return nil
}
dummyResource.ReadContext = func(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
d.Set("sha256_digest", "bar")
return nil
}
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: map[string]func() (*schema.Provider, error){
"docker": func() (*schema.Provider, error) {
return dummyProvider, nil
},
},
Steps: []resource.TestStep{
{
Config: loadTestConfiguration(t, RESOURCE, "docker_registry_image", "testBuildDockerRegistryImageMappingConfig"),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrSet("docker_registry_image.foo", "sha256_digest"),
),
},
},
})
}
func TestAccDockerRegistryImageResource_build(t *testing.T) {
pushOptions := createPushImageOptions("127.0.0.1:15000/tftest-dockerregistryimage:1.0")
wd, _ := os.Getwd()
context := strings.ReplaceAll((filepath.Join(wd, "..", "..", "scripts", "testing", "docker_registry_image_context")), "\\", "\\\\")
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: fmt.Sprintf(loadTestConfiguration(t, RESOURCE, "docker_registry_image", "testBuildDockerRegistryImageNoKeepConfig"), pushOptions.Registry, pushOptions.Name, context),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrSet("docker_registry_image.foo", "sha256_digest"),
),
},
},
CheckDestroy: testDockerRegistryImageNotInRegistry(pushOptions),
})
}
func TestAccDockerRegistryImageResource_buildAndKeep(t *testing.T) {
pushOptions := createPushImageOptions("127.0.0.1:15000/tftest-dockerregistryimage:1.0")
wd, _ := os.Getwd()
context := strings.ReplaceAll(filepath.Join(wd, "..", "..", "scripts", "testing", "docker_registry_image_context"), "\\", "\\\\")
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: fmt.Sprintf(loadTestConfiguration(t, RESOURCE, "docker_registry_image", "testBuildDockerRegistryImageKeepConfig"), pushOptions.Registry, pushOptions.Name, context),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrSet("docker_registry_image.foo", "sha256_digest"),
),
},
},
// as the providerConfig obtained from testAccProvider.Meta().(*ProviderConfig)
// is empty after the test the credetials are passed here manually
CheckDestroy: testDockerRegistryImageInRegistry("testuser", "testpwd", pushOptions, true),
})
}
func TestAccDockerRegistryImageResource_pushMissingImage(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: loadTestConfiguration(t, RESOURCE, "docker_registry_image", "testDockerRegistryImagePushMissingConfig"),
ExpectError: regexp.MustCompile("An image does not exist locally"),
},
},
})
}
func testDockerRegistryImageNotInRegistry(pushOpts internalPushImageOptions) resource.TestCheckFunc {
return func(s *terraform.State) error {
providerConfig := testAccProvider.Meta().(*ProviderConfig)
username, password := getDockerRegistryImageRegistryUserNameAndPassword(pushOpts, providerConfig)
digest, _ := getImageDigestWithFallback(pushOpts, username, password, true)
if digest != "" {
return fmt.Errorf("image found")
}
return nil
}
}
func testDockerRegistryImageInRegistry(username, password string, pushOpts internalPushImageOptions, cleanup bool) resource.TestCheckFunc {
return func(s *terraform.State) error {
digest, err := getImageDigestWithFallback(pushOpts, username, password, true)
if err != nil || len(digest) < 1 {
return fmt.Errorf("image '%s' with credentials('%s' - '%s') not found: %w", pushOpts.Name, username, password, err)
}
if cleanup {
err := deleteDockerRegistryImage(pushOpts, digest, username, password, true, false)
if err != nil {
return fmt.Errorf("Unable to remove test image '%s': %w", pushOpts.Name, err)
}
}
return nil
}
}