import unittest from sudoku import * class SudokuTestCase( unittest.TestCase ): SQUARE = 3 SQUARE_SQUARE = 3 ROW_SIZE = COL_SIZE = SQUARE * SQUARE_SQUARE def noneMatrix(self): noneMatrix = [ [ None for j in range( 1, self.COL_SIZE + 1 ) ] for i in range( 1, self.ROW_SIZE + 1 ) ] return noneMatrix def goodStringMatrix(self): return [ "123456789", "456789123", "789123456", "234567891", "567891234", "891234567", "345678912", "678912345", "912345678" ] def testInitNone(self): self.failUnless( Sudoku( self.noneMatrix() ) ) def testInitSameRow( self ): badRowMatrix = [ [ j for j in range( 1, self.COL_SIZE+1 ) ] for i in range( 1, self.ROW_SIZE + 1) ] self.failUnlessRaises( SudokuException, Sudoku, badRowMatrix ) def testInitSameCol( self ): badColMatrix = [ [ i for j in range( 1, self.COL_SIZE+1 ) ] for i in range( 1, self.ROW_SIZE + 1 ) ] self.failUnlessRaises( SudokuException, Sudoku, badColMatrix ) def testInitSameSquare( self ): """creates 3 4 5 ... 4 5 6 ... 5 6 7 ... ..... (same values in square but different across rows and cols) """ badSquareMatrix = [ [ (i+j)% self.COL_SIZE + 1 for j in range( 1, self.COL_SIZE + 1 ) ] for i in range( 1, self.ROW_SIZE + 1 ) ] self.failUnlessRaises( SudokuException, Sudoku, badSquareMatrix ) def testEmptyStringMatrix(self): stringMatrix = [ " "*self.COL_SIZE for i in range(self.ROW_SIZE) ] self.failUnless( Sudoku( stringMatrix ) ) def testFullMatrix(self): stringMatrix = self.goodStringMatrix() self.failUnless( Sudoku( stringMatrix ) ) def testAddMatrix(self): noneMatrix = self.noneMatrix() s = Sudoku( noneMatrix ) s.add_val( 0, 0, 1 ) s.add_val( 1, 1, 2 ) self.failUnless( s ) def testAddBadMatrix(self): noneMatrix = self.noneMatrix() s = Sudoku( noneMatrix ) s.add_val( 0, 0, 1 ) self.failUnlessRaises( SudokuException, s.add_val, 1, 1, 1 ) def testStrings(self): goodStringMatrix = self.goodStringMatrix() s = Sudoku( goodStringMatrix ) retStrings = s.strings() self.failUnlessEqual( goodStringMatrix, retStrings ) def testString(self): goodStringMatrix = self.goodStringMatrix() s = Sudoku( goodStringMatrix ) retString = s.string() self.failUnlessEqual ( ''.join( map(lambda x: x+"\n", goodStringMatrix )), retString ) def testSolution1(self): s = Sudoku( [ " 4 8 7 ", " 7 63", " 3 4 1 ", " 8", "8 1 5 6", "9 ", " 5 4 2 ", "14 6 ", " 7 2 5 ", ] ) answer = Sudoku( [ "564381792", "281597463", "739462815", "415976238", "823145976", "976238154", "358714629", "142659387", "697823541", ] ) possibles = s.solution() self.failUnlessEqual( possibles, answer ) def testSolution2(self): s = Sudoku( [ " 1 5 ", " 2 3 4", " 7 1482 ", " 6 5", " 45 2 13 ", "3 6 ", " 5128 7 ", "7 9 2 ", " 7 4 ", ] ) answer = Sudoku( [ "814562973", "692738514", "537914826", "126379485", "945826137", "378145692", "451283769", "763491258", "289657341", ] ) possibles = s.solution() self.failUnlessEqual( possibles, answer ) if __name__ == '__main__': unittest.main()