How can I call a custom Django manage.py command directly from a test driver? How can I call a custom Django manage.py command directly from a test driver? django django

How can I call a custom Django manage.py command directly from a test driver?


The best way to test such things - extract needed functionality from command itself to standalone function or class. It helps to abstract from "command execution stuff" and write test without additional requirements.

But if you by some reason cannot decouple logic form command you can call it from any code using call_command method like this:

from django.core.management import call_commandcall_command('my_command', 'foo', bar='baz')


Rather than do the call_command trick, you can run your task by doing:

from myapp.management.commands import my_management_taskcmd = my_management_task.Command()opts = {} # kwargs for your command -- lets you override stuff for testing...cmd.handle_noargs(**opts)


the following code:

from django.core.management import call_commandcall_command('collectstatic', verbosity=3, interactive=False)call_command('migrate', 'myapp', verbosity=3, interactive=False)

...is equal to the following commands typed in terminal:

$ ./manage.py collectstatic --noinput -v 3$ ./manage.py migrate myapp --noinput -v 3

See running management commands from django docs.