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

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

    There's also a way to temporarily overwrite settings in a unit test in Django. This might be a easier/cleaner solution for certain cases.

    You can do this inside a test:

    with self.settings(MY_SETTING='my_value'):
        # test code
    

    Or add it as a decorator on the test method:

    @override_settings(MY_SETTING='my_value')
    def test_my_test(self):
        # test code
    

    You can also set the decorator for the whole test case class:

    @override_settings(MY_SETTING='my_value')
    class MyTestCase(TestCase):
        # test methods
    

    For more info check the Django docs: https://docs.djangoproject.com/en/1.11/topics/testing/tools/#django.test.override_settings

提交回复
热议问题