[Python-Dev] PEP: Frequently-requested additional features for the `unittest` module

Nick Coghlan ncoghlan at gmail.com
Wed Jul 16 16:29:45 CEST 2008

Ben Finney wrote:
> Do you perhaps mean something like this::
>     def assert_compare_true(op, first, second, msg=None):
>         fail_detail = "%(first)r %(op)r %(second)r" % vars()
>         if msg is None:
>             msg = fail_detail
>         else:
>             msg = "%(fail_detail)s: %(msg)s" % vars()
>         if not op(first, second):
>             raise self.failure_exception(msg)
> If so, that sems to be in line with the "Enhanced failure message"
> principle exercised elsewhere in the same PEP, i.e. that the failure
> message should *always* contain certain information, even if a message
> is specified by the caller.

I was going to suggest the same thing, so this sounds like a good idea 
to me. The other point I was going to make is that repr(operator.lt) is 
actually "<built-in function lt>". It may be better to just make a 
general method for asserting that an operation gives an expected result 
and gives the name of the operation and the details of the arguments and 
expected result if anything goes wrong:

     def assert_op(op, *args, msg=None, expected=True):
         fail_detail = "%r%r != %r" % (op.__name__, arg, expect)
         if msg is None:
             msg = fail_detail
             msg = "%s: %s" % (msg, fail_detail)
         if op(*args) != expected:
             raise self.failure_exception(msg)

> One downside I can see is that, in optimising for this common case, it
> makes the function useless to someone who wants to specify their own
> failure message exactly, without the specific extra information in
> that specific format.

If you don't want the extra details in the error messages then you can 
just use the basic self.assert_ method - the only advantage to use the 
other assertion methods is they provide additional details in the 
assertion error. (except assert_raises, where it provides the try/catch 
block as well)


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list