Skip to content
This repository has been archived by the owner on Aug 12, 2022. It is now read-only.

Commit

Permalink
feat: Implement Diagnostics.BySeverity filtering (#288)
Browse files Browse the repository at this point in the history
Co-authored-by: Kemal Hadimli <[email protected]>
  • Loading branch information
disq and disq authored May 25, 2022
1 parent 186c620 commit 75213de
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
18 changes: 18 additions & 0 deletions provider/diag/diagnostics.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,24 @@ func (diags Diagnostics) CountBySeverity(sev Severity, includeSquashed bool) uin
return count
}

// BySeverity returns a subset of diagnostics matching the given severity.
func (diags Diagnostics) BySeverity(sevs ...Severity) Diagnostics {
sevMap := make(map[Severity]struct{}, len(sevs))
for i := range sevs {
sevMap[sevs[i]] = struct{}{}
}

ret := make(Diagnostics, 0, len(diags))
for _, d := range diags {
if _, ok := sevMap[d.Severity()]; !ok {
continue
}
ret = append(ret, d)
}

return ret
}

func (diags Diagnostics) Redacted() Diagnostics {
res := make(Diagnostics, len(diags))
for i := range diags {
Expand Down
46 changes: 46 additions & 0 deletions provider/diag/diagnostics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package diag
import (
"errors"
"sort"
"strconv"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -238,3 +239,48 @@ func TestDiagnostics_Sort(t *testing.T) {
}
}
}

func TestDiagnostics_BySeverity(t *testing.T) {
diagSet := Diagnostics{
NewBaseError(errors.New("warn test 1"), RESOLVING, WithSeverity(WARNING)),
NewBaseError(errors.New("err test 1"), RESOLVING),
NewBaseError(errors.New("ign test 1"), RESOLVING, WithSeverity(IGNORE)),
NewBaseError(errors.New("warn test 2"), RESOLVING, WithSeverity(WARNING)),
NewBaseError(errors.New("ign test 2"), RESOLVING, WithSeverity(IGNORE)),
NewBaseError(errors.New("err test 2"), RESOLVING),
}

cases := []struct {
sevs []Severity
expectedErrs []string
}{
{
sevs: []Severity{WARNING},
expectedErrs: []string{"warn test 1", "warn test 2"},
},
{
sevs: []Severity{ERROR, WARNING},
expectedErrs: []string{"warn test 1", "err test 1", "warn test 2", "err test 2"},
},
{
sevs: []Severity{IGNORE, PANIC},
expectedErrs: []string{"ign test 1", "ign test 2"},
},
{
sevs: []Severity{PANIC},
expectedErrs: []string{},
},
}
for caseNo := range cases {
t.Run("Test #"+strconv.Itoa(caseNo+1), func(t *testing.T) {
tc := cases[caseNo]
res := diagSet.BySeverity(tc.sevs...)
assert.Equal(t, len(tc.expectedErrs), len(res))
resErrs := make([]string, len(res))
for i := range res {
resErrs[i] = res[i].Error()
}
assert.Equal(t, tc.expectedErrs, resErrs)
})
}
}

0 comments on commit 75213de

Please sign in to comment.