I'm trying to learn how to build a good test suite, using simple sorting as an example. Particularly, I am using Nose to generate all the tests based on a simple list of lists, where each sublist is a unit-test for each sorting method, as seen below:
from nose.tools import assert_equal def check_sort(s, arr): assert_equal( s(arr), sorted(arr) ) def selection_sort(arr): """Repeatedly find the smallest element in the unsorted part and swap it with the first element in the unsorted part""" for i in xrange(len(arr)): min_val = min(arr[i:]) min_ind = i + arr[i:].index(min_val) arr[i], arr[min_ind] = arr[min_ind], arr[i] return arr def test_sorts(): sorts = [selection_sort] for s in sorts: examples = [ ,\ ,\ [1,1],\ [1, 2, 3],\ [1, 3, 2],\ [2, 1, 3],\ [2, 3, 1],\ [3, 1, 2],\ [3, 2, 1],\ [-10, 35, 4, 99, 1003, 2],\ [-10, 2, 35, 4, 4, 99, 99, 1003, 2]] for arr in examples: yield check_sort, s, arr
It seems to me that there has to be a better way of doing this, by using classes and more advanced methods to set-up and tear-down on the go. The caveat is that I would like to be able to extend the
sorts list, adding more functions that implement bubble sort, merge sort, quick sort, etc. without having to create more tests by hand.
Any advice is appreciated.