CS 257: Software Design

In-class lab exercise: unit testing in Python

Python's unittest framework, also known as PyUnit, gives you a simple tool to help you do Test-Driven Development (TDD). This exercise will give you a short introduction to unittest.

If you have questions while you work, write them on your wall.

  1. Get primechecker.py and primecheckertests.py.

  2. Don't open primechecker.py, but do the following to learn about PrimeChecker and its two main methods:

    python
    >>> import primechecker
    >>> dir(primechecker.PrimeChecker)
    ...
    >>> help(primechecker.PrimeChecker.isPrime)
    ...
    >>> help(primechecker.PrimeChecker.getPrimesBelow)
    ...
    
  3. Read through primecheckertests.py. What do you expect to see when you run it, and why? You may want to read briefly about unittest.TestCase and assertFalse and assertTrue in the unittest documentation.

  4. Run primecheckertests.py. What happens? Was it consistent with your prediction?

  5. Put print statements in setUp, tearDown, and each of the testXXXX methods. When and in what order do these methods get called?

  6. The Best practices: Test structure section of the Wikipedia page on TDD, the authors describe four phases of a good test case: setup, execution, validation, and cleanup. In primecheckertests.py, where do these four phases happen (if at all)?

  7. Based on the documentation for isPrime, what should happen when you call isPrime(0)? Use this information and this chart to fix testZero.

  8. Add a new test to check what happens when you test a negative number for primality. What should you name the test? What should happen when you run it?

  9. Add more tests to check the boundary cases for isPrime and getPrimesBelow. Be creative--try to think of all the different ways programmers might abuse these methods, and create a test for each. Write the names of your new tests on your wall.

  10. Open primechecker.py and break its algorithm in some simple way (e.g. on line 24, you could change "currentPrime = 2" to "currentPrime = 3"). What do you expect will happen if you re-run the unit tests after this change? Re-run the unit tests. Did your test suite detect the error you introduced?

  11. Put primechecker.py back the way you found it, and make sure it passes all your tests.

  12. Consider this. Suppose you were about to embark on the implementation of a Python project, and you had already designed your class interfaces and typed up the method signatures as stubs. Now suppose you took the time at this stage to write unit tests analogous to primecheckertests.py. How would this affect the progress of your code-writing and debugging?