Python base and inherited classes, test harness and unit testing - new examples
Archive - Originally posted on "The Horse's Mouth" - 2014-12-07 10:42:27 - Graham Ellis
From a recent Python course ... a new series of examples on writing, testing and using classes. The customer is using Python 2.6 and 2.7, so the code is written with what we call "new style classes" where everything eventually inherits from a base class os object - with that eventual inheritance expected to become implicit when the code is moved to Python 3.
The class definition itself is [here] - a class of "transport" to be the base for various types of transport which are all defined below within the same source file, and it also includes a very simple test harness.
Testing of code is critical, and I used this newly written class during the course as my basis for writing tests and showing off the unittest modules in simple examples - [here] for "Hello testing world" giving very simple results:
munchkin: grahamellis$ python utdemo
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
munchkin: grahamellis$
and [here] for a test set which produces a far more verbose output, and also demonstrates how errors are flagged:
munchkin: grahamellis$ python utd2
test_001 (__main__.Mytests) ... ok
test_002 (__main__.Mytests) ... ok
test_003 (__main__.Mytests) ... ok
test_004 (__main__.Mytests) ... ok
test_005 (__main__.Mytests) ... ERROR
======================================================================
ERROR: test_005 (__main__.Mytests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "utd2", line 25, in test_005
c = self.example.getstandees()
AttributeError: 'train' object has no attribute 'getstandees'
----------------------------------------------------------------------
Ran 5 tests in 0.001s
FAILED (errors=1)
munchkin: grahamellis$
Following on from our tests, there are further examples - application code snippets that use the transport classes [here] and [here], with that latter example showing how a data file can be loaded into a list of objects through a factory method. Sample data file [here].
What's missing from these examples? Documentation Strings! ... simply because the examples were written dynamically in front of delegates during the course, with time being limited, and with a desire for the whole example to fit onto a single projection screen. The documentation was there, in my verbal comments and descriptions, as the course ran - if you can think of it like that.