Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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 <code>if TESTING</code> block 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.</p> <p><em>However</em>, if you insist of doing this, there are two potential ways (that I can think of) this can be done.</p> <p>First of, you could use a module level <code>TESTING</code> var that you set in your test case to <code>True</code>. For example:</p> <p><strong>Production Code:</strong></p> <pre><code>TESTING = False # This is false until overridden in tests def foo(): if TESTING: print "expensive stuff..." </code></pre> <p><strong>Unit-Test Code:</strong></p> <pre><code>import production def test_foo(): production.TESTING = True production.foo() # Prints "expensive stuff..." </code></pre> <p>The second way is to use python's builtin <code>assert</code> keyword. When python is run with <code>-O</code>, 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 <code>-O</code> flag.</p> <p><strong>Example (Production Code):</strong></p> <pre><code>def expensive_checks(): print "expensive stuff..." return True def foo(): print "normal, speedy stuff." assert expensive_checks() foo() </code></pre> <p><strong>Output (run with <code>python mycode.py</code>)</strong></p> <pre><code>normal, speedy stuff. expensive stuff... </code></pre> <p><strong>Output (run with <code>python -O mycode.py</code>)</strong></p> <pre><code>normal, speedy stuff. </code></pre> <p>One word of caution about the assert statements... if the assert statement does not evaluate to a true value, an <code>AssertionError</code> will be raised.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload