Python offers us unittest, an official unit testing framework for Python, sometimes referred as PyUnit. It's like a Python version of JUnit for Java and written by Kent Beck and Erich Gamma.
For more information on how to use unittest, visit: http://docs.python.org/2/library/unittest.html
Currently the best package that helps us write Python unit tests is called sublime-unittest written by Samuel Martin, which can be found at https://github.com/martinsam/sublime-unittest.
Python's unittest for Sublime is a package that contains a number of useful snippets to ease our unittest writing. To install the package, we'll use Package Control. Let's open the command palette by pressing Ctrl + Shift + P in Windows or Linux and Command + Shift + P in OS X. Then choose Install Package and install the Unittest (python) package.
The installed package has two main snippets:
class [Foo]TestCase(unittest.TestCase): …
def test_[foo](self): …
After creating a test function, we'll need to use some assertions, which the package includes and also the following assertions snippets:
Snippet |
Function |
Checks that |
---|---|---|
asse |
|
|
assne |
|
|
asst |
|
|
assf |
|
|
assis |
|
|
assisnt |
|
|
assisne |
|
|
assisntne |
|
|
assin |
|
|
assnin |
|
|
assisins |
|
|
assnisins |
|
|
Let's try creating a new Test
class using our snippets, starting with writing testclass
and pressing Tab to insert the snippet. We'll call our TestSequenceFunctions
class. We'll also create a test function called test_shuffle
using the testfunc
snippet, as shown in the following screenshot:
When inserting a snippet, we will get the preceding autocomplete window. Pressing Tab will insert the snippet.
import random import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.sequence = range(30) def test_shuffle(self): # checks that the shuffled sequence doesn't lose any elements while shuffling and sorting random.shuffle(self.sequence) self.sequence.sort() self.assertEqual(self.sequence, range(30), msg="Elements missing") if __name__ == '__main__': unittest.main()
When this code is executed, the setUp
function is the first to be called and will initialize our sequence
. After that, it will start to run all the test functions and assert if something goes wrong. The test functions test_shuffle
or random.shuffle(self.sequence)
will shuffle our sequence randomly, and then self.sequence.sort()
will sort it back. Afterwards, we check if our sorted sequence is equal to range(30)
, which returns a sorted sequence from 0
to 30
. If something went wrong and the sequence doesn't equal the range of 0
to 30
, then this test will fail with a message of Elements missing.
We can run this code as we run every Python code:
C:UsersDanpeDesktop>python sample.py . --------------------------------------------------------------- Ran 1 test in 0.000s OK
The preceding is the result of a successful run of our test.