Login

Testing for failure in management commands

Author:
David
Posted:
August 17, 2010
Language:
Python
Version:
1.2
Score:
1 (after 1 ratings)

Because BaseCommand catches all CommandError exceptions and turns them into nicely formatted strings before calling sys.exit(1), it can be tricky to properly test failure.

Normally, this is great, but it makes testing that a command fails when we expect to a little harder. That's where this snippet comes in. It redirects sys.stderr to an instance StringIO where we can monitor what's output and catches the BaseException raised by sys.exit(1). Form here, it's trivial to test that a management command fails exactly as you'd expect it to.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import cStrinIO
import sys

from django.test import TestCase


class MyCommandTestCase(TestCase):

    def test_mycommand_failure(self):
        old_stderr = sys.stderr
        sys.stderr = cStringIO.StringIO()
        self.assertRaises(BaseException, management.call_command, 'mycommand')
        self.assertTrue('Error: Some error condition here' in sys.stderr.getvalue())
        sys.stderr = old_stderr

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.