Search code examples
djangodjango-testingdjango-unittest

How to use verbosity level in your tests in Django


Running a Django test case allows you to specify verbosity (0,1,2,3) like this

manage.py test -v 2 myapp.tests.test_mycode.TestMyCode.test_func 

How can I receive the verbosity flag inside my test_func


Solution

  • You can use inspect module:

    from django.test import TestCase
    import inspect
    
    class MyTest(TestCase):
    
        def get_verbosity(self):
            for s in reversed(inspect.stack()):
                options = s[0].f_locals.get('options')
                if isinstance(options, dict):
                    return int(options['verbosity'])
            return 1
    
        def test_func(self):
            verbosity = self.get_verbosity()
            self.assertEqual(verbosity, 2)