0

I would like to test the following Python function using pytest:

def increase_by_one()
    n = int(input())
    return n + 1

How can I write to the stdin/user input request within a function, for testing purposes?

itsafox
  • 71
  • 2
  • 5
  • Where possible, replace calls to `input` with function parameters. It makes your function easier to test, and pushes I/O towards the "edge" of your program. – chepner Jun 25 '20 at 12:00

1 Answers1

0

You can write your own input() function which will return a fix string.

save_it = input
input = lambda: 'your_simulated_input'
def test():
    s = input() # returns 'your_simulated_input'
    ...
Alexander Kosik
  • 669
  • 3
  • 10
  • `input` is in the built-in scope. You don't necessarily need to save the reference; it will always be available via `builtins.input`, and you can simply use `del input` to stop shadowing the builtin name. – chepner Jun 25 '20 at 11:58
  • thank's for the hint – Alexander Kosik Jun 25 '20 at 12:01