Unit Tests

Terms defined: mock object, parameterize (a test)

False Starts

def test_grid_array_constructed_correctly():
    g = GridArray(2, 3, 4)
    assert g.width() == 2
    assert g.height() == 3
    assert g.depth() == 4
    for x in range(g.width()):
        for y in range(g.height()):
            assert g[x, y] > 0
def test_grid_list_constructed_correctly():
    g = GridList(2, 3, 4)
    assert g.width() == 2
    assert g.height() == 3
    assert g.depth() == 4
    for x in range(g.width()):
        for y in range(g.height()):
            assert g[x, y] > 0
def __init__(self, width, height, depth, rand=random.randint):
    """Construct and fill."""
    super().__init__(width, height, depth)
    self._rand = rand
    self._grid = []
    for x in range(self._width):
        row = []
        for y in range(self._height):
            row.append(self._rand(1, depth))
        self._grid.append(row)
def test_grid_list_with_randomizer_function():

    def r(low, high):
        return 12345
    g = GridListRandomizer(2, 3, 4, r)
    assert g.width() == 2
    assert g.height() == 3
    assert g.depth() == 4
    for x in range(g.width()):
        for y in range(g.height()):
            assert g[x, y] == 12345

Better Tools

def test_grid_list_patching_randomization():
    with patch('random.randint', return_value=12345):
        g = GridList(2, 3, 4)
    assert g.width() == 2
    assert g.height() == 3
    assert g.depth() == 4
    for x in range(g.width()):
        for y in range(g.height()):
            assert g[x, y] == 12345
@pytest.mark.parametrize('cls', [GridArray, GridList])
def test_grid_list_parameterizing_classes(cls):
    with patch('random.randint', return_value=12345):
        g = cls(2, 3, 4)
    assert g.width() == 2
    assert g.height() == 3
    assert g.depth() == 4
    for x in range(g.width()):
        for y in range(g.height()):
            assert g[x, y] == 12345

A Testable Grid

def __init__(self, width, height, depth, values):
    """Construct and fill."""
    assert len(values) == width
    assert all((len(col) == height for col in values))
    super().__init__(width, height, depth)
    self._grid = [col[:] for col in values]
def test_explicit_filling_fills_correctly():
    g = GridFilled(3, 3, 4, [[1, 1, 1], [2, 2, 2], [3, 3, 3]])
    assert g.width() == 3
    assert g.height() == 3
    assert g.depth() == 4
    for x in range(g.width()):
        assert all((g[x, y] == x + 1 for y in range(g.height())))
def test_filling_with_straight_run_to_edge():
    g = GridFilled(3, 3, 4, [[4, 1, 4], [4, 4, 4], [4, 4, 4]])
    g.fill()
    assert g == GridFilled(3, 3, 4, [[4, 0, 4], [4, 0, 4], [4, 4, 4]])

Exercises

  1. Refactor grid classes so that we have a patchable method for filling initial values.