python / intermediate
Snippet
Testing Custom Django Management Commands with call_command and StringIO
Testing custom Django management commands requires capturing stdout stream output. Passing an io.StringIO buffer into call_command() captures printed output for asserting expected execution feedback.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
from io import StringIOfrom django.core.management import call_commandfrom django.test import TestCaseclass CommandExecutionTest(TestCase):def test_cleanup_command_output(self):out = StringIO()call_command('cleanup_stale_tokens', '--days=7', stdout=out)output_text = out.getvalue()self.assertIn('Successfully removed stale tokens', output_text)
django
Breakdown
1
out = StringIO()
Instantiates in-memory string buffer to capture command console output.
2
call_command('cleanup_stale_tokens', '--days=7', stdout=out)
Executes management command programmatically while redirecting stdout stream.
3
output_text = out.getvalue()
Extracts written text string contents from the buffer.
4
self.assertIn('Successfully removed stale tokens', output_text)
Asserts presence of expected log verification string in output.