When writing production standard code, your program must be tested at many different levels.
For now, let us just talk about the lowest level of tests called Unit Tests
. Lowest level doesn't mean Unit Tests
are insignificant, it's quite the opposite. These tests make sure that your code is tested at atomic level. Only once all unit tests pass then you can move on to other types of tests in the pyramid.
General guidelines for unit tests :
unittest
was the most frequently used unit testing module at one time. You define your own classes which subclasses the unittest.TestCase
superclass.
In [3]:
import unittest
def cube(x):
return x ** 3
def square(x):
return x**2
def add(x, y):
return x + y
class CalcTest(unittest.TestCase):
def test_square(self):
self.assertTrue(square(3) == 9)
self.assertFalse(square(1) == 2)
with self.assertRaises(TypeError):
cube("Lite")
def test_add(self):
self.assertTrue(add(3, 4) == 9)
def test_cube(self):
self.assertEqual(cube(3), 27)
unittest.main(argv=['first-arg-is-ignored'], exit=False, verbosity=2)
Out[3]:
You can go the unittest docs if you're interested in knowing more about this module. We won't be focusing on this cause knowing PyTest is important.
This module searches for pieces of text that resemble interactive Python sessions in docstrings, and then executes those lines of code to make sure they work. Mostly doctests are simple examples to give an idea of what the function is supposed to do.
The main use of doctests are to improve the documentation of the module by showing some main use cases of the module and its components
In [5]:
import doctest
def concat(*words, sep=" "):
"""Return a sentence from input words
separated by a separator(default being space)
>>> concat('a','b','c', 'd')
'a b c d'
>>> concat('a','1')
'b 1'
"""
return sep.join(words)
doctest.testmod()
Out[5]:
py.test is the no-boilerplate alternative to the unittest
module. It has a lot of features and most importantly can be easily extended due to its relatively simple syntax.
Test suites are as simple as writing a module(python file) with couple of test methods.
Let us see some basic examples. To explore pytest better take a look at the pytest docs.
Travis CI is a hosted, distributed continuous integration service used to build and test software projects hosted at GitHub. The best way to understand what it does is to actually create a test repository and then integrate it with Travis CI.
Let's get started !