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

前端 未结 8 861
长情又很酷
长情又很酷 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条回答
  •  猫巷女王i
    2020-12-07 21:05

    Put this in your settings.py:

    import sys
    
    TESTING = len(sys.argv) > 1 and sys.argv[1] == 'test'
    

    This tests whether the second commandline argument (after ./manage.py) was test. Then you can access this variable from other modules, like so:

    from django.conf import settings
    
    if settings.TESTING:
        ...
    

    There are good reasons to do this: suppose you're accessing some backend service, other than Django's models and DB connections. Then you might need to know when to call the production service vs. the test service.

提交回复
热议问题