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!

asked Nov 25, 2018 at 21:24
2
  • 1
    Have you checked this? Commented Nov 26, 2018 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! Commented Nov 27, 2018 at 4:12

1 Answer 1

3

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.

answered Jun 16, 2021 at 20:05
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.