Skip to content

Commit 9af10d6

Browse files
authored
Merge pull request #170 from hpidcock/unhashable-samecontents
Allow SameContents to work with unhashable contents.
2 parents 0e4da91 + 334b536 commit 9af10d6

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

checkers/checker.go

+22-9
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,8 @@ type sameContents struct {
151151

152152
// SameContents checks that the obtained slice contains all the values (and
153153
// same number of values) of the expected slice and vice versa, without respect
154-
// to order or duplicates. Uses DeepEquals on mapped contents to compare.
154+
// to order or duplicates. Uses DeepEquals on contents to compare. Content types
155+
// do not need to be hashable, but must satisfy reflect.DeepEquals.
155156
var SameContents gc.Checker = &sameContents{
156157
&gc.CheckerInfo{Name: "SameContents", Params: []string{"obtained", "expected"}},
157158
}
@@ -190,16 +191,29 @@ func (checker *sameContents) Check(params []interface{}, names []string) (result
190191
return false, ""
191192
}
192193

193-
// spin up maps with the entries as keys and the counts as values
194-
mob := make(map[interface{}]int, length)
195-
mexp := make(map[interface{}]int, length)
194+
// left is the expected
195+
left := make([]any, 0, length)
196+
// right is the obtained
197+
right := make([]any, 0, length)
196198

197199
for i := 0; i < length; i++ {
198-
mexp[reflect.Indirect(vexp.Index(i)).Interface()]++
199-
mob[reflect.Indirect(vob.Index(i)).Interface()]++
200+
left = append(left, reflect.Indirect(vexp.Index(i)).Interface())
201+
right = append(right, reflect.Indirect(vob.Index(i)).Interface())
200202
}
201203

202-
return reflect.DeepEqual(mob, mexp), ""
204+
outer:
205+
for i := 0; i < len(left); i++ {
206+
for j, r := range right {
207+
if reflect.DeepEqual(left[i], r) {
208+
left = append(left[:i], left[i+1:]...)
209+
right = append(right[:j], right[j+1:]...)
210+
i--
211+
continue outer
212+
}
213+
}
214+
}
215+
216+
return len(left) == 0 && len(right) == 0, ""
203217
}
204218

205219
type errorIsNilChecker struct {
@@ -211,8 +225,7 @@ type errorIsNilChecker struct {
211225
//
212226
// For example:
213227
//
214-
// c.Assert(err, ErrorIsNil)
215-
//
228+
// c.Assert(err, ErrorIsNil)
216229
var ErrorIsNil gc.Checker = &errorIsNilChecker{
217230
&gc.CheckerInfo{Name: "ErrorIsNil", Params: []string{"value"}},
218231
}

0 commit comments

Comments
 (0)