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
Following up on @Matthijs answer, you can extend the setup_test_environment
method similar to how the DiscoveryRunner
handles the debug-mode.
It changes the value of settings.DEBUG
which can be used in your tests by importing django.conf.settings
. But you can also add your own settings:
from django.test.runner import DiscoverRunner
class TestRunner(DiscoverRunner):
def __init__(self, option=None, **kwargs):
super().__init__(**kwargs)
print("Passed option: {}".format(option))
self.option = option
@classmethod
def add_arguments(cls, parser):
DiscoverRunner.add_arguments(parser)
parser.add_argument('-o', '--option', help='Example option')
def setup_test_environment(self, **kwargs):
super(TestRunner, self).setup_test_environment(**kwargs)
settings.TEST_SETTINGS = {
'option': self.option,
}
In the test you can then simply access the option via the settings
from django.test import TestCase
from django.conf import settings
class MyTestCase(TestCase):
def test_something(self):
if settings.TEST_SETTINGS['option']:
print("Do stuff")