How to test a function with input call?

Zelphir Kaltstahl picture Zelphir Kaltstahl · Mar 7, 2016 · Viewed 24.6k times · Source

I have a console program written in Python. It asks the user questions using the command:

some_input = input('Answer the question:', ...)

How would I test a function containing a call to input using pytest? I wouldn't want to force a tester to input text many many times only to finish one test run.

Answer

mareoraft picture mareoraft · Apr 2, 2016

As The Compiler suggested, pytest has a new monkeypatch fixture for this. A monkeypatch object can alter an attribute in a class or a value in a dictionary, and then restore its original value at the end of the test.

In this case, the built-in input function is a value of python's __builtins__ dictionary, so we can alter it like so:

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 _: "Mark")

    # go about using input() like you normally would:
    i = input("What is your name?")
    assert i == "Mark"