Python Unit Test examples don't apply?

Viewed 33

I am currently unit testing my Python Code. As I am only learning python (self taught) I started off with making a game - A custom game with no real use case just to have "functional" code.

A player has a limit of how many items they can carry in their inventory. So I have the following (note: there is more in player, but isn't needed for the rest of this case)

class Player:
def __init__(self):
    self.inventory: list = []
    
def drop_item(self, index):
    self.inventory.pop(index)
    

My test case is as follows (importing unittest and Player)

class TestPlayer(unittest.TestCase):

def test_drop_item(self):
    p = Player()
    p.inventory = ["A", "B"]
    inv_len = len(p.inventory)
    print(f"Player's currently holds {inv_len} item's")
    p.drop_item(1)
    self.assertIs(inv_len, 1, "Passed")

I did run into the issue of drop_item freaking out because it didn't have a self case, hence why the test has the p = player() - this fixed it thought is this technically right?

I get the slight issue of:

line X, in test_drop_item self.assertIs(inv_len, 1, "Passed") 
AssertionError: 2 is not 1 : Passed

Where it should have popped "B" from the list just leaving ["A"] in the list

Now to pivot to the example that I had found, that does work:

def add(x, y):
"""Add Function"""
return x + y

class TestAdd(unittest.TestCase):
    def test_add(self):
        result = add(10, 5)
        self.assertEqual(result, 15)

I know they are different in terms of what they are trying to test however I feel like there "isn't anything wrong" in what I currently have. I am missing something here? Could it be to do with something how my pop works?

1 Answers

You assigned the length on the inventory to inv_len before dropping an item. Such an assignment just copies the value, and it won't continue updating after the initial assignment. One approach is to remove the local variable and just call len(p.inventory) whenever you need it:

def test_drop_item(self):
    p = Player()
    p.inventory = ["A", "B"]
    print(f"Player's currently holds {len(p.inventory)} item's")
    p.drop_item(1)
    self.assertIs(len(p.inventory), 1, "Passed")
Related