How to test custom django-admin commands How to test custom django-admin commands django django

How to test custom django-admin commands


If you're using some coverage tool it would be good to call it from the code with:

from django.core.management import call_commandfrom django.test import TestCaseclass CommandsTestCase(TestCase):    def test_mycommand(self):        " Test my custom command."        args = []        opts = {}        call_command('mycommand', *args, **opts)        # Some Asserts.

From the official documentation

Management commands can be tested with the call_command() function. The output can be redirected into a StringIO instance


You should make your actual command script the minimum possible, so that it just calls a function elsewhere. The function can then be tested via unit tests or doctests as normal.


you can see in github.com examplesee here

def test_command_style(self):    out = StringIO()    management.call_command('dance', style='Jive', stdout=out)    self.assertEquals(out.getvalue(),        "I don't feel like dancing Jive.")