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

后端 未结 15 787
爱一瞬间的悲伤
爱一瞬间的悲伤 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've found that for tests within unittest or similar a framework, the most effective way to safely disable unwanted logging in unit tests is to enable/disable in the setUp/tearDown methods of a particular test case. This lets one target specifically where logs should be disabled. You could also do this explicitly on the logger of the class you're testing.

    import unittest
    import logging
    
    class TestMyUnitTest(unittest.TestCase):
        def setUp(self):
            logging.disable(logging.CRITICAL)
    
        def tearDown(self):
            logging.disable(logging.NOTSET)
    

提交回复
热议问题