utils.suppress_warning, TestCase.assertWarns

54 views
Skip to first unread message

Shai Berger

unread,
Apr 3, 2016, 6:21:59 AM4/3/16
to django-d...@googlegroups.com
Hi all,

While working on a ticket that had to do with cookies, I found myself writing
this code (essentially):

with warnings.catch_warnings(record=True) as warnings_log:
#
# Begin actual code I'm trying to test
#
CsrfViewMiddleware().process_view(req, token_view, (), {})
#
# End actual code I'm trying to test
#
if (len(warnings_log) > 1 or
not issubclass(warnings_log[0].category, UnicodeWarning)):
for warning in warnings_log:
warnings.warn(warning)

The code I'm trying to test is going to make a UnicodeWarning, because the
whole point of the test is to see how the code deals with broken user input.
Having to wrap it in 5 lines of unrelated code feels odd.

So I thought a context manager to suppress specific warnings in a block might
be generally useful, and for tests, it may be even useful to have an
assertWarns -- an analog of assertRaises.

Opinions?

Thanks,
Shai.

Tim Graham

unread,
Apr 4, 2016, 11:37:39 AM4/4/16
to Django developers (Contributions to Django itself)
I think django.test.ignore_warnings may meet your needs.

As for the latter idea, unless something is really eager to add a Python 2 compatible version (if possible) to Django's SimpleTestCase, we can wait until dropping Python 2 support and then use the TestCase.assertWarns() in Python 3.2+.

Shai Berger

unread,
Apr 4, 2016, 6:45:44 PM4/4/16
to django-d...@googlegroups.com
On Monday 04 April 2016 18:37:39 Tim Graham wrote:
> I think django.test.ignore_warnings may meet your needs.
>

Yes, probably. I had misunderstood the warnings.catch_warnings() documentation
(and might have misunderstood the django.test.ignore_warnings documentation as
well, if there was such doumentation).

> As for the latter idea, unless something is really eager to add a Python 2
> compatible version (if possible) to Django's SimpleTestCase, we can wait
> until dropping Python 2 support and then use the TestCase.assertWarns() in
> Python 3.2+.
>

Agreed.

Thanks,
Shai.
Reply all
Reply to author
Forward
0 new messages