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

后端 未结 15 807
爱一瞬间的悲伤
爱一瞬间的悲伤 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:32

    There is some pretty and clean method to suspend logging in tests with unittest.mock.patch method.

    foo.py:

    import logging
    
    
    logger = logging.getLogger(__name__)
    
    def bar():
        logger.error('There is some error output here!')
        return True
    

    tests.py:

    from unittest import mock, TestCase
    from foo import bar
    
    
    class FooBarTestCase(TestCase):
        @mock.patch('foo.logger', mock.Mock())
        def test_bar(self):
            self.assertTrue(bar())
    

    And python3 -m unittest tests will produce no logging output.

提交回复
热议问题