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

前端 未结 8 845
长情又很酷
长情又很酷 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
    

提交回复
热议问题