简体   繁体   中英

Enable Python code only for unittests?

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 TESTING 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.

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 TESTING var that you set in your test case to True . For example:

Production Code:

TESTING = False    # This is false until overridden in tests

def foo():
    if TESTING:
        print "expensive stuff..."

Unit-Test Code:

import production

def test_foo():
    production.TESTING = True
    production.foo()    # Prints "expensive stuff..."

The second way is to use python's builtin assert keyword. 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 -O flag.

Example (Production Code):

def expensive_checks():
    print "expensive stuff..."
    return True

def foo():
    print "normal, speedy stuff."
    assert expensive_checks()

foo()

Output (run with python mycode.py )

normal, speedy stuff.
expensive stuff...

Output (run with python -O mycode.py )

normal, speedy stuff.

One word of caution about the assert statements... if the assert statement does not evaluate to a true value, an AssertionError will be raised.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM