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

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

    Since you are in Django, you could add these lines to your settings.py:

    import sys
    import logging
    
    if len(sys.argv) > 1 and sys.argv[1] == 'test':
        logging.disable(logging.CRITICAL)
    

    That way you don't have to add that line in every setUp() on your tests.

    You could also do a couple of handy changes for your test needs this way.

    There is another "nicer" or "cleaner" way to add specifics to your tests and that is making your own test runner.

    Just create a class like this:

    import logging
    
    from django.test.simple import DjangoTestSuiteRunner
    from django.conf import settings
    
    class MyOwnTestRunner(DjangoTestSuiteRunner):
        def run_tests(self, test_labels, extra_tests=None, **kwargs):
    
            # Don't show logging messages while testing
            logging.disable(logging.CRITICAL)
    
            return super(MyOwnTestRunner, self).run_tests(test_labels, extra_tests, **kwargs)
    

    And now add to your settings.py file:

    TEST_RUNNER = "PATH.TO.PYFILE.MyOwnTestRunner"
    #(for example, 'utils.mytest_runner.MyOwnTestRunner')
    

    This lets you do one really handy modification that the other approach doesn't, which is to make Django just tests the applications that you want. You can do that by changing the test_labels adding this line to the test runner:

    if not test_labels:
        test_labels = ['my_app1', 'my_app2', ...]
    

提交回复
热议问题