Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0e8ef09

Browse files
authored
test(coderd/database/dbauthz): compare outputs with cmp (#16161)
1 parent 5b72a43 commit 0e8ef09

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

coderd/database/dbauthz/setup_test.go

+26-5
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,16 @@ package dbauthz_test
22

33
import (
44
"context"
5+
"encoding/gob"
56
"errors"
67
"fmt"
78
"reflect"
89
"sort"
910
"strings"
1011
"testing"
1112

13+
"github.com/google/go-cmp/cmp"
14+
"github.com/google/go-cmp/cmp/cmpopts"
1215
"github.com/google/uuid"
1316
"github.com/open-policy-agent/opa/topdown"
1417
"github.com/stretchr/testify/require"
@@ -198,11 +201,29 @@ func (s *MethodTestSuite) Subtest(testCaseF func(db database.Store, check *expec
198201
s.Equal(len(testCase.outputs), len(outputs), "method %q returned unexpected number of outputs", methodName)
199202
for i := range outputs {
200203
a, b := testCase.outputs[i].Interface(), outputs[i].Interface()
201-
if reflect.TypeOf(a).Kind() == reflect.Slice || reflect.TypeOf(a).Kind() == reflect.Array {
202-
// Order does not matter
203-
s.ElementsMatch(a, b, "method %q returned unexpected output %d", methodName, i)
204-
} else {
205-
s.Equal(a, b, "method %q returned unexpected output %d", methodName, i)
204+
205+
// To avoid the extra small overhead of gob encoding, we can
206+
// first check if the values are equal with regard to order.
207+
// If not, re-check disregarding order and show a nice diff
208+
// output of the two values.
209+
if !cmp.Equal(a, b, cmpopts.EquateEmpty()) {
210+
if diff := cmp.Diff(a, b,
211+
// Equate nil and empty slices.
212+
cmpopts.EquateEmpty(),
213+
// Allow slice order to be ignored.
214+
cmpopts.SortSlices(func(a, b any) bool {
215+
var ab, bb strings.Builder
216+
_ = gob.NewEncoder(&ab).Encode(a)
217+
_ = gob.NewEncoder(&bb).Encode(b)
218+
// This might seem a bit dubious, but we really
219+
// don't care about order and cmp doesn't provide
220+
// a generic less function for slices:
221+
// https://github.com/google/go-cmp/issues/67
222+
return ab.String() < bb.String()
223+
}),
224+
); diff != "" {
225+
s.Failf("compare outputs failed", "method %q returned unexpected output %d (-want +got):\n%s", methodName, i, diff)
226+
}
206227
}
207228
}
208229
}

0 commit comments

Comments
 (0)