3

I have a Django custom command that can return non-zero exit codes. I'd like to test this command, but the call to sys.exit(1) exits the test runner.

Is there a "proper" way to assign the exit code in a custom Django command?

My code currently looks like this:

# Exit with the appropriate return code
if len(result.failures) > 0 or len(result.errors) > 0:
    sys.exit(1)
Mickaël
  • 3,763
  • 5
  • 26
  • 32

2 Answers2

7

I chose to mock the call to sys.exit() in the tests to prevent it to exit the test runner:

from mock import patch
with patch('sys.exit') as exit_mocked:
    call_command(...)
    exit_mocked.assert_called_with(1)
Mickaël
  • 3,763
  • 5
  • 26
  • 32
  • I liked the solution, but I also think it is worth mentioning that if you have more code after `exit(CODE)`, when mocked, the code that comes after will run normally as if there was no `exit` call. – Ruben Alves Nov 26 '20 at 17:51
0

A solution that worked for me was the one taken from https://stackoverflow.com/a/8332117/6490637. My unit test ended like this:

with self.assertRaises(SystemExit) as sys_exit:
    # call your code here
    pass


# Assuming I'm expecting 101 as the exit code
self.assertEquals(sys_exit.exception.code, 101)
Ruben Alves
  • 166
  • 4
  • 12