Key Word(s): Documentation, Testing, Coverage



Exercise: Documentation and Testing

The following little program needs some documentation and some tests. Since you didn't write it, I'll tell you what it's supposed to do. You'll need to document it. Feel free to test for additional exceptions if you have time but start with it as it is.

The point of the program is to compute the $L_{2}$ norm of a vector $v$. A second argument, if provided, will be interpreted as a vector of weights. The second argument must have the same length as the input vector.

NOTE: The input type of the vectors for this program should be a list of numbers.

As a reminder, the weighted $L_2$ norm of a vector $v$ is given by \begin{align*} \|v\|_{W} = \sqrt{\sum_{i=1}^{N}{\left(w_{i}v_{i}\right)^2}} \end{align*} where $N$ is the length of the vector $v$, $v_{i}$ is the i-th component of the vector $v$ and $w_{i}$ is the i-th component of the weight vector.

Requirements

  • You must write the documentation and a decent test suite. Try to include some doctests as well!
  • Use the pytest module to run the doctests and unit tests and to assess the code coverage.

If you don't already have pytest, you can install it using pip install pytest. If you have trouble installing, here's the website: pytest installation.

Solution

The tests can be found in the file test_L2.py and the function can be found in L2.py.

Run pytest --doctest-modules --cov --cov-report term-missing from inside the directory to run the test suite. Please don't use the Jupyter notebook this time.

Interpreter

Now we'll use the Jupyter notebook as a Python interpreter.

In [1]:
# Import our module
import L2
In [2]:
# Print the documentation
import pydoc
pydoc.doc(L2)
Python Library Documentation: module L2

NAME
    L2

FUNCTIONS
    L2(v, *args)
        Compute the weighted L2 norm.
        
        INPUTS
        =======
        v: a list of floats
        args: a list of variable input arguments
           args[0]: a list of weights, floats
        
        RETURNS
        ========
        s: the weighted L2 norm of the input v
        
        NOTES
        =====
        PRE: 
             - v is a list of floats
             - the weights are stored in args[0]
        POST:
             - a, b, and c are not changed by this function
             - raises a ValueError exception if len(v) .ne. len(args[0])
             - returns a float
        
        EXAMPLES
        =========
        >>> L2([3.0, 4.0], [1.0, 2.0])
        8.54400374531753

FILE
    /Users/dsondak/Teaching/Harvard/CS207/cs207_david_sondak/lectures/L11/L2.py

In [3]:
# Run the doctests
import doctest
doctest.testmod(L2, verbose=True)
Trying:
    L2([3.0, 4.0], [1.0, 2.0])
Expecting:
    8.54400374531753
ok
1 items had no tests:
    L2
1 items passed all tests:
   1 tests in L2.L2
1 tests in 2 items.
1 passed and 0 failed.
Test passed.
Out[3]:
TestResults(failed=0, attempted=1)