Lab 4: Using Conditionals to Disable Testing Code

Disabling test work

When writing problem set code, unless you test all your functions via the console, you may have test invocations in your code.

For example, if you were tasked with creating a function called calculateTip, you might have the following test invocations in your file:

calculateTip(22) # Expected: 4.4
calculateTip(45.05) # Expected: 9.01
calculateTip(0) # Expected: 0

These test invocations are an important part of your work process, but they may create output that interferes with our automatic testing of your code.

Therefore, your problem set code should disable any test invocations. Of course, the most straightforward way to do this is simply delete any test lines.

Alternatively, you can use one of the following two methods:

Method 1A. “Comment out line-by-line”

#print("Start of testing.")
#diamondPattern()
#print("Done with testing.")

Method 1B. “Comment out with triple quotes”

"""
print("Start of testing.")
diamondPattern()
print("Done with testing.")
"""

In both Method 1A and 1B, the last three lines are effectively “turned off” because they're commented out; Python will ignore them regardless of the context in which the file is run.

Method 2. Main method

Nest any test invocations in an if statement that checks to see if __name__ is set to __main__. For example, you might recognize this code from PS02's diamond.py:

if __name__ == "__main__":
    '''
    All your testing code should go below.
    Uncomment and comment particular lines as appropriate.
    '''
    print("Start of testing.")
    diamondPattern()
    print("Done with testing.") # don't comment out this line

What this does:

__name__ is a special variable set by Python, and when a program is being run directly, it's set to __main__.

As a result, by nesting your test invocations in this if statement, they will only be invoked when you run your code file directly. They will not be run if your code file is imported by another file, as is the case when we test your code.

Side note: Other programming languages, like Java and C, make use of this "main method" approach; so you may see it again if you continune down the CS path!

Conclusion

The above methods have the same effect in their ability to enable/disable your tests. Choose the one that best fits your taste.

And if you prefer to run all your test invocations from the Python console, you don't have to worry about any of this.

Table of Contents