Detect django testing mode

后端 未结 6 851
逝去的感伤
逝去的感伤 2020-12-14 13:41

I\'m writing a reusable django app and I need to ensure that its models are only sync\'ed when the app is in test mode. I\'ve tried to use a custom DjangoTestRunner, but I f

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 14:24

    The selected answer is a massive hack. :)

    A less-massive hack would be to create your own TestSuiteRunner subclass and change a setting or do whatever else you need to for the rest of your application. You specify the test runner in your settings:

    TEST_RUNNER = 'your.project.MyTestSuiteRunner'
    

    In general, you don't want to do this, but it works if you absolutely need it.

    from django.conf import settings
    from django.test.simple import DjangoTestSuiteRunner
    
    class MyTestSuiteRunner(DjangoTestSuiteRunner):
        def __init__(self, *args, **kwargs):
            settings.IM_IN_TEST_MODE = True
            super(MyTestSuiteRunner, self).__init__(*args, **kwargs)
    

    NOTE: As of Django 1.8, DjangoTestSuiteRunner has been deprecated. You should use DiscoverRunner instead:

    from django.conf import settings
    from django.test.runner import DiscoverRunner
    
    
    class MyTestSuiteRunner(DiscoverRunner):
        def __init__(self, *args, **kwargs):
            settings.IM_IN_TEST_MODE = True
            super(MyTestSuiteRunner, self).__init__(*args, **kwargs)
    

提交回复
热议问题