[TIP] unittest2 assertRaises failure message

Michael Rene Armida me at marmida.com
Tue Jan 15 09:55:12 PST 2013


I'd suggest inspecting the context manager object, which exposes the caught
exception as an attribute.  You can see it here in the unittest2 docs:
http://www.voidspace.org.uk/python/articles/unittest2.shtml#assertraises

In your case, you'd want something like:

with self.assertRaises(MyException) as cm:
    # Assertions et al.
self.assertEqual(cm.exception.somevalue, 42)


As for dumping the globals and locals during a failure, I don't know how to
hook that into the unittest2 machinery.  However, nosetests does allow you
to invoke pdb on failures with a command-line switch, whic allows you to
interactively poke around at the locals, globals, and whatever else you
might want.  pdb has a learning curve, but I think the payoff makes it
worthwhile.

On Sun, Jan 13, 2013 at 7: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/20130115/2aa1aead/attachment.html>


More information about the testing-in-python mailing list