In most cases the best approach to study how something works is to test its behavior in various circumstances. In a helicopter view it is a dissection or a scrutiny.

The same approach for studying programming language has a plethora benefits and the most significant is that it take you chance to play with code. Of cause studying by playing is a most natural way of learning.



Lets create a mold for pouring by the test suits:

#+BEGIN_SRC python :noweb yes :results none :tangle tests/
"""Discover how it works by a coherent testing"""

# it might be several test cases
# thus several test classes
# as several include source code block

Tip Use C-c C-v t to generate (tangle) the test file

Necessary imports

It's clear what you expected to test by means the unittest module:

#+NAME: import-header
#+BEGIN_SRC python
import unittest

Test suits

Each test case class as a separate source code block with a particular name for substitution into template.

#+NAME: built-in-constants-test
#+BEGIN_SRC python
  class TestBuiltInConstants(unittest.TestCase):

      def test_true(self):
          self.assertTrue(1 + 3 == 4)

      def test_false(self):
          self.assertFalse(1 + 4 == 4)

      def test_none(self):
          value = None

Obviously that arbitrary number of named blocks can exist there.

Test runner

Accustomed unittest as Python module:

#+BEGIN_SRC sh :results output :exports both
  python -m unittest -v tests/


: test_false (tests.test_built-in_constants.TestBuiltInConstants) ... ok
: test_none (tests.test_built-in_constants.TestBuiltInConstants) ... ok
: test_true (tests.test_built-in_constants.TestBuiltInConstants) ... ok
: ----------------------------------------------------------------------
: Ran 3 tests in 0.002s
: OK


Now it is totally clear how to compose tests for Python standard library testing in a literate programming style.

blog comments powered by Disqus


09 September 2016


python stdlib TDD literate programming