Skip to content

Instantly share code, notes, and snippets.

@GenevieveBuckley
Last active March 11, 2026 20:37
Show Gist options
  • Select an option

  • Save GenevieveBuckley/efd16862de9e2fe7adfd2bf2bef93e02 to your computer and use it in GitHub Desktop.

Select an option

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
@alexcreek
Copy link
Copy Markdown

💯

@brucestull
Copy link
Copy Markdown

Great solution!

Thanks for sharing! It's much appreciated! This is the best solution for me for now.

@Elena-GHub
Copy link
Copy Markdown

👏🏼👏🏼 Sooooo simple and useful. Thank you so much for sharing 👍🏼 😁

@bruskiza
Copy link
Copy Markdown

bruskiza commented Feb 9, 2022

Who said code can't be art :) Nice one!

@nasimhc
Copy link
Copy Markdown

nasimhc commented Aug 24, 2022

Nice solution, thanks

@Bazzaware
Copy link
Copy Markdown

Nice, clean and simple. Thank you.

@ascrookes
Copy link
Copy Markdown

This is great 🎉

@terencebarrett
Copy link
Copy Markdown

Thank you!

@ZathrasXI
Copy link
Copy Markdown

Excellent, a simple solution to my problem!

@nathannovaes
Copy link
Copy Markdown

Thank you!! Great call!

@morenohernan
Copy link
Copy Markdown

Thank you, pragmatic solution...

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