dimanche 5 avril 2020

How to replace the call to random.randint() in a function tested with pytest?

I'm new to programming and did search a lot through the questions but couldn't find and answer to my present problem.

I am writing a little game in python 3.8 and use pytest to run some basic tests. One of my tests is about a function using random.randint().

Here's an extract of my program :

import random
...
def hit(self, enemy, attack):
    dmg = random.randint(self.weapon.damage_min, self.weapon.damage_max) + self.strength // 4

hit() does other things after that but the problem is with this first line.

I tried to use monkeypatching to get a fake random number for the test :

def test_player_hit_missed(monkeypatch, monster, hero):
    monkeypatch.setattr('random.randint', -3)
    hero.hit(monster, 'Scream')
    assert monster.life == 55

When I run the test, I get this error :

TypeError: 'int' object is not callable

From what I understand, the monkeypatch did replace randint() by the number I indicated (-3), but then my function hit() did try to call it nonetheless. I thought -3 would replace randint()'s result.

Can someone explain me : - why this doesn't work (I probably haven't correctly understood the behavior of the monkeypatch) ? - and how I can replace the call to random.randint() by the value -3 during the test ?

Thanks




Aucun commentaire:

Enregistrer un commentaire