Pytest: How to test a separate function with input call?

Pytest: How to test a separate function with input call?



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




2 Answers
2



Your problem has nothing to do with moving the input to a separate function, or even with monkeypatching; it has to do with passing the wrong number of arguments—just as the error message says.


input



In the example you refer to, the monkeypatching function is defined to take one parameter, and the input call passes one argument.


input



If your own attempt, the monkeypatching function is defined to take one parameter, but the input call passes no arguments.


input



You can just define it to take an optional parameter, just like the real input:


m.setattr('builtins.input', lambda prompt="": ans)



An alternative to patching is a technique called "dependency injection":


def separate_input_function(_input=input):
a = _input()
return a

def test_separate_function_monkeypatch_input(monkeypatch):
_input = lambda: 42
result = separate_input_function(_input=_input)
assert result == 42



Maybe this helps.



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)