Capturing output of management commands during tests doesn't work

252 views
Skip to first unread message

Patrice

unread,
Jan 20, 2016, 5:52:20 AM1/20/16
to Django users
Hello,

but all I got is an empty string in my out.getvalue().

From what I understand from  Django code here, it does not capture the output (ie: sys.stdout.write("blah blah")) but the return value of my command. It doesn't make sense to me, there's no point returning a value in a management command.

Am I missing something? Is the documentation wrong or is it a bug ?

Michal Petrucha

unread,
Jan 20, 2016, 6:20:24 AM1/20/16
to django...@googlegroups.com
On Wed, Jan 20, 2016 at 02:52:20AM -0800, Patrice wrote:
> Hello,
>
> I followed what is describe in the docs here
> : https://docs.djangoproject.com/en/1.9/topics/testing/tools/#management-commands
> but all I got is an empty string in my *out.getvalue()*.
>
> From what I understand from Django code here
> <https://github.com/django/django/blob/master/django/core/management/base.py#L339>,
> it does not capture the output (ie: sys.stdout.write("blah blah")) but the *return
> value *of my command. It doesn't make sense to me, there's no point
> returning a value in a management command.
>
> Am I missing something? Is the documentation wrong or is it a bug ?

Hi Patrice,

Returning a value from a management command's ``handle`` method is
documented [1], though it might only be useful in very specific
situations (namely, when your management command produces SQL code).

The problem you're facing is that your management command writes
directly to ``sys.stdout`` instead of ``self.stdout`` as indicated in
the docs [2]. If you change your management command to use
``self.stdout``, it should work as you expect.

Good luck,

Michal


[1]: https://docs.djangoproject.com/en/1.9/howto/custom-management-commands/#django.core.management.BaseCommand.handle
[2]: https://docs.djangoproject.com/en/1.9/howto/custom-management-commands/#management-commands-output
signature.asc

Patrice

unread,
Jan 20, 2016, 7:49:02 AM1/20/16
to Django users
Hi Michal,

It looks like I missed those parts of the doc :)
Thanks for pointing them out, working now!
Reply all
Reply to author
Forward
0 new messages