Testing in Python 3 - unittest, doctest and __name__ == __main__ too.
Archive - Originally posted on "The Horse's Mouth" - 2015-04-21 11:25:17 - Graham Ellis
Python's doctest modules takes an interactive session pasted into your documentations string, analyses it and reruns the Python code you used in your session ... telling you whether you're still getting the same results or not.
Firstly, it's a great way of copying tests you've done and recording the for re-use later, so that you can check whether you've damaged anything / changed behaviours when you've enhanced / updated / debugged your code later
Secondly, it's a great way of describing what your results SHOULD be and then being able to run code to make sure that you've actually acheieved your requirement ("met the specification") - that's test driven development.
There's a working examples that passes tests [here] and one that fails [here]. The class I tested may be found [here]. The doctest example should work in Python 2 and Python 3. The test class has been implemented / tested in Python 3.4.
• As well as using doctest, you can include a test harness within your individually imported modules using if __name__ == "__main__":
and such a test is included in the class we're using in this module ([here])
• A much heavier test suite - unittest - is also available in Python. There's an example of that in use to test out train class / module - see [here].
On our public public Python courses, we cover testing, introduce test driven development, and stress the importance of testing. On private courses, we can tailor what we present but we strongly encourage you to include coverage of this important subject.