How to call a custom Django command directly from a test driver


I want to write a unit test for a Django command that does a backend operation on a database table. How would I invoke the management command directly from code?

I don't want to execute the command on the Operating System's shell from because I can't use the test environment set up using test (test database, test dummy email outbox, etc…)

Best Solution

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 import call_command

call_command('my_command', 'foo', bar='baz')
Related Question