Reputation: 3794
The PyTest documentation states that stdin is redirected to null as no-one will want to do interactive testing in a batch test context. This is true, but interactive is not the only use of stdin. I want to test code that uses stdin just as it would use any other file. I am happy with stdout and sterr being captured but how to actually have stdin connected to an io.StringIO object say in a PyTest conformant way?
Upvotes: 46
Views: 12011
Reputation: 38777
You can monkeypatch it:
def test_method(monkeypatch):
monkeypatch.setattr('sys.stdin', io.StringIO('my input'))
# test code
Upvotes: 55
Reputation: 4556
Maybe you could run your script as a subprocess
? In Python 3.6:
import subprocess
def test_a_repl_session():
comlist = ['./executable_script.py']
script = b'input\nlines\n\n'
res = subprocess.run(comlist, input=script,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
assert res.returncode == 0
assert res.stdout
assert res.stderr == b''
Upvotes: 3