Reputation: 11028
I am using a custom management command to run code that is +500 lines and contains multiple function definitions(and executes database queries).
management/commands/talk.py
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self):
def hello():
print "Hello!"
def my_god():
print "OMG!"
def main():
hello()
my_god()
I can't access the functions inside the handle method seperately (e.g. by doing Command().handle.hello()
) in order to unit test them or am I missing a way to do it?
My solution to this is to put all the code under the handle
method in management/handle_command.py
and then just import that code and run main
under handle
in management/commands/talk.py
. Then I can just unit test the functions from management/handle_command.py
.
Example of a proposed management/commands/talk.py
import my_project.my_app.management.handle_command
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self):
my_project.my_app.management.handle_command.main()
How should I best deal with testing functions inside the handle
method of a custom django-admin command module?
Upvotes: 1
Views: 1450
Reputation: 20353
First part:
You will need to define the functions on the class itself using the self
class Command(BaseCommand):
def hello(self):
print "Hello!"
def my_god(self):
print "OMG!"
def handle(self):
# this was def main():
self.hello()
self.my_god()
Second part:
It's obviously preferable not to have these methods stapled to your Command
class if you want to use them elsewhere / add them to unittest
. If you're only ever using them in the Command
class (other than testing) then your suggested method for testing seems most sensible.
Upvotes: 2