smarty / assertions

Fluent assertion-style functions used by goconvey and gunit. Can also be used in any test or application.
Other
100 stars 34 forks source link

should.ContainKey fails for int32 key #30

Closed jornj closed 6 years ago

jornj commented 6 years ago

Greetings, first of all, great library! It enables me to write more or less fluent assertions, as I'm used to from C#.

However, the test below fails with the int32 key, but works with int key. This is for version 1.8.3

func Test_Should_ContainKey_With_Integer_Keys_Works(t *testing.T) {
    // Arrange
    assert := assertions.New(t)
    target := map[int32]int{}
    target[3] = 5
    // Assert
    assert.So(target, should.ContainKey, 3)
}
mdwhatcott commented 6 years ago

You're very welcome! Long may this library assist you in your quest for more or less fluent assertions. (We came from C# as well.)

You raise an interesting question. After thinking about this and studying the code I thought of an interesting variation on the code you provided that adds some perspective. Consider another map type (map[interface{}]int) which has the following key/value pairs:

func Test_Map_Keys_Are_Compared_Strictly(t *testing.T) {
    target := map[interface{}]int{
        int16(3): 5,
        int32(3): 5,
        int64(3): 5,
    }
    assertions.New(t).So(target, should.ContainKey, 3) // FAIL
}

In this case it is more clear that the assertion will (and should) fail. Unlike the ShouldEqual assertion (which uses fairly loose comparison logic, allowing int(3) to appear equal to int32(3)), map keys should only be compared strictly (as if doing an == comparison) because that is how map keys work:

The comparison operators == and != must be fully defined for operands of the key type;