简体   繁体   中英

Testing a boolean function with Python unittest

I have created a tic tac toe game in Python. I want to test a few of my functions to make sure they work properly but can't figure out how to go about it. I've tried a few different methods including assertTrue and assertEqual. The functions I want to test check the rows, columns, and diagonals of the board to see if there is either all X's or O's and essentially a winner. Here are the functions I want to test.

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

The test I'm running right now for my checkCols function doesn't work which is this:

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()

I had tried setting letter equal to X or O but that didn't work and I get the error "global name 'X' is not defined" so I'm very confused as to how to test my functions.

Nevermind I think I might've figured it out.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM