Some programmers test only in production. If you are not one of them you're probably familiar with the concept of unit testing. Unit tests are automated tests written by a programmer to test his or her code. These tests could, for example, test a function or part of a function in isolation. Only a small unit of code is tested by each test. The benefits are increased confidence in the quality of the code, reproducible tests, and as a side effect, more clear code.
Python has good support for unit testing. Additionally, NumPy adds the numpy.testing
package to that for NumPy code unit testing.
Test driven development (TDD) is one of the most important things that happened to software development. TDD focuses a lot on automated unit testing. The goal is to test automatically as much as possible of the code. The next time the code is changed we can run the tests and catch potential regressions. In other words functionality already present will still work.
This chapter's topics include:
Unit tests usually use functions, which assert something as part of the test. When doing numerical calculations, often we have the fundamental issue of trying to compare floating-point numbers that are almost equal. For integers, comparison is a trivial operation, but for floating-point numbers it is not because of the inexact representation by computers. The numpy.testing
package has a number of utility functions that test whether a precondition is true or not, taking into account the problem of floating-point comparisons: