Writing Testable Numerics Code

Copyright (C) 2020 Andreas Kloeckner

MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Here's the contents of a file containing numerics code:

In [15]:
!pygmentize norms.py
import numpy as np

def norm_1(ary):
    """Computes the 1-norm of vectors or matrices *ary* passed in as numpy arrays."""
    
    if len(ary.shape) == 1:
        return np.sum(np.abs(ary))
    elif len(ary.shape) == 2:
        return np.max(np.sum(np.abs(ary), axis=1))
    else:
        raise ValueError("ary must be vector or matrix")

Note:

  • Docstring
  • Defensive programming
In [16]:
!pygmentize test_norms.py
import numpy as np

def test_norm_1():
    from norms import norm_1

    for i in range(10):
        A = np.random.randn(20, 20)
        x = np.random.randn(20)
        
        assert norm_1(A@x) <= norm_1(A) * norm_1(x)
  • Now use pytest to run the test.
In [17]:
!python -m pytest
============================= test session starts ==============================
platform linux -- Python 3.7.2+, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: /home/andreas, inifile: pytest.ini
plugins: celery-4.2.1
collected 1 item                                                               

test_norms.py .                                                          [100%]

=========================== 1 passed in 0.13 seconds ===========================

A typical use for these tests would be to run them on every commit to a codebase.

Example: https://github.com/inducer/boxtree (click the "Pipeline" button)

In [ ]: