This question has been asked here Pytest: How to test a function with input call?
But the answer by mareoraft (below) does not work for a function call it only works inside the current test function scope.
original answer:
def test_something_that_involves_user_input(monkeypatch):
# monkeypatch the "input" function, so that it returns "Mark".
# This simulates the user entering "Mark" in the terminal:
monkeypatch.setattr('builtins.input', lambda x: "Mark")
# go about using input() like you normally would:
i = input("What is your name?")
assert i == "Mark"
Here is test code where I moved the input to another function (this fails)
def separate_input_function():
a = input()
return a
def test_separate_function_monkeypatch_input(monkeypatch):
ans = '3'
with monkeypatch.context() as m:
m.setattr('builtins.input', lambda prompt: ans)
result = separate_input_function()
assert result == ans
This raises
TypeError: <lambda>() missing 1 required positional argument: 'prompt'
Any ideas on how to get this to work?
Thanks