Skip to content

Instantly share code, notes, and snippets.

@GenevieveBuckley
Last active December 12, 2023 18:57
Show Gist options
  • Save GenevieveBuckley/efd16862de9e2fe7adfd2bf2bef93e02 to your computer and use it in GitHub Desktop.
Save GenevieveBuckley/efd16862de9e2fe7adfd2bf2bef93e02 to your computer and use it in GitHub Desktop.
Monkeypatching user input with pytest
from io import StringIO
def double():
x = input("Enter an integer: ")
return int(x) * 2
def adding():
x = float(input('Enter the first number'))
y = float(input('Enter the second number'))
return x + y
def test_double(monkeypatch):
number_inputs = StringIO('1234\n')
monkeypatch.setattr('sys.stdin', number_inputs)
assert double() == 2468
def test_adding(monkeypatch):
number_inputs = StringIO('2\n3\n')
monkeypatch.setattr('sys.stdin', number_inputs)
assert adding() == 5
@morenohernan
Copy link

Thank you, pragmatic solution...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment