Skip to content

Commit

Permalink
Updating defer func to log error and fail test if closing file contai…
Browse files Browse the repository at this point in the history
…ning output from stdout returns an error (#16)
  • Loading branch information
bendbennett committed Jan 12, 2023
1 parent 5c1b67e commit 71f0877
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions helper/resource/testing_new.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,15 +125,21 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest
// acts as default for import tests
var appliedCfg string

var file *os.File
defer func() error {
if file != nil {
err := file.Close()
// stdoutFile is used as the handle to the file that contains
// json output from running Terraform commands.
var stdoutFile *os.File
defer func() {
if stdoutFile != nil {
err := stdoutFile.Close()
if err != nil {
return err
logging.HelperResourceError(ctx,
"Error closing file containing json output from Terraform commands",
map[string]interface{}{logging.KeyError: err},
)
t.Fatalf("Error closing file containing json from Terraform commands: %s", err.Error())
return
}
}
return nil
}()

for stepIndex, step := range c.Steps {
Expand Down Expand Up @@ -338,15 +344,15 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest
if step.ExpectWarning != nil {
logging.HelperResourceDebug(ctx, "Checking TestStep ExpectWarning")

file, err = os.Open(filepath.Join(wd.GetBaseDir(), "stdout.txt"))
stdoutFile, err = os.Open(filepath.Join(wd.GetBaseDir(), "stdout.txt"))
if err != nil {
log.Fatal(err)
}

warningFound := false

// TODO: Use MultiLineJSONDecode providing entire contents of stdout.txt is valid JSON.
scanner := bufio.NewScanner(file)
scanner := bufio.NewScanner(stdoutFile)
// optionally, resize scanner's capacity for lines over 64K, see next example
for scanner.Scan() {
var outer struct {
Expand All @@ -356,6 +362,7 @@ func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest
if json.Unmarshal([]byte(scanner.Text()), &outer) == nil {
if step.ExpectWarning.MatchString(outer.Diagnostic.Summary) && outer.Diagnostic.Severity == tfjson.DiagnosticSeverityWarning {
warningFound = true
break
}
}
}
Expand Down

0 comments on commit 71f0877

Please sign in to comment.