[Haskell-cafe] order of assertEqual arguments is counterintuitive

Viktor Dukhovni ietf-dane at dukhovni.org
Tue Mar 1 19:35:18 UTC 2022


On Tue, Mar 01, 2022 at 12:56:02PM -0500, Daneel Yaitskov wrote:

> I noticed, that I pay more attention than I should, when working with
> assertions, because I am not sure about argument order i.e. whether the
> expected value goes first or vice-versa. Does anybody have similar thought?

The documentation is quite clear:

    https://hackage.haskell.org/package/HUnit-1.6.2.0/docs/Test-HUnit-Base.html#v:assertEqual

> Such subtle detail should be easy to grasp with regular practice, but I
> observe difficulties and I suspect that there is a logical reason for that.
> 
> I spell "assertEqual" expression as:  "Assert that x equals to y"
> "y" sounds like a model value (i.e. expected value).

As a combinator that can be curried, 

    -- Check variable given against fixed wanted
    assertEqual prefix wanted :: (Eq a, Show a) => a -> Assertion

is I think more useful than:

    -- Check variable wanted against fixed given.
    assertEqual prefix given :: (Eq a, Show a) => a -> Assertion

> Similar issue with test fixing - I always have to check first, that an
> expected value is actually one. There is no type safety preventing mixing
> arguments.

The test works either way of course, the only thing that changes is the
error message on failure.  You could implement a type-safe wrapper:

    newtype Given a  = Given a
    newtype Wanted a = Wanted a

    checkEq :: (Eq a, Show a) => String -> Given a -> Wanted a -> Assertion
    checkEq prefix (Given x) (Wanted y) = assertEqual prefix y x

Then always call via:

    checkEq "Oops" (Given (2 + 2)) (Wanted 5)

-- 
    Viktor.


More information about the Haskell-Cafe mailing list