使用Python unittest测试布尔函数

时间:2016-05-04 19:09:32

标签: python unit-testing python-2.6 python-unittest

我用Python创建了一个tic tac toe游戏。我想测试一些我的功能,以确保它们正常工作,但无法弄清楚如何去做。我尝试了几种不同的方法,包括assertTrue和assertEqual。我想要测试的功能检查电路板的行,列和对角线,看看是否有所有的X或O,并且基本上是赢家。这是我想要测试的功能。

def checkRows(letter, board):
    if ((board[0] == letter and board[1] == letter and board[2] == letter) or (board[3] == letter and board[4] == letter and board[5] == letter) or (board[6] == letter and board[7] == letter and board[8] == letter))
            return True
    else:
            return False

def checkCols(letter, board):
    if ((board[0] == letter and board[3] == letter and board[6] == letter) or (board[1] == letter and board[4] == letter and board[7] == letter) or (board[2] == letter and board[5] == letter and board[8] == letter))
            return True
    else:
            return False

def checkDiags(letter, board):
    if ((board[0] == letter and board[4] == letter and board[8] == letter) or (board[2] == letter and board[4] == letter and board[6] == letter))
            return True
    else:
            return False

我正在运行的测试我的checkCols功能不起作用,这是:

import unittest
import tictactoeFuncs

#CheckCols tests.
class TestCases(unittest.TestCase):
    def test_func1(self):
            letter = X
            board = letter
            L2 = tictactoeFuncs.checkCols(letter, board)
            self.assertEqual(L2, True)


# Run the unit tests.
if __name__ == '__main__':
   unittest.main()

我曾尝试将字母设置为等于X或O,但这不起作用,我收到错误“全局名称'X'未定义”所以我对如何测试我的功能感到非常困惑。

1 个答案:

答案 0 :(得分:1)

没关系,我想我可能已经弄清楚了。

class TestCases(unittest.TestCase):
        def test_func1(self):
            letter = "X"
            board = ([1],[2],[3])
            board == letter
            L2 = tictactoeFuncs.checkCols(letter, board)
            self.assertEqual(L2, False)


# Run the unit tests.
if __name__ == '__main__':
   unittest.main()