Python unit testing super fun time
There’s a weird thing that happens after a long night of mind-blowing back-breaking coding. Well, hacking in this case. Every time I stay up late working really hard on something, I feel compelled to blog/tweet/emote about my experience so others might feel sympathy/compassion for me. Even though I’m dizzyingly tired, and have to get up in ~5 hours, I cannot deny this urge to massage my ego.
So tonight I bring to you the joy of unit testing in Python. I’ve been using py.test, and loving it. It extends the basic functionality of Python’s built-in module, unittest (which is really not that bad). The main improvements are in the simplicity of writing the tests. Py.test supports unit testing on methods, classes, even whole modules.
Here’s your first test
def test_iszero():
assert 1==0
If you haven’t guessed, this test will fail (1 does not equal 0). A cool thing about py.test is that you just prefix the method name with “test_” and that becomes a test. If it’s in a class or module, you need setup and teardown methods, but beyond that just write methods starting with “test_”. There’s lots more fancy stuff you can do, I suggest checking out the docs (link above).
However, by my favorite thing py.test does is support generative testing. By using generators, a test can spawn “sub” tests with a yield statement. Let’s say I want to test if a bunch of numbers are even.
def isEven(x):
assert x%2==0
def test_evenNumbers():
n = [1,2,3,4,5,6]
for x in n:
yield isEven,x
This can be tremendously helpful when you need to do a repetitive test on many input parameters. Enjoy!
-David
[...] the vaingloriously-named “py” module, is my unit testing framework of choice (I have written about it before). It provides a convenient way to collect tests and to write generative tests (which are super [...]
API Functional Testing with Python at Null Disquisition
18 Jul 09 at 6:03 pm