Answering to help OP as there is a slightly difference between this and the linked duplicate (although I'd still suggest this is a duplicate that should be closed). The input here is being run at the module scope - so will execute when first loaded. i.e. simpleScript.py
will ask for input when it is first called by import
.
To do this in a test scenario, I'd firstly recommend to change this so that simpleScript.py provides a function that can be run. That way - the same solutions as the duplicates provide can be used.
But for this specific case where simpleScript.py
does directly execute code, we can test the functionality with a test script below:
from unittest.mock import patch
from io import StringIO
@patch("sys.stdin", StringIO("1\n4"))
def test_simpleScript():
import simpleScript
test_simpleScript()
This works by mocking the stdin
(commandline input) to return 1, a new line then 4. Because of how input
works with stdin
this will return 1 on the first call to input
and then 4
on the next call.
When we import
the simpleScript
module - all the code in it is executed. Because of the above mock patch we did, any calls to input
during this will read the numbers we have given it. As the module only executes the first time it is loaded - you may have issues if you try multiple tests one after another. See here for how to force a module to reload if that is the case: How do I unload (reload) a Python module?