django - how to detect test environment (check / determine if tests are being run)

前端 未结 8 837
长情又很酷
长情又很酷 2020-12-07 20:40

How can I detect whether a view is being called in a test environment (e.g., from manage.py test)?

#pseudo_code
def my_view(request):
    if not          


        
相关标签:
8条回答
  • 2020-12-07 21:23

    I think the best approach is to run your tests using their own settings file (i.e. settings/tests.py). That file can look like this (the first line imports settings from a local.py settings file):

    from local import *
    TEST_MODE = True
    

    Then do ducktyping to check if you are in test mode.

    try:
        if settings.TEST_MODE:
            print 'foo'
    except AttributeError:
        pass
    
    0 讨论(0)
  • 2020-12-07 21:31

    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)
    
    0 讨论(0)
提交回复
热议问题