Goals
- Learn about what unit tests are.
- Learn how to create and run unit tests using the Python
unittest module.
Background
Python's unittest module,
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 or post
them in #questions on Slack.
- Update your copy of my CS257 GitHub repo.
There should be a folder called tdd/, containing Python files
primechecker.py and primecheckertests.py.
- Don't open primechecker.py, but do the following to learn about PrimeChecker
and its two main methods:
python3
>>> import primechecker
>>> dir(primechecker.PrimeChecker)
...
>>> help(primechecker.PrimeChecker.is_prime)
...
>>> help(primechecker.PrimeChecker.get_primes_below)
...
- Read through the
Basic Example
in the unittest documentation.
Then take a look, briefly, at the more formal documentation of
assertFalse and assertTrue
and
unittest.TestCase.
- Read through primecheckertests.py. What do you expect to see when you run it, and why?
- Run "python3 primecheckertests.py". What happens? Was it consistent with your prediction?
What does the output "....E" (or whatever similar string you see at the top of the output)
mean in this context?
- Put print statements in setUp, tearDown, and each of the test_xxxxx methods.
When and in what order do these methods get called?
- 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)?
- Based on the documentation for is_prime, what should happen when you call is_prime(0)?
Use this information and this chart
to fix test_zero.
- 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?
- Add more tests to check the boundary cases for is_prime and
get_primes_below. Be creative—try to
think of all the different ways programmers might abuse these methods, and create a test for each.
Be ready to discuss your tests, and how they went, in your discussion group.
- 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?
- Put primechecker.py back the way you found it, and make sure it passes all your tests.
- 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?