How can I disable logging while running unit tests in Python Django?

后端 未结 15 723
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 09:50

I am using a simple unit test based test runner to test my Django application.

My application itself is configured to use a basic logger in settings.py using:

<
15条回答
  •  醉梦人生
    2020-12-07 10:38

    I like Hassek's custom test runner idea. It should be noted that DjangoTestSuiteRunner is no longer the default test runner in Django 1.6+, it has been replaced by the DiscoverRunner. For default behaviour, the test runner should be more like:

    import logging
    
    from django.test.runner import DiscoverRunner
    
    class NoLoggingTestRunner(DiscoverRunner):
        def run_tests(self, test_labels, extra_tests=None, **kwargs):
    
            # disable logging below CRITICAL while testing
            logging.disable(logging.CRITICAL)
    
            return super(NoLoggingTestRunner, self).run_tests(test_labels, extra_tests, **kwargs)
    

提交回复
热议问题