Skip to content

Commit

Permalink
Add initial implementation of copying files from ConfigDirectory into…
Browse files Browse the repository at this point in the history
… wd.baseDir (#150)
  • Loading branch information
bendbennett committed Jul 18, 2023
1 parent 4230bb1 commit d46d517
Show file tree
Hide file tree
Showing 5 changed files with 138 additions and 21 deletions.
4 changes: 4 additions & 0 deletions helper/fixtures/random.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Copyright (c) HashiCorp, Inc.
# SPDX-License-Identifier: MPL-2.0

resource "random_id" "test" {}
34 changes: 34 additions & 0 deletions helper/resource/teststep_providers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,40 @@ func TestTest_TestStep_Taint(t *testing.T) {
}
}

func TestTest_TestStep_ConfigDirectory(t *testing.T) {
t.Parallel()

Test(t, TestCase{
ProviderFactories: map[string]func() (*schema.Provider, error){
"random": func() (*schema.Provider, error) { //nolint:unparam // required signature
return &schema.Provider{
ResourcesMap: map[string]*schema.Resource{
"random_id": {
CreateContext: func(_ context.Context, d *schema.ResourceData, _ interface{}) diag.Diagnostics {
d.SetId(time.Now().String())
return nil
},
DeleteContext: func(_ context.Context, _ *schema.ResourceData, _ interface{}) diag.Diagnostics {
return nil
},
ReadContext: func(_ context.Context, _ *schema.ResourceData, _ interface{}) diag.Diagnostics {
return nil
},
Schema: map[string]*schema.Schema{},
},
},
}, nil
},
},
Steps: []TestStep{
{
ConfigDirectory: `../fixtures`,
Check: TestCheckResourceAttrSet("random_id.test", "id"),
},
},
})
}

//nolint:unparam
func extractResourceAttr(resourceName string, attributeName string, attributeValue *string) TestCheckFunc {
return func(s *terraform.State) error {
Expand Down
68 changes: 67 additions & 1 deletion internal/plugintest/working_dir.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"

Expand Down Expand Up @@ -88,7 +89,7 @@ func (wd *WorkingDir) SetConfig(ctx context.Context, cfg teststep.Config) error

outFilename := filepath.Join(wd.baseDir, ConfigFileName)
rmFilename := filepath.Join(wd.baseDir, ConfigFileNameJSON)
bCfg := []byte(cfg.GetRaw(ctx))
bCfg := []byte(cfg.Raw(ctx))
if json.Valid(bCfg) {
outFilename, rmFilename = rmFilename, outFilename
}
Expand All @@ -101,6 +102,21 @@ func (wd *WorkingDir) SetConfig(ctx context.Context, cfg teststep.Config) error
}
wd.configFilename = outFilename

if cfg.HasDirectory() {
pwd, err := os.Getwd()

if err != nil {
return err
}

configDirectory := filepath.Join(pwd, cfg.Directory(ctx))

err = copyFiles(configDirectory, wd.baseDir)
if err != nil {
return err
}
}

// Changing configuration invalidates any saved plan.
err = wd.ClearPlan(ctx)
if err != nil {
Expand All @@ -109,6 +125,56 @@ func (wd *WorkingDir) SetConfig(ctx context.Context, cfg teststep.Config) error
return nil
}

func copyFiles(path string, dstPath string) error {
infos, err := os.ReadDir(path)
if err != nil {
return err
}

for _, info := range infos {
srcPath := filepath.Join(path, info.Name())
if info.IsDir() {
continue
} else {
err = copyFile(srcPath, dstPath)
if err != nil {
return err
}
}

}
return nil
}

func copyFile(path string, dstPath string) error {
srcF, err := os.Open(path)
if err != nil {
return err
}
defer srcF.Close()

di, err := os.Stat(dstPath)
if err != nil {
return err
}
if di.IsDir() {
_, file := filepath.Split(path)
dstPath = filepath.Join(dstPath, file)
}

dstF, err := os.Create(dstPath)
if err != nil {
return err
}
defer dstF.Close()

if _, err := io.Copy(dstF, srcF); err != nil {
return err
}

return nil
}

// ClearState deletes any Terraform state present in the working directory.
//
// Any remote objects tracked by the state are not destroyed first, so this
Expand Down
51 changes: 32 additions & 19 deletions internal/teststep/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ import (
var configProviderBlockRegex = regexp.MustCompile(`provider "?[a-zA-Z0-9_-]+"? {`)

type Config interface {
GetRaw(context.Context) string
Directory(context.Context) string
HasConfiguration() bool
HasDirectory() bool
HasProviderBlock(context.Context) bool
Raw(context.Context) string
}

type configuration struct {
Expand Down Expand Up @@ -65,24 +67,11 @@ func Configuration(req ConfigurationRequest) (configuration, error) {
return config, nil
}

func (c configuration) GetRaw(ctx context.Context) string {
var config strings.Builder

// Prevent issues with existing configurations containing the terraform
// configuration block.
if c.hasTerraformBlock(ctx) {
return c.raw
}

if c.testCaseProviderConfig != "" {
config.WriteString(c.testCaseProviderConfig)
} else {
config.WriteString(c.testStepProviderConfig)
}

config.WriteString(c.raw)

return config.String()
// Directory returns config directory.
// TODO: Need to handle testCaseProviderConfig and testStepProviderConfig when
// copying files from c.directory to working directory for test
func (c configuration) Directory(ctx context.Context) string {
return c.directory
}

func (c configuration) HasConfiguration() bool {
Expand All @@ -97,6 +86,10 @@ func (c configuration) HasConfiguration() bool {
return false
}

func (c configuration) HasDirectory() bool {
return c.directory != ""
}

// HasProviderBlock returns true if the Config has declared a provider
// configuration block, e.g. provider "examplecloud" {...}
//
Expand All @@ -105,6 +98,26 @@ func (c configuration) HasProviderBlock(_ context.Context) bool {
return configProviderBlockRegex.MatchString(c.raw)
}

func (c configuration) Raw(ctx context.Context) string {
var config strings.Builder

// Prevent issues with existing configurations containing the terraform
// configuration block.
if c.hasTerraformBlock(ctx) {
return c.raw
}

if c.testCaseProviderConfig != "" {
config.WriteString(c.testCaseProviderConfig)
} else {
config.WriteString(c.testStepProviderConfig)
}

config.WriteString(c.raw)

return config.String()
}

// HasTerraformBlock returns true if the Config has declared a terraform
// configuration block, e.g. terraform {...}
//
Expand Down
2 changes: 1 addition & 1 deletion internal/teststep/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,7 @@ resource "test_test" "test" {}
t.Errorf("error creating configuration: %s", err)
}

got := cfg.GetRaw(context.Background())
got := cfg.Raw(context.Background())

if diff := cmp.Diff(strings.TrimSpace(got), strings.TrimSpace(testCase.expected)); diff != "" {
t.Errorf("unexpected difference: %s", diff)
Expand Down

0 comments on commit d46d517

Please sign in to comment.