assert icon indicating copy to clipboard operation
assert copied to clipboard

assert.Equal panics on unexported fields

Open sparks opened this issue 12 years ago • 1 comments

Given two unequal structs from another package with unexported fields assert.Equal will panic.

Example with time package

package asserttest

import (
    "github.com/bmizerany/assert"
    "testing"
    "time"
)

func TestBreakAssert(t *testing.T) {
    assert.Equal(t, time.Now(), time.Unix(0, 0))
}

Example with an invented struct

asserttest/assert_test.go

package asserttest

import (
    "other"
    "github.com/bmizerany/assert"
    "testing"
)

func TestBreakAssert2(t *testing.T) {
    a := new(other.Other)
    a.Outer = 2
    b := new(other.Other)
    b.Outer = 4
    assert.Equal(t, a, b)
}

other/other.go

package other

type Other struct {
    Outer int
    inner int
}

Both these snippets panic like so

panic: reflect.Value.Interface: cannot return value obtained from unexported field or method [recovered]
panic: reflect.Value.Interface: cannot return value obtained from unexported field or method
etc ...

sparks avatar Mar 11 '13 21:03 sparks

I avoided this by using the Equal method on a time instead:

assert.T(t, time.Now().Equal(time.Unix(0, 0)))

justincampbell avatar Jul 31 '14 15:07 justincampbell