liveBook · Manning

Call_command()

As explained in Django in Action

A Django function that invokes a management command programmatically from Python code.

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

How Django in Action covers it

How deep it goes
Explains invocation, argument passing, stream capture, assertions, and repeated-test buffer isolation.
Examples
Demonstrates testing the musicians command with a Musician object, io.StringIO, captured output, and last_name arguments.
What it assumes
Assumes familiarity with Django management commands and tests while demonstrating command invocation and output capture.
What you can do after
Apply it via Django tests to invoke commands, capture output, and verify command behavior.
How it connects
Connects management commands with unit tests, argparse arguments, and stdout and stderr streams.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.