mirror of
https://github.com/stretchr/testify.git
synced 2025-05-31 11:42:44 +00:00
add ptr comparison func 'Same' to assert pkg
This commit is contained in:
parent
10a9f47426
commit
21cb1c2932
@ -350,6 +350,37 @@ func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{})
|
||||
|
||||
}
|
||||
|
||||
// Same asserts that two pointers reference the same object.
|
||||
//
|
||||
// assert.Same(t, ptr1, ptr2)
|
||||
//
|
||||
// Both arguments must be pointer variables. Pointer variable sameness is
|
||||
// determined based on the equality of both type and value.
|
||||
func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
|
||||
expectedPtr, actualPtr := reflect.ValueOf(expected), reflect.ValueOf(actual)
|
||||
if expectedPtr.Kind() != reflect.Ptr || actualPtr.Kind() != reflect.Ptr {
|
||||
return Fail(t, "Invalid operation: both arguments must be pointers", msgAndArgs...)
|
||||
}
|
||||
|
||||
expectedType, actualType := reflect.TypeOf(expected), reflect.TypeOf(actual)
|
||||
if expectedType != actualType {
|
||||
return Fail(t, fmt.Sprintf("Pointer expected to be of type %v, but was %v",
|
||||
expectedType, actualType), msgAndArgs...)
|
||||
}
|
||||
|
||||
if expected != actual {
|
||||
return Fail(t, fmt.Sprintf("Not same: \n"+
|
||||
"expected: %p %#v\n"+
|
||||
"actual : %p %#v", expected, expected, actual, actual), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// formatUnequalValues takes two values of arbitrary types and returns string
|
||||
// representations appropriate to be presented to the user.
|
||||
//
|
||||
|
@ -217,6 +217,29 @@ func TestEqual(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSame(t *testing.T) {
|
||||
|
||||
mockT := new(testing.T)
|
||||
|
||||
ptr := func(i int) *int {
|
||||
return &i
|
||||
}
|
||||
|
||||
if Same(mockT, ptr(1), ptr(1)) {
|
||||
t.Error("Same should return false")
|
||||
}
|
||||
if Same(mockT, 1, 1) {
|
||||
t.Error("Same should return false")
|
||||
}
|
||||
p := ptr(2)
|
||||
if Same(mockT, p, *p) {
|
||||
t.Error("Same should return false")
|
||||
}
|
||||
if !Same(mockT, p, p) {
|
||||
t.Error("Same should return true")
|
||||
}
|
||||
}
|
||||
|
||||
// bufferT implements TestingT. Its implementation of Errorf writes the output that would be produced by
|
||||
// testing.T.Errorf to an internal bytes.Buffer.
|
||||
type bufferT struct {
|
||||
|
Loading…
x
Reference in New Issue
Block a user