Most of the power of testing in Python comes from the unittest
framework and it’s TestCase
class.
Technically, unittest is Python’s library for writing tests.
TestCase
TestCase is a collection of tests. It is a class that contains multiple methods,
some of which are tests, and others that are just methods that you need.
There are two special methods, Set Up
and Tear Down
, that are run before and after each test.
Our First Test
Now, unlike doc tests, we’re gonna write all of our tests in a separate file, called test.py
.
To write our tests, we’re gonna group our tests into what’s called a test case.
So, we’re gonna make a new class and we’re gonna call this MoveTests
, and it’s going to extend unittest.TestCase
.
import unittest
import moves
class MoveTests(unittest.TestCase):
def test_five_plus_five(self):
assert 5 + 5 == 10
def test_one_plus_one(self):
assert not 1 + 1 == 3
import unittest
The library that let’s you write tests.
import moves
The code we’re actually going to test after trying out these simple math tests.
def test_five_plus_five(self)
All tests in a TestCase have to start with the word test_ to be run.
You can have methods that don’t start with test_ for other purposes if you need them.
assert 5 + 5 == 10
Assert makes sure that whatever comes after it is true.
Running tests
Command Line
python -m unittest tests.py
In a Script
If you want the tests to run automatically when you run the script using python tests.py
, add the following lines to the bottom of tests.py
.
if __name__ == '__main__':
unittest.main()
For more information on UnitTests, check its documentation.
https://docs.python.org/3/library/unittest.html