call_command() invokes a Django management command from Python code instead of launching it from a shell. Its most useful job is testing: run the command, capture its output, and check the result. section 9.4
A typical test follows this flow:
- Create the database objects the command expects. section 9.4
- Create a fresh io.StringIO buffer for the command's output. section 9.4
- Call call_command("musicians", stdout=output). section 9.4
- Assert against output.getvalue(), then use a new buffer for each additional invocation. section 9.4
Testing the musicians command
import io from django.core.management import call_command output = io.StringIO() call_command("musicians", stdout=output) assert "First" in output.getvalue() Arguments can be passed in command-line form, such as --last_name B, or as keyword arguments such as last_name="B". Pass stderr similarly when the test needs to capture error output. section 9.4 section 9.6
Listing 9.4 Test code for the musicians management command
# bands/tests.py
import io
from django.core.management import call_command
...
class TestMusiciansCommand(TestCase):
def setUp(self):
self.musician = Musician.objects.create( #1
first_name="First",
last_name="Last",
birth=date(1900, 1, 1)
)
def test_command(self):
output = io.StringIO() #2
call_command("musicians", stdout=output) #3
self.assertIn("First", output.getvalue()) #4
Use the complete test listing to see setup, StringIO capture, call_command(), and output assertion working together. section 9.4
