Test-Deep - Re: Defining optional hash keys

Posted on Tue Mar 4 00:10:55 2008 by fergal in response to 7254 (See the whole thread of 4)
Re: Defining optional hash keys

At the moment there is no builtin way to do this but you can make a way to do it and you can even make it convenient (if slightly inefficient).

sub opthash { my ($must_have, $can_have) = @_; # combine the mandatory and optional fields to make a new hash with all of them together my %upper_limit = %$must_have, %$can_have; return all(superhash($must_have), subhash($upper_limit)) } $data_expect = opthash( { name => 'tester', data => ignore(), records => 0 }, { husband => 'joey', } }

The superhash will ensure that all of the mandatory fields exist. The subhash allows the optional fields to be missing but if they are present they must match the spec.

It's a bit inefficient because you end up checking all the mandatory fields twice but that's not such a big deal (particularly as Test::Deep caches comparison results during a run of is_deeply).

If you want you can also use code() which allows you to have data passed to a function for comaparison but that looses diagnostic info.

I think it's really time for me to write a doc on how to extend Test::Deep with home-made comparators. The API has been stable for years now.

Hope that helps. If I had time, I think I would alter Test::Deep::Hash to allow optional keys, then provide a function in Test::Deep to give an interface to this. If you feel like digging in, I'm happy to review and apply patches.

Direct Responses: 7275 | Write a response