Let’s say I have the following function:
def f():
if TESTING:
# Run expensive sanity check code
...
What is the correct way to run the TESTING code block only if we are running a unittest?
[edit: Is there some “global” variable I can access to find out if unittests are on?]
Generally, I’d suggest not doing this. Your production-code really shouldn’t realize that the unit-tests exist. One reason for this, is that you could have code in your
if TESTINGblock that makes the tests pass (accidentally), and since production runs of your code won’t run these bits, could leave you exposed to failure in production even when your tests pass.However, if you insist of doing this, there are two potential ways (that I can think of) this can be done.
First of, you could use a module level
TESTINGvar that you set in your test case toTrue. For example:Production Code:
Unit-Test Code:
The second way is to use python’s builtin
assertkeyword. When python is run with-O, the interpreter will strip (or ignore) all assert statements in your code, allowing you to sprinkle these expensive gems throughout and know they will not be run if it is executed in optimized mode. Just be sure to run your tests without the-Oflag.Example (Production Code):
Output (run with
python mycode.py)Output (run with
python -O mycode.py)One word of caution about the assert statements… if the assert statement does not evaluate to a true value, an
AssertionErrorwill be raised.