2

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!

  • 1
    Have you checked [this](https://stackoverflow.com/questions/35851323/pytest-how-to-test-a-function-with-input-call)? – Samarth Nov 26 '18 at 16:56
  • 1
    I did, I couldn't figure out how it worked. But I mostly understood my program was poorly designed. I do not want to simulate a user input, I just want to select some specific inputs and test outcomes programmatically. Thanks for the help! – Bertrand Chevalier Nov 27 '18 at 04:12

1 Answers1

2

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.

kubablo
  • 83
  • 2
  • 9