Testing

Testing is very important to minimize bugs, but also to show how routines should be called. Proper testing avoids the all-to-frequent case of a code modification breaking previously working parts, if there are enough tests covering these parts. In general, every method of a class should have a test and, if you discover a bug that is not covered by a test, you should add a test for it.

We implement testing using the unittest Unit testing framework (https://docs.python.org/3/library/unittest.html). Ideally, every submodule should have a tests directory with a test.py file. This allows you to concentrate on local tests when you are modifying code, and should keep the test.py codes from being too huge.

A good practice when you modify a function is to see if that function has a test code that will see what you are changing and, if not, to add it and run the test before and after your modifications.

To run all tests, go into the obsinfo top directory and run

The basic structure of the test.py files is:

..code-block:: python

#!/usr/bin/env python # -- coding: utf-8 -- “”” Test network and station classes “”” import warnings from pathlib import Path import unittest import difflib

# Third party imports

# obsinfo modules from obsinfo.network import (Station, Network)

warnings.simplefilter(“once”) warnings.filterwarnings(“ignore”, category=DeprecationWarning) verbose = False

class NetworkTest(unittest.TestCase):

“”” Class of test methods for network and station objects

Attributes:
testing_path (str): path to datafiles to be tested aside from the

examples

level (str): level to be printed test (boolean): determines if this is test mode print_output (boolean): determines if this is print mode. Both can

coexist.

“””

def setUp(self, test=True, print_output=False, level=None):

“”” Set up default values and paths “”” self.testing_path = Path(__file__).parent.joinpath(“data”)

self.level = level self.test = test self.print_output = print_output

def assertTextFilesEqual(self, first, second, msg=None):
with open(first) as f:

str_a = f.read()

with open(second) as f:

str_b = f.read()

if str_a != str_b:

first_lines = str_a.splitlines(True) second_lines = str_b.splitlines(True) delta = difflib.unified_diff(

first_lines, second_lines, fromfile=first, tofile=second)

message = ‘’.join(delta) if msg:

message += ” : ” + msg

self.fail(“Multi-line strings are unequal:n” + message)

def test_A(self):

“””Test of one method””” …

def test_B(self):

“””Test of another method””” …

def test_C(self):

“””Test of yet another method””” …

def suite():

return unittest.makeSuite(NetworkTest, ‘test’)

if __name__ == ‘__main__’:

unittest.main(defaultTest=’suite’)