Erik Rullestad
Erik Rullestad

Reputation: 29

Writing a test in python

Im currently taking a python class and im new in programming. I have written the code below and want to write a code that tests if the ResilientPlayer actually does what it is supposed to. The code is from a chutes and ladders board game where the ResilientPlayer is a "special" type of player that gets a "superpower" in its next move afther falling down a chute. The next round afther he has fallen down a chute, he will add a given or a default number to the die_roll, and I want to test if my code actually does this! Hope someone can help me with this problem :)

class Player:
    def __init__(self, board):
        self.board = board
        self.position = 0
        self.n_steps = 0

    def move(self):
        die_roll = random.randint(1, 6)
        self.position = self.get_position() + die_roll

        self.board.position_adjustment(self.position)

        self.n_steps += 1

    def get_position(self):
        return self.position

    def get_steps(self):
        return self.n_steps


class ResilientPlayer(Player):
    default_extra_steps = 1

    def __init__(self, board, extra_steps=None):
        super().__init__(board)
        self.extra_steps = extra_steps
        if self.extra_steps is None:
            self.extra_steps = self.default_extra_steps

    def move(self):
        if self.get_position() in self.board.chutes.values():
            die_roll = random.randint(1, 6)
            self.position = self.get_position() + die_roll + self.extra_steps

            self.board.position_adjustment(self.position)

            self.n_steps += 1
        else:
            super().move()

    def get_position(self):
        return self.position

    def get_steps(self):
        return self.n_steps

Upvotes: 2

Views: 67

Answers (1)

Nathan
Nathan

Reputation: 3648

The best way to do this is using the unittest class, I do this as following:

import unittest
from .... import ResilientPlayer


class TestResilientPlayer(unittest.TestCase):

    def setUp(self):
        self.resilient_player = ResilientPlayer(....)

    def test_move(self):
        # Do stuff
        self.assertEqual(1, 1)


if __name__ == '__main__':
    unittest.main()

Here, unittest.main() will run all the tests in the file. setUp is run before each test (so you can have multiple tests with the same starting conditions).

This is an incredible useful module and I strongly suggest reading more on it, check the documentation

Upvotes: 1

Related Questions