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

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

    If you are multiple settings file for different environment, all you need to do is to create one settings file for testing.

    For instance, your setting files are:

    your_project/
          |_ settings/
               |_ __init__.py
               |_ base.py  <-- your original settings
               |_ testing.py  <-- for testing only
    

    In your testing.py, add a TESTING flag:

    from .base import *
    
    TESTING = True
    

    In your application, you can access settings.TESTING to check if you're in testing environment.

    To run tests, use:

    python manage.py test --settings your_project.settings.testing
    

提交回复
热议问题