Why do assertions in unittest use TestCase.assertEqual not the assert keyword?

The problem with the assert keyword is that it is optimized out, and thus ignored, when Python is run in ‘optimized’ mode (with the -O argument or with the PYTHONOPTIMIZE environment variable set.) If tests were to use assert then testing with -O would be impossible.

Additionally, the use of the assert methods makes it trivial to report about what the values involved actually were, without having to dig into the stack and the source and figure out what they were supposed to be (which, I believe, is the technique nose and py.test use for this.)

Leave a Comment