How to test a function with input call?

后端 未结 6 1039
野性不改
野性不改 2020-11-29 04:16

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

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

6条回答
  •  抹茶落季
    2020-11-29 04:50

    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"
    

提交回复
热议问题