[TIP] unittest2 assertRaises failure message

Julian Berman julian at grayvines.com
Sun Jan 13 19:49:32 PST 2013


Loops in test methods are somewhat precarious things. If something
unexpected happens (like your sequence being unexpectedly empty, say),
you've now got quite the false sense of security. Guard assertions can
help, but often there's a more clear way to eliminate the loop.

That being said, assertRaises in Py3 takes a msg keyword arg which could be
used to show the usual message (your x here). I presume you're not using it
(by virtue of the fact that you're using unittest2), and it appears that
msg hasn't been backported to unittest2. Py2 doesn't have keyword-only args
strictly speaking, but it could be done by plucking msg out of kwargs,
albeit that'd break some backwards compat. Not sure why that hasn't been
done, or if it was intentionally left out.

In the absence of that, I'd recommend using the simple thing:

for i in stuff:
    try:
        whatever(i)
    except ThingError:
        pass
    else:
        self.fail("Expected ThingError for %r" % x)

Salt as needed.

Cheers,

Julian


On Sun, Jan 13, 2013 at 10:40 PM, Olemis Lang <olemis at gmail.com> wrote:

> Hi all !
> :)
>
> The body of a `unittest2` test case looks like this ...
>
> {{{
> #!python
>
> # ------8<--- Further code omitted ---8<------
>     for x in seq:
>         # ------8<--- Further code omitted ---8<------
>         with self.assertRaises(MyException) as cm:
>             # Assertions et al.
>
> }}}
>
> As you can see there's a chance for assertRaises to fail and as a
> consequence a message like «AssertionError: MyException not raised» is
> included in ouput . That's not informative enough *in this case* since
> I'd like to know e.g. the exact value of x .
>
> Q:
>   - Is there a chance to customize `assertRaises` failure message ?
>   - Is there any chance for e.g. dumping `locals()` ?
>   - Can `unittest2` be helpful somehow ?
>   - Any other suggestions ?
>
> Any feedback will be welcome . Thanks in advance .
>
>
> --
> Regards,
>
> Olemis.
>
> Blog ES: http://simelo-es.blogspot.com/
> Blog EN: http://simelo-en.blogspot.com/
>
> Featured article:
>
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20130113/82895ad0/attachment.html>


More information about the testing-in-python mailing list