26

We have a bunch of commands in our Django site, some that are administrative and some that run on cron jobs that I can't figure out how to test. They pretty much look like this:

# Saved in file /app/management/commands/some_command.py
# Usage: python manage.py some_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
    def handle_noargs(self, **options):
         # Do something useful

And I have some tests, which look like this:

import unittest
from django.test import TestCase
from django_webtest import WebTest

class SomeTest(WebTest):
    fixtures = ['testdata.json']

    def setUp(self):
        self.open_in_browser = False
        # Set up some objects

    def test_registration(self):
        response = self.client.get('/register/')
        self.assertEqual(response.status_code, 200)
        form = self.app.get('/register/').forms[1]
        # Set up the form
        response = form.submit()
        self.assertContains(response, 'You are Registered.')
        if self.open_in_browser:
            response.showbrowser()

        # Here I'd like to run some_command to see the how it affects my new user.

In my test (where I have the comment) I'd like to run my NoArgsCommand to see what happens to my new user. I can't find any documentation or examples on how to accomplish this. Also note that my test environment is a SQLlite DB that I create from scratch in memory, load some fixtures and objects into and run my tests, so as much as I'd like to setup the data in a real DB, then just run my command from the command line, I can't, it's far too time consuming. Any ideas would be greatly appreciated.

scoopseven
  • 1,767
  • 3
  • 18
  • 27

1 Answers1

63

Django documentation on management commands might help, it describes how to call them from python code.

Basically you need something like this:

from django.core import management
management.call_command( ... )
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
kgr
  • 9,750
  • 2
  • 38
  • 43
  • Thanks! I have been trying to run my unit testing from Visual Studio and could not get it until I followed your reference link. – TurboGus Jan 18 '13 at 06:16
  • 1
    Updated link to Django development docs on `call_command`: https://docs.djangoproject.com/en/dev/ref/django-admin/#call-command – jamesc Aug 12 '14 at 10:35