25

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.

1 Answer 1

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( ... )
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I have been trying to run my unit testing from Visual Studio and could not get it until I followed your reference link.
Updated link to Django development docs on call_command: docs.djangoproject.com/en/dev/ref/django-admin/#call-command

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.