Reputation: 69
I am brand new to pytest and trying to work my way through it. I currently am programming a small CLI game which will require multiple user inputs in a row and I cannot figure out how I can do that. I read a bunch of solutions but did not manage to make it work.
Here is my code:
class Player:
def __init__(self):
self.set_player_name()
self.set_player_funds()
def set_player_name(self):
self.name = str(input("Player, what's you name?\n"))
def set_player_funds(self):
self.funds = int(input("How much money do you want?\n"))
I simply want to automate the user input for those two requests.
(ie: a test that would input "Bob"
and test: assert player.name=="Bob"
Can someone help out with that? Thank you!
Upvotes: 2
Views: 3702
Reputation: 113
Quite elegant way to test inputs is to mock input text by using monkeypatch
fixture. To handle multiple inputs can be used lambda
statement and iterator object.
def test_set_player_name(monkeypatch):
# provided inputs
name = 'Tranberd'
funds = 100
# creating iterator object
answers = iter([name, str(funds)])
# using lambda statement for mocking
monkeypatch.setattr('builtins.input', lambda name: next(answers))
player = Player()
assert player.name == name
assert player.funds == funds
monkeypatch
on docs.pytest.org.
Iterator object
on wiki.python.org.
Upvotes: 3