Run Python/Django Management Command from a UnitTest/WebTest

て烟熏妆下的殇ゞ 提交于 2019-12-03 11:06:43

问题


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:


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( ... )


来源:https://stackoverflow.com/questions/9539441/run-python-django-management-command-from-a-unittest-webtest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!