haskell - Testing custom data types which do not implement Eq -
lets have following custom data type:
data animal = characteristics [char] (set.set [char]) and function
checkanimaltype :: [char] -> animal -> [animal] now i'm trying write hspec tests so:
describe "checkanimaltype" $ "returns list of animals" $ (checkanimaltype ["foo", "coo", "doo", "bar", "moo"](characteristics "foo" $ set.fromlist(["foo", "coo"]))) $ `shouldbe` [(characteristics "foo" $ set.fromlist(["cockadoodledoo"]))] this fails with:
no instance (eq animal) arising use of ‘shouldbe’ my question is, possible temporarily, within scope of tests, implement eq typeclass on animal? or there better way this?
my question is, possible temporarily, within scope of tests, implement eq typeclass on animal?
within scope of module, sure. if module gets imported, you're going leak instance other modules. that's why creating instances recommended in same module data type has been defined, or class has been defined. otherwise end orphan instances.
or there better way this?
is remotely possible user want compare characteristics? derive eq. it's cleanest way. also, you're going need show instance, you're deriving already:
data animal = characteristics [char] (set.set [char]) deriving (show, eq) if cannot change original source can still use -xstandalonederiving derive instance in module (see orphan instances above, though).
however if want use special eq test can either fiddle around newtype wrappers, or write own combinator:
-- newtype variant newtype tanimal = tanimal animal instance eq tanimal ... instance show tanimal where... animalshouldbe :: animal -> animal -> expectation animalshouldbe = shouldbe `on` tanimal -- custom operator variant withshouldbe :: (show a) => (a -> -> bool) -> -> -> expectation withshouldbe f e = unless (f e) $ expectationfailure msg msg = "expected: " ++ show e ++ ", got " ++ show animalshouldbe = withshouldbe animalequalitytest -- fun fact: shouldbe = withshouldbe (==)
Comments
Post a Comment