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. Note that if you're using option 1B, the starting triple-quote must still be indented at the right level (it should match the indentation of the first line of code in your "comment").
Method 2. Test function
As you have seen in many of our provided starter files, another solution is to
put all of your code in a function called test
. Then you can call this test
function to test your code!
To streamline things even more, you can use a special conditional to invoke
your test
function whenever the file is run, but NOT when we import it to
grade it. To achieve this, invoke your test
function inside a conditional
where the condition is that the special variable __name__
is equal to the
special value '__main__'
.
Details: Why does this work?
The __name__
variable tells Python the name of the current module, and
'__main__'
is used when we're in the file that's being run instead of a file
that's imported. So for example, if you opened up a copy of turtleBeads.py
and clicked "Run", the __name__
variable would be set to '__main__'
within
that code. But if you instead run a different file that uses from turtleBeads import *
, during the same code (now being imported), the __name__
variable
will hold the value 'turtleBeads'
.
This is why if you do run the turtleBeads
file you'll see a bunch of tests
happen, but those same tests don't run when you import the module to use it,
which would be inconvenient.
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 shell, you don't have to worry about any of this.