Testing for failure in management commands
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.