Is it possible to pass command line arguments to Django\'s manage.py
script, specifically for unit tests? i.e. if I do something like
manage.py test
Django allows adding custom commandline options from the testrunner class. You can create a subclass of the default testrunner class and add your own options, and then let django use your custom testrunner as follows.
For example, create a testrunner.py in your Django project directory, containing:
from django.test.runner import DiscoverRunner
class TestRunner(DiscoverRunner):
def __init__(self, option=None, **kwargs):
super().__init__(**kwargs)
print("Passed option: {}".format(option))
@classmethod
def add_arguments(cls, parser):
DiscoverRunner.add_arguments(parser)
parser.add_argument('-o', '--option', help='Example option')
This is a testrunner that derives from the default runner (so it works just like the default), except that it tells django to add an extra commandline option (in the add_arguments()
class method) and processes the value of this extra option in the constructor. To run with this new runner, pass its name as follows:
./manage.py test --testrunner=testrunner.TestRunner -o foo
Of course you can put this class anywhere else, as long as you pass the full import name to it on the commandline.
Note that you must use --testrunner=foo
, you cannot use two separate arguments (--testrunner foo
), since then the extra arguments do not work. A fix is pending: https://github.com/django/django/pull/10307
This example just prints the option value, but you'll want to pass it to your testcase somehow. I couldn't find any quick info on how to pass options to unittest testcases, but you could probably just use a global (module level) variable or class variable for this (which is not so re-entrant and elegant, but is easy and works).