views:

287

answers:

2

I want to write a unit test for a Django manage.py 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 tests.py because I can't use the test environment set up using manage.py test (test database, test dummy email outbox, etc...)

A: 

You could look at your project's manage.py and run something similar yourself.

Marcus Lindblom
+5  A: 

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 like this:

from django.core.management import call_command

call_command('my_command', 'foo', bar='baz')
Alex Koshelev
+1 to putting the testable logic somewhere else (model method? manager method? standalone function?) so you don't need to mess with the call_command machinery at all. Also makes the functionality easier to reuse.
Carl Meyer