0

I'm trying to write test code for a python function in Replit. The function is taking user input from the console. As written in the test need to pass a value to the function. Test code:

  self.assertTrue(play(10) <6)

In the Function, user input needs to be taken as below(there are more codes in the function that use num and n to determine return value:

def play(n):

    num = int(input("Enter the ammount"))

  return num

I get the error: RuntimeError: input(): lost sys.stdin

Is there a way to test functions with user inputs in the Replit unit test as the above method is not working?

2 Answers2

1

You can use unittest.mock.patch to patch just about anything under the sun, and that includes built-in functions.

from unittest.mock import patch
with patch('builtins.input', side_effect=['0', '5']):
    self.assertTrue(play(10) < 6)

As pointed out in the comments, your function play should either take an argument (and not call input) or should not take an argument. Right now, you take n but never use it.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • Thanks! I'll try unittest.mock.patch, but can it do both argument and user input? this is the use case I want. We give markets to this exercise so I don't want to add the whole answer here. That is why I deleted not important codes from the play function where I would use the passed parameter and user input to calculate the return value. – Chanya Subasingha Apr 17 '23 at 20:25
  • It worked '''with patch('builtins.input', side_effect=['0', '5']):''' – Chanya Subasingha Apr 17 '23 at 21:54
0
def play(n):
  num = int(input("Enter the ammount"))
  return num

Regarding above function, you need to modify it like,

def play(n):
  return n/2

Thus it becomes clean (even pure). So you can easily test it like

self.assertTrue(play(10) < 6)

Then if you want pass a user provided input to it, just

num = int(input("Enter the ammount"))
play(num)
marmeladze
  • 6,468
  • 3
  • 24
  • 45