Skip to content

Commit

Permalink
add methods to extract error from diags (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidji99 committed Oct 14, 2021
1 parent 4b49b78 commit df4d1fa
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
17 changes: 17 additions & 0 deletions tfph.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package tfph

import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"strings"
)

Expand Down Expand Up @@ -29,3 +30,19 @@ func ContainsString(s []string, str string) bool {
}
return false
}

func DoesNotContainString(s []string, str string) bool {
return !ContainsString(s, str)
}

func ErrsFromDiags(diags diag.Diagnostics) error {
if !diags.HasError() {
return nil
}

var err string
for _, d := range diags {
err += fmt.Sprintf("Severity: %d | Summary: %s, | Detail: %s\n", d.Severity, d.Summary, d.Detail)
}
return fmt.Errorf(err)
}
36 changes: 36 additions & 0 deletions tfph_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package tfph

import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/stretchr/testify/assert"
"testing"
)
Expand Down Expand Up @@ -45,3 +47,37 @@ func TestContainsString_Invalid(t *testing.T) {
tester := []string{"abc", "efd", "xyz"}
assert.Equal(t, false, ContainsString(tester, "a2bc"))
}

func TestDoesNotContainString(t *testing.T) {
tester := []string{"abc", "efd", "xyz"}
assert.Equal(t, true, DoesNotContainString(tester, "ab1c"))
}

func TestDoesNotContainString_Invalid(t *testing.T) {
tester := []string{"abc", "efd", "xyz"}
assert.Equal(t, false, DoesNotContainString(tester, "abc"))
}

func TestErrsFromDiags(t *testing.T) {
expected := fmt.Errorf("Severity: 0 | Summary: The summer of error one, | Detail: The Details of error one\nSeverity: 0 | Summary: The summer of error two, | Detail: The Details of error two\n")
diags := diag.Diagnostics{
{
Severity: diag.Error,
Summary: "The summer of error one",
Detail: "The Details of error one",
},
{
Severity: diag.Error,
Summary: "The summer of error two",
Detail: "The Details of error two",
},
}

assert.Equal(t, expected, ErrsFromDiags(diags))
}

func TestErrsFromDiags_NoErrors(t *testing.T) {
diags := diag.Diagnostics{}

assert.Equal(t, nil, ErrsFromDiags(diags))
}

0 comments on commit df4d1fa

Please sign in to comment.