Chapter 8. Assuring Quality with Testing

Some programmers test only in production. If you are not one of them, then 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. Each test covers only a small unit of code. The benefits are increased confidence in the quality of the code, reproducible tests, and, as a side effect, clearer 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 the code as much as possible. The next time we change the code, we can run the tests and catch potential regressions. In other words, any functionality already present will still work.

The topics in this chapter include the following:

  • Unit testing
  • Asserts
  • Floating-point precision

Assert functions

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. The following table shows the different utility functions:

Function

Description

assert_almost_equal()

This function raises an exception if two numbers are not equal up to a specified precision

assert_approx_equal()

This function raises an exception if two numbers are not equal up to a certain significance

assert_array_almost_equal()

This function raises an exception if two arrays are not equal up to a specified precision

assert_array_equal()

This function raises an exception if two arrays are not equal.

assert_array_less()

This function raises an exception if two arrays do not have the same shape, and the elements of the first array are strictly less than the elements of the second array

assert_equal()

This function raises an exception if two objects are not equal

assert_raises()

This function fails if a specified exception is not raised by a callable invoked with defined arguments

assert_warns()

This function fails if a specified warning is not thrown

assert_string_equal()

This function asserts that two strings are equal

assert_allclose()

This function raise an assertion if two objects are not equal up to desired tolerance

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset