问题
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?
回答1:
You can mock it:
def test_method(monkeypatch):
monkeypatch.setattr('sys.stdin', io.StringIO('my input'))
# test code
来源:https://stackoverflow.com/questions/38723140/i-want-to-use-stdin-in-a-pytest-test